More DR unit tests and code cleanup
[dmaap/datarouter.git] / datarouter-prov / src / test / java / org / onap / dmaap / datarouter / provisioning / BaseServletTest.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
24 package org.onap.dmaap.datarouter.provisioning;
25
26 import java.security.NoSuchAlgorithmException;
27 import javax.crypto.SecretKeyFactory;
28 import org.apache.commons.lang3.reflect.FieldUtils;
29 import org.jetbrains.annotations.NotNull;
30 import org.json.JSONArray;
31 import org.json.JSONObject;
32 import org.junit.Assert;
33 import org.junit.Before;
34 import org.junit.Test;
35 import org.junit.runner.RunWith;
36 import org.mockito.Mock;
37 import org.mockito.Mockito;
38 import org.onap.dmaap.datarouter.provisioning.beans.Feed;
39 import org.onap.dmaap.datarouter.provisioning.beans.FeedAuthorization;
40 import org.onap.dmaap.datarouter.provisioning.beans.Group;
41 import org.onap.dmaap.datarouter.provisioning.beans.Subscription;
42 import org.powermock.api.mockito.PowerMockito;
43 import org.powermock.core.classloader.annotations.PowerMockIgnore;
44 import org.powermock.core.classloader.annotations.PrepareForTest;
45 import org.powermock.core.classloader.annotations.SuppressStaticInitializationFor;
46 import org.powermock.modules.junit4.PowerMockRunner;
47 import org.slf4j.MDC;
48
49 import javax.servlet.http.HttpServletRequest;
50 import java.util.HashSet;
51 import java.util.Set;
52 import java.util.UUID;
53
54 import static org.hamcrest.Matchers.is;
55 import static org.hamcrest.Matchers.nullValue;
56 import static org.junit.Assert.assertEquals;
57 import static org.junit.Assert.assertNull;
58 import static org.junit.Assert.assertThat;
59 import static org.mockito.Matchers.anyInt;
60 import static org.mockito.Mockito.mock;
61 import static org.mockito.Mockito.when;
62 import static org.powermock.api.mockito.PowerMockito.mockStatic;
63
64 @RunWith(PowerMockRunner.class)
65 @SuppressStaticInitializationFor({"org.onap.dmaap.datarouter.provisioning.beans.Feed",
66         "org.onap.dmaap.datarouter.provisioning.beans.Subscription",
67         "org.onap.dmaap.datarouter.provisioning.beans.Group"})
68 @PowerMockIgnore({"javax.crypto.*"})
69 @PrepareForTest({UUID.class, SecretKeyFactory.class})
70 public class BaseServletTest extends DrServletTestBase {
71
72     private BaseServlet baseServlet;
73
74     @Mock
75     private HttpServletRequest request;
76
77     @Before
78     public void setUp() throws Exception {
79         super.setUp();
80         baseServlet = new BaseServlet();
81     }
82
83
84     @Test
85     public void Given_Request_Path_Info_Is_Valid_Then_Id_Is_Extracted_Correctly() {
86         when(request.getPathInfo()).thenReturn("/123");
87         assertThat(BaseServlet.getIdFromPath(request), is(123));
88     }
89
90     @Test
91     public void Given_Request_Path_Info_Is_Not_Valid_Then_Minus_One_Is_Returned() {
92         when(request.getPathInfo()).thenReturn("/abc");
93         assertThat(BaseServlet.getIdFromPath(request), is(-1));
94         when(request.getPathInfo()).thenReturn("/");
95         assertThat(BaseServlet.getIdFromPath(request), is(-1));
96     }
97
98     @Test
99     public void Given_Remote_Address_Is_Known_And_RequireCerts_Is_True() throws Exception {
100         when(request.isSecure()).thenReturn(true);
101         Set<String> authAddressesAndNetworks = new HashSet<>();
102         authAddressesAndNetworks.add(("127.0.0.1"));
103         FieldUtils.writeDeclaredStaticField(BaseServlet.class, "authorizedAddressesAndNetworks", authAddressesAndNetworks, true);
104         FieldUtils.writeDeclaredStaticField(BaseServlet.class, "requireCert", true, true);
105         assertNull(baseServlet.isAuthorizedForProvisioning(request));
106     }
107
108     @Test
109     public void Given_Request_Is_GetFeedOwner_And_Feed_Exists() {
110         PowerMockito.mockStatic(Feed.class);
111         Feed feed = mock(Feed.class);
112         PowerMockito.when(Feed.getFeedById(anyInt())).thenReturn(feed);
113         when(feed.getPublisher()).thenReturn("stub_publisher");
114         assertThat(baseServlet.getFeedOwner("3"), is("stub_publisher"));
115     }
116
117     @Test
118     public void Given_Request_Is_GetFeedOwner_And_Feed_Does_Not_Exist(){
119         PowerMockito.mockStatic(Feed.class);
120         PowerMockito.when(Feed.getFeedById(anyInt())).thenReturn(null);
121         assertThat(baseServlet.getFeedOwner("3"), is(nullValue()));
122     }
123
124     @Test
125     public void Given_Request_Is_GetFeedClassification_And_Feed_Exists(){
126         PowerMockito.mockStatic(Feed.class);
127         Feed feed = mock(Feed.class);
128         PowerMockito.when(Feed.getFeedById(anyInt())).thenReturn(feed);
129         FeedAuthorization fAuth = mock(FeedAuthorization.class);
130         when(feed.getAuthorization()).thenReturn(fAuth);
131         when(fAuth.getClassification()).thenReturn("stub_classification");
132         assertThat(baseServlet.getFeedClassification("3"), is("stub_classification"));
133     }
134
135     @Test
136     public void Given_Request_Is_GetFeedClassification_And_Feed_Does_Not_Exist() {
137         PowerMockito.mockStatic(Feed.class);
138         PowerMockito.when(Feed.getFeedById(anyInt())).thenReturn(null);
139         assertThat(baseServlet.getFeedClassification("3"), is(nullValue()));
140     }
141
142     @Test
143     public void Given_Request_Is_GetSubscriptionOwner_And_Subscription_Exists() {
144         PowerMockito.mockStatic(Subscription.class);
145         Subscription subscription = mock(Subscription.class);
146         PowerMockito.when(Subscription.getSubscriptionById(anyInt())).thenReturn(subscription);
147         when(subscription.getSubscriber()).thenReturn("stub_subscriber");
148         assertThat(baseServlet.getSubscriptionOwner("3"), is("stub_subscriber"));
149     }
150
151     @Test
152     public void Given_Request_Is_GetSubscriptionOwner_And_Subscription_Does_Not_Exist() {
153         PowerMockito.mockStatic(Subscription.class);
154         PowerMockito.when(Subscription.getSubscriptionById(anyInt())).thenReturn(null);
155         assertThat(baseServlet.getSubscriptionOwner("3"), is(nullValue()));
156     }
157
158     @Test
159     public void Given_Request_Is_GetGroupByFeedGroupId_And_User_Is_A_Member_Of_Group() {
160         PowerMockito.mockStatic(Feed.class);
161         Feed feed = mock(Feed.class);
162         PowerMockito.when(Feed.getFeedById(anyInt())).thenReturn(feed);
163         when(feed.getGroupid()).thenReturn(3);
164         PowerMockito.mockStatic(Group.class);
165         Group group = mock(Group.class);
166         when(group.getMembers()).thenReturn("{id: stub_user}");
167         PowerMockito.when(Group.getGroupById(anyInt())).thenReturn(group);
168         when(group.getAuthid()).thenReturn("stub_authID");
169         assertThat(baseServlet.getGroupByFeedGroupId("stub_user", "3"), is("stub_authID"));
170     }
171
172     @Test
173     public void Given_Request_Is_GetGroupByFeedGroupId_And_User_Is_Not_A_Member_Of_Group() {
174         PowerMockito.mockStatic(Feed.class);
175         Feed feed = mock(Feed.class);
176         PowerMockito.when(Feed.getFeedById(anyInt())).thenReturn(feed);
177         when(feed.getGroupid()).thenReturn(3);
178         PowerMockito.mockStatic(Group.class);
179         Group group = mock(Group.class);
180         when(group.getMembers()).thenReturn("{id: stub_otherUser}");
181         PowerMockito.when(Group.getGroupById(anyInt())).thenReturn(group);
182         when(group.getAuthid()).thenReturn("stub_authID");
183         assertThat(baseServlet.getGroupByFeedGroupId("stub_user", "3"), is(nullValue()));
184     }
185
186     @Test
187     public void Given_Request_Is_GetGroupBySubGroupId_And_User_Is_A_Member_Of_Group() {
188         PowerMockito.mockStatic(Subscription.class);
189         Subscription subscription = mock(Subscription.class);
190         PowerMockito.when(Subscription.getSubscriptionById(anyInt())).thenReturn(subscription);
191         when(subscription.getGroupid()).thenReturn(3);
192         PowerMockito.mockStatic(Group.class);
193         Group group = mock(Group.class);
194         when(group.getMembers()).thenReturn("{id: stub_user}");
195         PowerMockito.when(Group.getGroupById(anyInt())).thenReturn(group);
196         when(group.getAuthid()).thenReturn("stub_authID");
197         assertThat(baseServlet.getGroupBySubGroupId("stub_user", "3"), is("stub_authID"));
198     }
199
200     @Test
201     public void Given_Request_Is_GetGroupBySubGroupId_And_User_Is_Not_A_Member_Of_Group() {
202         PowerMockito.mockStatic(Subscription.class);
203         Subscription subscription = mock(Subscription.class);
204         PowerMockito.when(Subscription.getSubscriptionById(anyInt())).thenReturn(subscription);
205         when(subscription.getGroupid()).thenReturn(3);
206         PowerMockito.mockStatic(Group.class);
207         Group group = mock(Group.class);
208         when(group.getMembers()).thenReturn("{id: stub_otherUser}");
209         PowerMockito.when(Group.getGroupById(anyInt())).thenReturn(group);
210         when(group.getAuthid()).thenReturn("stub_authID");
211         assertThat(baseServlet.getGroupBySubGroupId("stub_user", "3"), is(nullValue()));
212     }
213
214     @Test
215     public void Given_Request_Has_Empty_RequestId_And_InvocationId_Headers_Generate_MDC_Values() {
216         when(request.getHeader("X-ONAP-RequestID")).thenReturn("");
217         when(request.getHeader("X-InvocationID")).thenReturn("");
218         mockStatic(UUID.class);
219         when(UUID.randomUUID().toString()).thenReturn("123", "456");
220         baseServlet.setIpFqdnRequestIDandInvocationIDForEelf("doDelete", request);
221         Assert.assertNotEquals("123", MDC.get("RequestId"));
222         Assert.assertNotEquals("456", MDC.get("InvocationId"));
223     }
224
225     @Test
226     public void Given_Request_Has_RequestId_And_InvocationId_Headers_Set_MDC_Values() {
227         when(request.getHeader("X-ONAP-RequestID")).thenReturn("123");
228         when(request.getHeader("X-InvocationID")).thenReturn("456");
229         baseServlet.setIpFqdnRequestIDandInvocationIDForEelf("doDelete", request);
230         Assert.assertEquals("123", MDC.get("RequestId"));
231         Assert.assertEquals("456", MDC.get("InvocationId"));
232     }
233
234     @Test
235     public void Given_Json_Object_Requires_Mask_Encrypt() throws NoSuchAlgorithmException {
236         PowerMockito.mockStatic(SecretKeyFactory.class);
237         SecretKeyFactory secretKeyFactory = PowerMockito.mock(SecretKeyFactory.class);
238         PowerMockito.when(SecretKeyFactory.getInstance(Mockito.anyString())).thenReturn(secretKeyFactory);
239         BaseServlet.maskJSON(getJsonObject(), "password", true);
240     }
241
242     @Test
243     public void Given_Json_Object_Requires_Mask_Decrypt() throws NoSuchAlgorithmException {
244         PowerMockito.mockStatic(SecretKeyFactory.class);
245         SecretKeyFactory secretKeyFactory = PowerMockito.mock(SecretKeyFactory.class);
246         PowerMockito.when(SecretKeyFactory.getInstance(Mockito.anyString())).thenReturn(secretKeyFactory);
247         BaseServlet.maskJSON(getJsonObject(), "password", false);
248     }
249
250     public JSONObject getJsonObject() {
251         return new JSONObject("{\"authorization\": {\n" + "    \"endpoint_addrs\": [\n" + "    ],\n"
252                                       + "    \"classification\": \"unclassified\",\n"
253                                       + "    \"endpoint_ids\": [\n" + "      {\n"
254                                       + "        \"password\": \"dradmin\",\n"
255                                       + "        \"id\": \"dradmin\"\n" + "      },\n" + "      {\n"
256                                       + "        \"password\": \"demo123456!\",\n"
257                                       + "        \"id\": \"onap\"\n" + "      }\n" + "    ]\n" + "  }}");
258     }
259
260     @Test
261     public void Given_BaseServlet_Verify_Cadi_Feed_Permission() {
262         assertEquals("org.onap.dmaap-dr.feed|legacy|publish", baseServlet.getFeedPermission("legacy", "publish"));
263         assertEquals("org.onap.dmaap-dr.feed|legacy|suspend", baseServlet.getFeedPermission("legacy", "suspend"));
264         assertEquals("org.onap.dmaap-dr.feed|legacy|restore", baseServlet.getFeedPermission("legacy", "restore"));
265         assertEquals("org.onap.dmaap-dr.feed|org.onap.dmaap-dr.NoInstanceDefined|restore", baseServlet.getFeedPermission(null, "restore"));
266         assertEquals("org.onap.dmaap-dr.feed|legacy|*", baseServlet.getFeedPermission("legacy", "default"));
267     }
268
269     @Test
270     public void Given_BaseServlet_Verify_Cadi_Sub_Permission() {
271         assertEquals("org.onap.dmaap-dr.feed|legacy|subscribe", baseServlet.getSubscriberPermission("legacy", "subscribe"));
272         assertEquals("org.onap.dmaap-dr.sub|legacy|suspend", baseServlet.getSubscriberPermission("legacy", "suspend"));
273         assertEquals("org.onap.dmaap-dr.sub|legacy|restore", baseServlet.getSubscriberPermission("legacy", "restore"));
274         assertEquals("org.onap.dmaap-dr.sub|legacy|publish", baseServlet.getSubscriberPermission("legacy", "publish"));
275         assertEquals("org.onap.dmaap-dr.sub|org.onap.dmaap-dr.NoInstanceDefined|restore", baseServlet.getSubscriberPermission(null, "restore"));
276         assertEquals("org.onap.dmaap-dr.sub|legacy|*", baseServlet.getSubscriberPermission("legacy", "default"));
277     }
278
279 }