[DMaaP DR] JKD 11 migration
[dmaap/datarouter.git] / datarouter-node / src / test / java / org / onap / dmaap / datarouter / node / NodeServletTest.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.node;
24
25 import static org.junit.Assert.assertEquals;
26 import static org.mockito.ArgumentMatchers.any;
27 import static org.mockito.ArgumentMatchers.anyObject;
28 import static org.mockito.ArgumentMatchers.eq;
29 import static org.mockito.Mockito.anyString;
30 import static org.mockito.Mockito.doNothing;
31 import static org.mockito.Mockito.mock;
32 import static org.mockito.Mockito.verify;
33 import static org.mockito.Mockito.when;
34
35 import ch.qos.logback.classic.Logger;
36 import ch.qos.logback.classic.spi.ILoggingEvent;
37 import ch.qos.logback.core.read.ListAppender;
38 import java.io.File;
39 import java.io.IOException;
40 import java.util.ArrayList;
41 import java.util.Arrays;
42 import java.util.Collections;
43 import java.util.Enumeration;
44 import java.util.List;
45 import javax.servlet.http.HttpServletRequest;
46 import javax.servlet.http.HttpServletResponse;
47 import org.apache.commons.lang3.reflect.FieldUtils;
48 import org.junit.AfterClass;
49 import org.junit.Before;
50 import org.junit.Test;
51 import org.junit.runner.RunWith;
52 import org.mockito.Mock;
53 import org.powermock.api.mockito.PowerMockito;
54 import org.powermock.core.classloader.annotations.PowerMockIgnore;
55 import org.powermock.core.classloader.annotations.SuppressStaticInitializationFor;
56 import org.powermock.modules.junit4.PowerMockRunner;
57 import org.slf4j.LoggerFactory;
58
59 @RunWith(PowerMockRunner.class)
60 @SuppressStaticInitializationFor("org.onap.dmaap.datarouter.node.NodeConfigManager")
61 @PowerMockIgnore({"com.sun.org.apache.xerces.*", "javax.xml.*", "org.xml.*", "org.w3c.*"})
62 public class NodeServletTest {
63
64     private NodeServlet nodeServlet;
65     private Delivery delivery;
66
67     @Mock
68     private HttpServletRequest request;
69
70     @Mock
71     private HttpServletResponse response;
72
73     private ListAppender<ILoggingEvent> listAppender;
74
75     private NodeConfigManager config = mock(NodeConfigManager.class);
76
77     @Before
78     public void setUp() throws Exception {
79         listAppender = setTestLogger();
80         setBehalfHeader("Stub_Value");
81         when(request.getPathInfo()).thenReturn("2");
82         when(request.isSecure()).thenReturn(true);
83         createFilesAndDirectories();
84         setUpConfig();
85         setUpNodeMainDelivery();
86         delivery = mock(Delivery.class);
87         when(delivery.markTaskSuccess("spool/s/0/1", "dmaap-dr-node.1234567")).thenReturn(true);
88         nodeServlet = new NodeServlet(delivery);
89         when(request.getHeader("Authorization")).thenReturn("User1");
90         when(request.getHeader("X-DMAAP-DR-PUBLISH-ID")).thenReturn("User1");
91     }
92
93     @AfterClass
94     public static void tearDown() {
95         deleteCreatedDirectories();
96     }
97
98     @Test
99     public void Given_Request_Is_HTTP_GET_And_Config_Is_Down_Then_Service_Unavailable_Response_Is_Generated() throws Exception {
100         setNodeConfigManagerIsConfiguredToReturnFalse();
101         nodeServlet.doGet(request, response);
102         verify(response).sendError(eq(HttpServletResponse.SC_SERVICE_UNAVAILABLE));
103         verifyEnteringExitCalled(listAppender);
104     }
105
106     @Test
107     public void Given_Request_Is_HTTP_GET_And_Endpoint_Is_Internal_FetchProv_Then_No_Content_Response_Is_Generated() {
108         when(request.getPathInfo()).thenReturn("/internal/fetchProv");
109         nodeServlet.doGet(request, response);
110         verify(response).setStatus(eq(HttpServletResponse.SC_NO_CONTENT));
111         verifyEnteringExitCalled(listAppender);
112     }
113
114     @Test
115     public void Given_Request_Is_HTTP_GET_And_Endpoint_Is_ResetSubscription_Then_No_Content_Response_Is_Generated() {
116         when(request.getPathInfo()).thenReturn("/internal/resetSubscription/1");
117         nodeServlet.doGet(request, response);
118         verify(response).setStatus(eq(HttpServletResponse.SC_NO_CONTENT));
119         verifyEnteringExitCalled(listAppender);
120     }
121
122     @Test
123     public void Given_Request_Is_HTTP_GET_To_Invalid_Endpoint_Then_Not_Found_Response_Is_Generated() throws Exception {
124         when(request.getPathInfo()).thenReturn("/incorrect");
125         nodeServlet.doGet(request, response);
126         verify(response).sendError(eq(HttpServletResponse.SC_NOT_FOUND));
127         verifyEnteringExitCalled(listAppender);
128     }
129
130     @Test
131     public void Given_Request_Is_HTTP_PUT_And_Config_Is_Down_Then_Service_Unavailable_Response_Is_Generated() throws Exception {
132         setNodeConfigManagerIsConfiguredToReturnFalse();
133         nodeServlet.doPut(request, response);
134         verify(response).sendError(eq(HttpServletResponse.SC_SERVICE_UNAVAILABLE));
135         verifyEnteringExitCalled(listAppender);
136     }
137
138     @Test
139     public void Given_Request_Is_HTTP_PUT_And_Endpoint_Is_Incorrect_Then_Not_Found_Response_Is_Generated() throws Exception {
140         when(request.getPathInfo()).thenReturn("/incorrect/");
141         nodeServlet.doPut(request, response);
142         verify(response).sendError(eq(HttpServletResponse.SC_NOT_FOUND), anyString());
143         verifyEnteringExitCalled(listAppender);
144     }
145
146     @Test
147     public void Given_Request_Is_HTTP_PUT_And_Request_Is_Not_Secure_Then_Forbidden_Response_Is_Generated() throws Exception {
148         when(request.isSecure()).thenReturn(false);
149         nodeServlet.doPut(request, response);
150         verify(response).sendError(eq(HttpServletResponse.SC_FORBIDDEN), anyString());
151         verifyEnteringExitCalled(listAppender);
152     }
153
154     @Test
155     public void Given_Request_Is_HTTP_PUT_And_File_Id_Is_Null_Then_Not_Found_Response_Is_Generated() throws Exception {
156         when(request.getPathInfo()).thenReturn(null);
157         nodeServlet.doPut(request, response);
158         verify(response).sendError(eq(HttpServletResponse.SC_NOT_FOUND), anyString());
159         verifyEnteringExitCalled(listAppender);
160     }
161
162     @Test
163     public void Given_Request_Is_HTTP_PUT_And_Authorization_Is_Null_Then_Forbidden_Response_Is_Generated() throws Exception {
164         when(request.getHeader("Authorization")).thenReturn(null);
165         nodeServlet.doPut(request, response);
166         verify(response).sendError(eq(HttpServletResponse.SC_FORBIDDEN), anyString());
167         verifyEnteringExitCalled(listAppender);
168     }
169
170     @Test
171     public void Given_Request_Is_HTTP_PUT_And_Publish_Does_Not_Include_File_Id_Then_Not_Found_Response_Is_Generated() throws Exception {
172         when(request.getPathInfo()).thenReturn("/publish/");
173         nodeServlet.doPut(request, response);
174         verify(response).sendError(eq(HttpServletResponse.SC_NOT_FOUND), anyString());
175         verifyEnteringExitCalled(listAppender);
176     }
177
178     @Test
179     public void Given_Request_Is_HTTP_PUT_And_Publish_Not_Permitted_Then_Forbidden_Response_Is_Generated() throws Exception {
180         when(request.getPathInfo()).thenReturn("/publish/1/fileName");
181         when(request.getRemoteAddr()).thenReturn("1.2.3.4");
182         setNodeConfigManagerIsPublishPermittedToReturnAReason();
183         nodeServlet.doPut(request, response);
184         verify(response).sendError(eq(HttpServletResponse.SC_FORBIDDEN), anyString());
185         verifyEnteringExitCalled(listAppender);
186     }
187
188     @Test
189     public void Given_Request_Is_HTTP_PUT_And_Internal_Publish_On_Same_Node_Then_Forbidden_Response_Is_Generated() throws Exception {
190         when(request.getPathInfo()).thenReturn("/internal/publish/1/fileName");
191         setNodeConfigManagerIsPublishPermittedToReturnAReason();
192         nodeServlet.doPut(request, response);
193         verify(response).sendError(eq(HttpServletResponse.SC_FORBIDDEN));
194         verifyEnteringExitCalled(listAppender);
195     }
196
197     @Test
198     public void Given_Request_Is_HTTP_PUT_And_Internal_Publish_But_Invalid_File_Id_Then_Not_Found_Response_Is_Generated() throws Exception {
199         when(request.getPathInfo()).thenReturn("/internal/publish/1/blah");
200         when(request.getRemoteAddr()).thenReturn("1.2.3.4");
201         when(config.isAnotherNode(anyString(), anyString())).thenReturn(true);
202         nodeServlet.doPut(request, response);
203         verify(response).sendError(eq(HttpServletResponse.SC_NOT_FOUND), anyString());
204         verifyEnteringExitCalled(listAppender);
205     }
206
207     @Test
208     public void Given_Request_Is_HTTP_PUT_On_Publish_And_Ingress_Node_Is_Provided_Then_Request_Is_Redirected() throws Exception {
209         setNodeConfigManagerToAllowRedirectOnIngressNode();
210         when(request.getPathInfo()).thenReturn("/publish/1/fileName");
211         when(request.getRemoteAddr()).thenReturn("1.2.3.4");
212         nodeServlet.doPut(request, response);
213         verify(response).sendRedirect(anyString());
214         verifyEnteringExitCalled(listAppender);
215     }
216
217     @Test
218     public void Given_Request_Is_HTTP_PUT_On_Publish_With_Meta_Data_Too_Long_Then_Bad_Request_Response_Is_Generated() throws Exception {
219         when(request.getPathInfo()).thenReturn("/publish/1/fileName");
220         setHeadersForValidRequest(true);
221         nodeServlet.doPut(request, response);
222         verify(response).sendError(eq(HttpServletResponse.SC_BAD_REQUEST), anyString());
223     }
224
225     @Test
226     public void Given_Request_Is_HTTP_PUT_On_Publish_With_Meta_Data_Malformed_Then_Bad_Request_Response_Is_Generated() throws Exception {
227         when(request.getPathInfo()).thenReturn("/publish/1/fileName");
228         setHeadersForValidRequest(false);
229         nodeServlet.doPut(request, response);
230         verify(response).sendError(eq(HttpServletResponse.SC_BAD_REQUEST), anyString());
231     }
232
233     @Test
234     public void Given_Request_Is_HTTP_PUT_On_Publish_On_AAF_Feed_And_Cadi_Enabled_And_No_Permissions_Then_Forbidden_Response_Is_Generated() throws Exception {
235         when(config.getCadiEnabled()).thenReturn(true);
236         when(config.getAafInstance("1")).thenReturn("*");
237         when(request.getPathInfo()).thenReturn("/publish/1/fileName");
238         setHeadersForValidRequest(true);
239         nodeServlet.doPut(request, response);
240         verify(response).sendError(eq(HttpServletResponse.SC_FORBIDDEN), anyString());
241         verifyEnteringExitCalled(listAppender);
242     }
243
244     @Test
245     public void Given_Request_Is_HTTP_DELETE_On_Publish_With_Meta_Data_Malformed_Then_Bad_Request_Response_Is_Generated() throws Exception {
246         when(request.getPathInfo()).thenReturn("/publish/1/fileName");
247         setHeadersForValidRequest(false);
248         nodeServlet.doDelete(request, response);
249         verify(response).sendError(eq(HttpServletResponse.SC_BAD_REQUEST), anyString());
250     }
251
252     @Test
253     public void Given_Request_Is_HTTP_DELETE_File_With_Invalid_Endpoint_Then_Not_Found_Response_Is_Generated() throws Exception {
254         when(request.getPathInfo()).thenReturn("/delete/1");
255         nodeServlet.doDelete(request, response);
256         verify(response).sendError(eq(HttpServletResponse.SC_NOT_FOUND), anyString());
257         verifyEnteringExitCalled(listAppender);
258     }
259
260     @Test
261     public void Given_Request_Is_HTTP_DELETE_File_And_Is_Not_Privileged_Subscription_Then_Not_Found_Response_Is_Generated() throws Exception {
262         when(request.getPathInfo()).thenReturn("/delete/1/dmaap-dr-node.1234567");
263         setUpConfigToReturnUnprivilegedSubscriber();
264         nodeServlet.doDelete(request, response);
265         verify(response).sendError(eq(HttpServletResponse.SC_UNAUTHORIZED));
266         verifyEnteringExitCalled(listAppender);
267     }
268
269     @Test
270     public void Given_Request_Is_HTTP_DELETE_File_And_Subscription_Does_Not_Exist_Then_Not_Found_Response_Is_Generated() throws Exception {
271         when(request.getPathInfo()).thenReturn("/delete/1/dmaap-dr-node.1234567");
272         setUpConfigToReturnNullOnIsDeletePermitted();
273         nodeServlet.doDelete(request, response);
274         verify(response).sendError(eq(HttpServletResponse.SC_NOT_FOUND));
275         verifyEnteringExitCalled(listAppender);
276     }
277
278     @Test
279     public void Given_Request_Is_HTTP_DELETE_File_Then_Request_Succeeds() throws Exception {
280         when(request.getPathInfo()).thenReturn("/delete/1/dmaap-dr-node.1234567");
281         createFilesAndDirectories();
282         nodeServlet.doDelete(request, response);
283         verify(response).setStatus(eq(HttpServletResponse.SC_OK));
284         verifyEnteringExitCalled(listAppender);
285     }
286
287     @Test
288     public void Given_Request_Is_HTTP_DELETE_File_And_File_Does_Not_Exist_Then_Not_Found_Response_Is_Generated() throws IOException {
289         when(request.getPathInfo()).thenReturn("/delete/1/nonExistingFile");
290         nodeServlet.doDelete(request, response);
291         verify(response).sendError(eq(HttpServletResponse.SC_NOT_FOUND), anyString());
292         verifyEnteringExitCalled(listAppender);
293     }
294
295     private void setBehalfHeader(String headerValue) {
296         when(request.getHeader("X-DMAAP-DR-ON-BEHALF-OF")).thenReturn(headerValue);
297     }
298
299     private ListAppender<ILoggingEvent> setTestLogger() {
300         Logger Logger = (Logger) LoggerFactory.getLogger(NodeServlet.class);
301         ListAppender<ILoggingEvent> listAppender = new ListAppender<>();
302         listAppender.start();
303         Logger.addAppender(listAppender);
304         return listAppender;
305     }
306
307     private void verifyEnteringExitCalled(ListAppender<ILoggingEvent> listAppender) {
308         assertEquals("EELF0004I  Entering data router node component with RequestId and InvocationId", listAppender.list.get(0).getMessage());
309         assertEquals("EELF0005I  Exiting data router node component with RequestId and InvocationId", listAppender.list.get(listAppender.list.size() -1).getMessage());
310     }
311
312     private void setUpConfig() throws IllegalAccessException {
313         PowerMockito.mockStatic(NodeConfigManager.class);
314         when(config.isShutdown()).thenReturn(false);
315         when(config.isConfigured()).thenReturn(true);
316         when(config.getSpoolDir()).thenReturn("spool/f");
317         when(config.getSpoolBase()).thenReturn("spool");
318         when(config.getLogDir()).thenReturn("log/dir");
319         when(config.getPublishId()).thenReturn("User1");
320         when(config.isAnotherNode(anyString(), anyString())).thenReturn(false);
321         when(config.getEventLogInterval()).thenReturn("40");
322         when(config.isDeletePermitted("1")).thenReturn(true);
323         when(config.getAllDests()).thenReturn(new DestInfo[0]);
324         FieldUtils.writeDeclaredStaticField(NodeServlet.class, "config", config, true);
325         FieldUtils.writeDeclaredStaticField(NodeRunner.class, "nodeConfigManager", config, true);
326         PowerMockito.when(NodeConfigManager.getInstance()).thenReturn(config);
327     }
328
329     private void setUpConfigToReturnUnprivilegedSubscriber() throws IllegalAccessException {
330         NodeConfigManager config = mock(NodeConfigManager.class);
331         PowerMockito.mockStatic(NodeConfigManager.class);
332         when(config.isShutdown()).thenReturn(false);
333         when(config.isConfigured()).thenReturn(true);
334         when(config.isDeletePermitted("1")).thenReturn(false);
335         FieldUtils.writeDeclaredStaticField(NodeServlet.class, "config", config, true);
336         FieldUtils.writeDeclaredStaticField(NodeRunner.class, "nodeConfigManager", config, true);
337         PowerMockito.when(NodeConfigManager.getInstance()).thenReturn(config);
338     }
339
340     private void setUpConfigToReturnNullOnIsDeletePermitted() throws IllegalAccessException {
341         NodeConfigManager config = mock(NodeConfigManager.class);
342         PowerMockito.mockStatic(NodeConfigManager.class);
343         when(config.isShutdown()).thenReturn(false);
344         when(config.isConfigured()).thenReturn(true);
345         when(config.isDeletePermitted("1")).thenThrow(new NullPointerException());
346         FieldUtils.writeDeclaredStaticField(NodeServlet.class, "config", config, true);
347         FieldUtils.writeDeclaredStaticField(NodeRunner.class, "nodeConfigManager", config, true);
348         PowerMockito.when(NodeConfigManager.getInstance()).thenReturn(config);
349     }
350
351     private void setUpNodeMainDelivery() throws IllegalAccessException{
352         Delivery delivery = mock(Delivery.class);
353         doNothing().when(delivery).resetQueue(anyObject());
354         FieldUtils.writeDeclaredStaticField(NodeServer.class, "delivery", delivery, true);
355     }
356
357     private void setNodeConfigManagerIsConfiguredToReturnFalse() throws IllegalAccessException{
358         NodeConfigManager config = mock(NodeConfigManager.class);
359         when(config.isConfigured()).thenReturn(false);
360         FieldUtils.writeDeclaredStaticField(NodeServlet.class, "config", config, true);
361     }
362
363     private void setNodeConfigManagerIsPublishPermittedToReturnAReason() throws IllegalAccessException{
364         NodeConfigManager config = mock(NodeConfigManager.class);
365         when(config.isShutdown()).thenReturn(false);
366         when(config.getMyName()).thenReturn("dmaap-dr-node");
367         when(config.isConfigured()).thenReturn(true);
368         when(config.getSpoolDir()).thenReturn("spool/dir");
369         when(config.getLogDir()).thenReturn("log/dir");
370         when(config.isPublishPermitted(anyString(), anyString(), anyString())).thenReturn("Publisher not permitted for this feed");
371         when(config.isAnotherNode(anyString(), anyString())).thenReturn(false);
372         FieldUtils.writeDeclaredStaticField(NodeServlet.class, "config", config, true);
373     }
374
375     private void setNodeConfigManagerToAllowRedirectOnIngressNode() throws IllegalAccessException{
376         NodeConfigManager config = mock(NodeConfigManager.class);
377         when(config.isShutdown()).thenReturn(false);
378         when(config.isConfigured()).thenReturn(true);
379         when(config.getSpoolDir()).thenReturn("spool/dir");
380         when(config.getLogDir()).thenReturn("log/dir");
381         when(config.getPublishId()).thenReturn("User1");
382         when(config.isAnotherNode(anyString(), anyString())).thenReturn(true);
383         when(config.getAuthUser(anyString(), anyString())).thenReturn("User1");
384         when(config.getIngressNode(anyString(), anyString(), anyString())).thenReturn("NewNode");
385         when(config.getExtHttpsPort()).thenReturn(8080);
386         FieldUtils.writeDeclaredStaticField(NodeServlet.class, "config", config, true);
387     }
388
389     private String createLargeMetaDataString() {
390         StringBuilder myString = new StringBuilder("meta");
391         for (int i = 0; i <= 4098; ++i) {
392             myString.append('x');
393         }
394         return myString.toString();
395     }
396
397     private void setHeadersForValidRequest(boolean isMetaTooLong) {
398         String metaDataString;
399         if (isMetaTooLong) {
400             metaDataString = createLargeMetaDataString();
401         } else {
402             metaDataString = "?#@><";
403         }
404         List<String> headers = new ArrayList<>();
405         headers.add("Content-Type");
406         headers.add("X-DMAAP-DR-ON-BEHALF-OF");
407         headers.add("X-DMAAP-DR-META");
408         Enumeration<String> headerNames = Collections.enumeration(headers);
409         when(request.getHeaderNames()).thenReturn(headerNames);
410         Enumeration<String> contentTypeHeader = Collections.enumeration(Arrays.asList("text/plain"));
411         Enumeration<String> behalfHeader = Collections.enumeration(Arrays.asList("User1"));
412         Enumeration<String> metaDataHeader = Collections.enumeration(Arrays.asList(metaDataString));
413         when(request.getHeaders("Content-Type")).thenReturn(contentTypeHeader);
414         when(request.getHeaders("X-DMAAP-DR-ON-BEHALF-OF")).thenReturn(behalfHeader);
415         when(request.getHeaders("X-DMAAP-DR-META")).thenReturn(metaDataHeader);
416     }
417
418     private void createFilesAndDirectories() throws IOException {
419         File nodeDir = new File("spool/n/172.0.0.1");
420         File spoolDir = new File("spool/s/0/1");
421         File dataFile = new File("spool/s/0/1/dmaap-dr-node.1234567");
422         File metaDataFile = new File("spool/s/0/1/dmaap-dr-node.1234567.M");
423         nodeDir.mkdirs();
424         spoolDir.mkdirs();
425         dataFile.createNewFile();
426         metaDataFile.createNewFile();
427     }
428
429     private static void deleteCreatedDirectories() {
430         File spoolDir = new File("spool");
431         delete(spoolDir);
432     }
433
434     private static void delete(File file) {
435         if (file.isDirectory()) {
436             for (File f: file.listFiles()) {
437                 delete(f);
438             }
439         }
440         if (!file.delete()) {
441             System.out.println("Failed to delete: " + file);
442         }
443     }
444 }