Added Junits
[portal.git] / ecomp-portal-BE-common / src / main / java / org / onap / portalapp / portal / interceptor / PortalResourceInterceptor.java
1 /*-
2  * ============LICENSE_START==========================================
3  * ONAP Portal
4  * ===================================================================
5  * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
6  * ===================================================================
7  *
8  * Unless otherwise specified, all software contained herein is licensed
9  * under the Apache License, Version 2.0 (the "License");
10  * you may not use this software except in compliance with the License.
11  * You may obtain a copy of the License at
12  *
13  *             http://www.apache.org/licenses/LICENSE-2.0
14  *
15  * Unless required by applicable law or agreed to in writing, software
16  * distributed under the License is distributed on an "AS IS" BASIS,
17  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18  * See the License for the specific language governing permissions and
19  * limitations under the License.
20  *
21  * Unless otherwise specified, all documentation contained herein is licensed
22  * under the Creative Commons License, Attribution 4.0 Intl. (the "License");
23  * you may not use this documentation except in compliance with the License.
24  * You may obtain a copy of the License at
25  *
26  *             https://creativecommons.org/licenses/by/4.0/
27  *
28  * Unless required by applicable law or agreed to in writing, documentation
29  * distributed under the License is distributed on an "AS IS" BASIS,
30  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
31  * See the License for the specific language governing permissions and
32  * limitations under the License.
33  *
34  * ============LICENSE_END============================================
35  *
36  * ECOMP is a trademark and service mark of AT&T Intellectual Property.
37  */
38 package org.onap.portalapp.portal.interceptor;
39
40 import java.nio.charset.Charset;
41 import java.util.ArrayList;
42 import java.util.Base64;
43 import java.util.List;
44 import java.util.Set;
45 import java.util.regex.Matcher;
46 import java.util.regex.Pattern;
47 import java.util.stream.Collectors;
48
49 import javax.servlet.http.HttpServletRequest;
50 import javax.servlet.http.HttpServletResponse;
51
52 import org.apache.commons.codec.binary.Hex;
53 import org.onap.portalapp.controller.sessionmgt.SessionCommunicationController;
54 import org.onap.portalapp.portal.controller.BasicAuthenticationController;
55 import org.onap.portalapp.portal.controller.ExternalAppsRestfulController;
56 import org.onap.portalapp.portal.controller.SharedContextRestController;
57 import org.onap.portalapp.portal.controller.WebAnalyticsExtAppController;
58 import org.onap.portalapp.portal.domain.BasicAuthCredentials;
59 import org.onap.portalapp.portal.domain.EPEndpoint;
60 import org.onap.portalapp.portal.domain.EPRole;
61 import org.onap.portalapp.portal.domain.EPUser;
62 import org.onap.portalapp.portal.logging.aop.EPEELFLoggerAdvice;
63 import org.onap.portalapp.portal.logging.format.EPAppMessagesEnum;
64 import org.onap.portalapp.portal.logging.logic.EPLogUtil;
65 import org.onap.portalapp.portal.service.BasicAuthenticationCredentialService;
66 import org.onap.portalapp.portal.utils.EcompPortalUtils;
67 import org.onap.portalapp.service.RemoteWebServiceCallService;
68 import org.onap.portalapp.service.sessionmgt.ManageService;
69 import org.onap.portalapp.util.EPUserUtils;
70 import org.onap.portalsdk.core.controller.FusionBaseController;
71 import org.onap.portalsdk.core.exception.UrlAccessRestrictedException;
72 import org.onap.portalsdk.core.interceptor.ResourceInterceptor;
73 import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate;
74 import org.onap.portalsdk.core.onboarding.listener.PortalTimeoutHandler;
75 import org.onap.portalsdk.core.onboarding.util.CipherUtil;
76 import org.onap.portalsdk.core.util.SystemProperties;
77 import org.onap.portalsdk.core.util.SystemProperties.SecurityEventTypeEnum;
78 import org.springframework.beans.factory.annotation.Autowired;
79 import org.springframework.web.method.HandlerMethod;
80
81 public class PortalResourceInterceptor extends ResourceInterceptor {
82         private static final String APP_KEY = "uebkey";
83
84         private EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(PortalResourceInterceptor.class);
85
86         @Autowired
87         private RemoteWebServiceCallService remoteWebServiceCallService;
88
89         @Autowired
90         private ManageService manageService;
91
92         @Autowired
93         private EPEELFLoggerAdvice epAdvice;
94
95         @Autowired
96         private BasicAuthenticationCredentialService basicAuthService;
97
98         @SuppressWarnings("unchecked")
99         @Override
100         public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
101                         throws Exception {
102
103                 if (handler instanceof HandlerMethod) {
104                         HandlerMethod method = (HandlerMethod) handler;
105
106                         /**
107                          * These classes provide REST endpoints used by other application
108                          * servers, NOT by an end user's browser.
109                          */
110                         if (method.getBean() instanceof FusionBaseController) {
111                                 FusionBaseController controller = (FusionBaseController) method.getBean();
112                                 if (!controller.isAccessible()) {
113
114                                         // authorize portalApi requests by user role
115                                         String requestURI = request.getRequestURI();
116                                         if (requestURI != null) {
117                                                 String[] uriArray = requestURI.split("/portalApi/");
118                                                 if (uriArray.length > 1) {
119                                                         String portalApiPath = uriArray[1];
120
121                                                         Set<? extends String> roleFunctions = (Set<? extends String>) request.getSession()
122                                                                         .getAttribute(SystemProperties
123                                                                                         .getProperty(SystemProperties.ROLE_FUNCTIONS_ATTRIBUTE_NAME));
124                                                         Set<? extends String> allRoleFunctions = (Set<? extends String>) request.getSession()
125                                                                         .getAttribute(EPUserUtils.ALL_ROLE_FUNCTIONS);
126                                                         // Defend against code error to avoid throwing NPE
127                                                         if (roleFunctions == null || allRoleFunctions == null) {
128                                                                 logger.error(EELFLoggerDelegate.errorLogger,
129                                                                                 "preHandle: failed to get role functions attribute(s) from session!!");
130                                                                 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeInitializationError);
131                                                                 return false;
132                                                         }
133                                                         // check to see if roleFunctions of the user is in
134                                                         // the
135                                                         // list of all role functions
136                                                         // if not, ignore to prevent restricting every
137                                                         // trivial
138                                                         // call; otherwise, if it is, then check for the
139                                                         // access
140                                                         if (matchRoleFunctions(portalApiPath, allRoleFunctions)
141                                                                         && !matchRoleFunctions(portalApiPath, roleFunctions)) {
142                                                                 EPUser user = (EPUser) request.getSession().getAttribute(
143                                                                                 SystemProperties.getProperty(SystemProperties.USER_ATTRIBUTE_NAME));
144                                                                 logger.error(EELFLoggerDelegate.errorLogger,
145                                                                                 "preHandle: User {} not authorized for path {} ", user.getOrgUserId(),
146                                                                                 portalApiPath);
147                                                                 EcompPortalUtils.setBadPermissions(user, response, portalApiPath);
148                                                                 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeRestApiAuthenticationError);
149                                                                 return false;
150                                                         } // failed to match
151
152                                                 } // is portalApi
153
154                                         } // requestURI
155                                 } // instance check
156                         } // not accessible
157                         else if (method.getBean() instanceof BasicAuthenticationController) {
158                                 return checkBasicAuth(request, response);
159                         }
160                         Object controllerObj = method.getBean();
161                         if (controllerObj instanceof SessionCommunicationController
162                                         || controllerObj instanceof SharedContextRestController
163                                         || controllerObj instanceof ExternalAppsRestfulController) {
164                                 // check user authentication for RESTful calls
165                                 String secretKey = null;
166                                 try {
167                                         epAdvice.loadServletRequestBasedDefaults(request, SecurityEventTypeEnum.INCOMING_REST_MESSAGE);
168                                         if (!remoteWebServiceCallService.verifyRESTCredential(secretKey, request.getHeader(APP_KEY),
169                                                         request.getHeader("username"), request.getHeader("password"))) {
170                                                 throw new UrlAccessRestrictedException();
171                                         }
172                                 } catch (Exception e) {
173                                         logger.error(EELFLoggerDelegate.errorLogger, "preHandle: failed to authenticate RESTful service",
174                                                         e);
175                                         EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeRestApiAuthenticationError, e);
176                                         throw new UrlAccessRestrictedException();
177                                 }
178                         }
179
180                         if (controllerObj instanceof WebAnalyticsExtAppController) {
181                                 if (!remoteWebServiceCallService.verifyAppKeyCredential(request.getHeader(APP_KEY))) {
182                                         logger.error(EELFLoggerDelegate.errorLogger,
183                                                         "preHandle: failed to verify app key for web analytics call");
184                                         throw new UrlAccessRestrictedException();
185                                 }
186                         }
187                 }
188
189                 handleSessionUpdates(request);
190                 return true;
191         }
192
193         /**
194          * Sets the status code and sends a response. Factors code out of many
195          * methods.
196          * 
197          * @param response
198          *            HttpServletResponse
199          * @param statusCode
200          *            HTTP status code like 404
201          * @param message
202          *            Message to send in a JSON error object
203          */
204         private void sendErrorResponse(HttpServletResponse response, final int statusCode, final String message)
205                         throws Exception {
206                 response.setStatus(statusCode);
207                 response.setContentType("application/json");
208                 response.getWriter().write("{\"error\":\"" + message + "\"}");
209                 response.getWriter().flush();
210         }
211
212         /**
213          * Gets HTTP basic authentication information from the request and checks
214          * whether those credentials are authorized for the request path.
215          * 
216          * @param request
217          *            HttpServletRequest
218          * @param response
219          *            HttpServletResponse
220          * @return True if the request is authorized, else false
221          * @throws Exception
222          */
223         private boolean checkBasicAuth(HttpServletRequest request, HttpServletResponse response) throws Exception {
224                 String uri = request.getRequestURI().toString();
225                 uri = uri.substring(uri.indexOf("/", 1));
226
227                 final String authHeader = request.getHeader("Authorization");
228
229                 // Unauthorized access due to missing HTTP Authorization request header
230                 if (authHeader == null) {
231                         final String msg = "no authorization found";
232                         logger.debug(EELFLoggerDelegate.debugLogger, "checkBasicAuth: {}", msg);
233                         sendErrorResponse(response, HttpServletResponse.SC_UNAUTHORIZED, msg);
234                         return false;
235                 }
236
237                 String[] accountNamePassword = getUserNamePassword(authHeader);
238                 if (accountNamePassword == null || accountNamePassword.length != 2) {
239                         final String msg = "failed to get username and password from Atuhorization header";
240                         logger.debug(EELFLoggerDelegate.debugLogger, "checkBasicAuth: {}", msg);
241                         sendErrorResponse(response, HttpServletResponse.SC_UNAUTHORIZED, msg);
242                         return false;
243                 }
244
245                 BasicAuthCredentials creds;
246                 try {
247                         creds = basicAuthService.getBasicAuthCredentialByUsernameAndPassword(accountNamePassword[0],
248                                         accountNamePassword[1]);
249                 } catch (Exception e) {
250                         logger.error(EELFLoggerDelegate.errorLogger, "checkBasicAuth failed to get credentials", e);
251                         final String msg = "Failed while getting basic authentication credential: ";
252                         sendErrorResponse(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, msg);
253                         throw e;
254                 }
255
256                 // Unauthorized access due to invalid credentials (username and
257                 // password)
258                 if (creds == null || !creds.getUsername().equals(accountNamePassword[0])) {
259                         final String msg = "Unauthorized: Access denied";
260                         logger.debug(EELFLoggerDelegate.debugLogger, "checkBasicAuth: {}", msg);
261                         sendErrorResponse(response, HttpServletResponse.SC_UNAUTHORIZED, msg);
262                         return false;
263                 }
264
265                 // Unauthorized access due to inactive account
266                 if (creds.getIsActive().equals("N")) {
267                         final String msg = "Unauthorized: The account is inactive";
268                         logger.debug(EELFLoggerDelegate.debugLogger, "checkBasicAuth: {}", msg);
269                         sendErrorResponse(response, HttpServletResponse.SC_UNAUTHORIZED, msg);
270                         return false;
271                 }
272                 boolean isAllowedEp = false;
273                 for (EPEndpoint ep : creds.getEndpoints()) {
274                         if (ep.getName().equals(uri)) {
275                                 isAllowedEp = true;
276                                 break;
277                         }
278                 }
279
280                 // If user doesn't specify any endpoint, allow all endpoints for that
281                 // account
282                 if (creds.getEndpoints().size() == 0)
283                         isAllowedEp = true;
284
285                 // Unauthorized access due to the invalid endpoints
286                 if (!isAllowedEp) {
287                         final String msg = "Unauthorized: Endpoint access denied";
288                         logger.debug(EELFLoggerDelegate.debugLogger, "checkBasicAuth: {}", msg);
289                         sendErrorResponse(response, HttpServletResponse.SC_UNAUTHORIZED, msg);
290                         return false;
291                 }
292
293                 // Made it to the end!
294                 return true;
295         }
296
297         private String[] getUserNamePassword(String authValue) {
298                 String base64Credentials = authValue.substring("Basic".length()).trim();
299                 String credentials = new String(Base64.getDecoder().decode(base64Credentials), Charset.forName("UTF-8"));
300                 final String[] values = credentials.split(":", 2);
301                 return values;
302         }
303
304         @SuppressWarnings("unused")
305         private String decrypted(String encrypted) throws Exception {
306                 String result = "";
307                 if (encrypted != null & encrypted.length() > 0) {
308                         try {
309                                 result = CipherUtil.decryptPKC(encrypted, SystemProperties.getProperty(SystemProperties.Decryption_Key));
310                         } catch (Exception e) {
311                                 logger.error(EELFLoggerDelegate.errorLogger, "decryptedPassword failed", e);
312                                 throw e;
313                         }
314                 }
315                 return result;
316         }
317
318         private String encrypted(String decryptedPwd) throws Exception {
319                 String result = "";
320                 if (decryptedPwd != null & decryptedPwd.length() > 0) {
321                         try {
322                                 result = CipherUtil.encryptPKC(decryptedPwd,
323                                                 SystemProperties.getProperty(SystemProperties.Decryption_Key));
324                         } catch (Exception e) {
325                                 logger.error(EELFLoggerDelegate.errorLogger, "encryptedPassword() failed", e);
326                                 throw e;
327                         }
328                 }
329                 return result;
330         }
331
332         private Boolean matchRoleFunctions(String portalApiPath, Set<? extends String> roleFunctions) {
333                 String[] path = portalApiPath.split("/");
334                 List<String> roleFunList = new ArrayList<>();
335                 if (path.length > 1) {
336                         roleFunList = roleFunctions.stream().filter(item -> item.startsWith(path[0])).collect(Collectors.toList());
337                         if (roleFunList.size() >= 1) {
338                                 for (String roleFunction : roleFunList) {
339                                         String[] roleFunctionArray = roleFunction.split("/");
340                                         boolean b = true;
341                                         if (roleFunctionArray.length == path.length) {
342                                                 for (int i = 0; i < roleFunctionArray.length; i++) {
343                                                         if (b) {
344                                                                 if (!roleFunctionArray[i].equals("*")) {
345                                                                         Pattern p = Pattern.compile(Pattern.quote(path[i]), Pattern.CASE_INSENSITIVE);
346                                                                         Matcher m = p.matcher(roleFunctionArray[i]);
347                                                                         b = m.matches();
348
349                                                                 }
350                                                         }
351                                                 }
352                                                         if (b)
353                                                                 return b;
354                                         }
355                                 }
356                         }
357                 } else {
358                         for (String roleFunction : roleFunctions) {
359                                 if (portalApiPath.matches(roleFunction))
360                                         return true;
361                         }
362                 }
363                 return false;
364         }
365
366         protected void handleSessionUpdates(HttpServletRequest request) {
367                 PortalTimeoutHandler.handleSessionUpdatesNative(request, null, null, null, null, manageService);
368         }
369 }