1 /*******************************************************************************
2 * ============LICENSE_START==================================================
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
11 * * http://www.apache.org/licenses/LICENSE-2.0
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====================================================
20 * * ECOMP is a trademark and service mark of AT&T Intellectual Property.
22 ******************************************************************************/
23 package org.onap.dmaap.datarouter.node;
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;
35 import ch.qos.logback.classic.Logger;
36 import ch.qos.logback.classic.spi.ILoggingEvent;
37 import ch.qos.logback.core.read.ListAppender;
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;
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 {
64 private NodeServlet nodeServlet;
65 private Delivery delivery;
68 private HttpServletRequest request;
71 private HttpServletResponse response;
73 private ListAppender<ILoggingEvent> listAppender;
75 private NodeConfigManager config = mock(NodeConfigManager.class);
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();
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");
94 public static void tearDown() {
95 deleteCreatedDirectories();
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);
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);
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);
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);
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);
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);
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);
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);
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);
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);
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);
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);
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);
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);
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());
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());
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);
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());
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);
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);
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);
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);
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);
295 private void setBehalfHeader(String headerValue) {
296 when(request.getHeader("X-DMAAP-DR-ON-BEHALF-OF")).thenReturn(headerValue);
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);
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());
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);
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);
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);
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);
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);
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);
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);
389 private String createLargeMetaDataString() {
390 StringBuilder myString = new StringBuilder("meta");
391 for (int i = 0; i <= 4098; ++i) {
392 myString.append('x');
394 return myString.toString();
397 private void setHeadersForValidRequest(boolean isMetaTooLong) {
398 String metaDataString;
400 metaDataString = createLargeMetaDataString();
402 metaDataString = "?#@><";
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);
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");
425 dataFile.createNewFile();
426 metaDataFile.createNewFile();
429 private static void deleteCreatedDirectories() {
430 File spoolDir = new File("spool");
434 private static void delete(File file) {
435 if (file.isDirectory()) {
436 for (File f: file.listFiles()) {
440 if (!file.delete()) {
441 System.out.println("Failed to delete: " + file);