b143906038b246e29b513aefc04c7ebb4295bffa
[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-2018 AT&T Intellectual Property. All rights reserved.
6  * 
7  * Modification Copyright (C) 2018 IBM.
8  * ===================================================================
9  *
10  * Unless otherwise specified, all software contained herein is licensed
11  * under the Apache License, Version 2.0 (the "License");
12  * you may not use this software except in compliance with the License.
13  * You may obtain a copy of the License at
14  *
15  *             http://www.apache.org/licenses/LICENSE-2.0
16  *
17  * Unless required by applicable law or agreed to in writing, software
18  * distributed under the License is distributed on an "AS IS" BASIS,
19  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
20  * See the License for the specific language governing permissions and
21  * limitations under the License.
22  *
23  * Unless otherwise specified, all documentation contained herein is licensed
24  * under the Creative Commons License, Attribution 4.0 Intl. (the "License");
25  * you may not use this documentation except in compliance with the License.
26  * You may obtain a copy of the License at
27  *
28  *             https://creativecommons.org/licenses/by/4.0/
29  *
30  * Unless required by applicable law or agreed to in writing, documentation
31  * distributed under the License is distributed on an "AS IS" BASIS,
32  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
33  * See the License for the specific language governing permissions and
34  * limitations under the License.
35  *
36  * ============LICENSE_END============================================
37  *
38  * 
39  */
40 package org.onap.portalapp.portal.interceptor;
41
42 import java.util.ArrayList;
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.mockito.internal.stubbing.answers.ThrowsException;
53 import org.onap.aaf.cadi.CadiWrap;
54 import org.onap.portalapp.controller.sessionmgt.SessionCommunicationController;
55 import org.onap.portalapp.portal.controller.BasicAuthenticationController;
56 import org.onap.portalapp.portal.controller.ExternalAppsRestfulController;
57 import org.onap.portalapp.portal.controller.SharedContextRestController;
58 import org.onap.portalapp.portal.controller.WebAnalyticsExtAppController;
59 import org.onap.portalapp.portal.domain.BasicAuthCredentials;
60 import org.onap.portalapp.portal.domain.EPApp;
61 import org.onap.portalapp.portal.domain.EPEndpoint;
62 import org.onap.portalapp.portal.domain.EPUser;
63 import org.onap.portalapp.portal.logging.aop.EPEELFLoggerAdvice;
64 import org.onap.portalapp.portal.logging.format.EPAppMessagesEnum;
65 import org.onap.portalapp.portal.logging.logic.EPLogUtil;
66 import org.onap.portalapp.portal.service.AdminRolesService;
67 import org.onap.portalapp.portal.service.AppsCacheService;
68 import org.onap.portalapp.portal.service.BasicAuthenticationCredentialService;
69 import org.onap.portalapp.portal.service.ExternalAccessRolesService;
70 import org.onap.portalapp.portal.utils.EPCommonSystemProperties;
71 import org.onap.portalapp.portal.utils.EcompPortalUtils;
72 import org.onap.portalapp.service.RemoteWebServiceCallService;
73 import org.onap.portalapp.service.sessionmgt.ManageService;
74 import org.onap.portalapp.util.EPUserUtils;
75 import org.onap.portalsdk.core.controller.FusionBaseController;
76 import org.onap.portalsdk.core.exception.UrlAccessRestrictedException;
77 import org.onap.portalsdk.core.interceptor.ResourceInterceptor;
78 import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate;
79 import org.onap.portalsdk.core.onboarding.listener.PortalTimeoutHandler;
80 import org.onap.portalsdk.core.onboarding.util.AuthUtil;
81 import org.onap.portalsdk.core.onboarding.util.CipherUtil;
82 import org.onap.portalsdk.core.onboarding.util.PortalApiConstants;
83 import org.onap.portalsdk.core.onboarding.util.PortalApiProperties;
84 import org.onap.portalsdk.core.util.SystemProperties;
85 import org.onap.portalsdk.core.util.SystemProperties.SecurityEventTypeEnum;
86 import org.springframework.beans.factory.annotation.Autowired;
87 import org.springframework.web.method.HandlerMethod;
88
89 public class PortalResourceInterceptor extends ResourceInterceptor {
90         
91         private EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(PortalResourceInterceptor.class);
92
93         @Autowired
94         private RemoteWebServiceCallService remoteWebServiceCallService;
95
96         @Autowired
97         private ManageService manageService;
98         
99         @Autowired
100         AppsCacheService appCacheService;
101
102         @Autowired
103         private EPEELFLoggerAdvice epAdvice;
104         
105         @Autowired
106         private AdminRolesService adminRolesService;
107
108         @Autowired
109         private BasicAuthenticationCredentialService basicAuthService;
110
111         @SuppressWarnings("unchecked")
112         @Override
113         public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
114                         throws Exception {
115
116                 if (handler instanceof HandlerMethod) {
117                         HandlerMethod method = (HandlerMethod) handler;
118
119                         /**
120                          * These classes provide REST endpoints used by other application
121                          * servers, NOT by an end user's browser.
122                          */
123                         if (method.getBean() instanceof FusionBaseController) {
124                                 FusionBaseController controller = (FusionBaseController) method.getBean();
125                                 if (!controller.isAccessible()) {
126
127                                         // authorize portalApi requests by user role
128                                         String requestURI = request.getRequestURI();
129                                         if (requestURI != null) {
130                                                 String[] uriArray = requestURI.split("/portalApi/");
131                                                 if (uriArray.length > 1) {
132                                                         String portalApiPath = uriArray[1];
133
134                                                         Set<? extends String> roleFunctions = (Set<? extends String>) request.getSession()
135                                                                         .getAttribute(SystemProperties
136                                                                                         .getProperty(SystemProperties.ROLE_FUNCTIONS_ATTRIBUTE_NAME));
137                                                         Set<? extends String> allRoleFunctions = (Set<? extends String>) request.getSession()
138                                                                         .getAttribute(EPUserUtils.ALL_ROLE_FUNCTIONS);
139                                                         // Defend against code error to avoid throwing NPE
140                                                         if (roleFunctions == null || allRoleFunctions == null) {
141                                                                 logger.error(EELFLoggerDelegate.errorLogger,
142                                                                                 "preHandle: failed to get role functions attribute(s) from session!!");
143                                                                 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeInitializationError);
144                                                                 return false;
145                                                         }
146                                                         // check to see if roleFunctions of the user is in
147                                                         // the
148                                                         // list of all role functions
149                                                         // if not, ignore to prevent restricting every
150                                                         // trivial
151                                                         // call; otherwise, if it is, then check for the
152                                                         // access
153                                                         EPUser user = (EPUser) request.getSession().getAttribute(
154                                                                         SystemProperties.getProperty(SystemProperties.USER_ATTRIBUTE_NAME));
155                                                         //RoleAdmin check is being added because the role belongs to partner application 
156                                                         //inorder to access portal api's, bypassing this with isRoleAdmin Check
157                                                         if ((matchRoleFunctions(portalApiPath, allRoleFunctions)
158                                                                         && !matchRoleFunctions(portalApiPath, roleFunctions)) && !adminRolesService.isRoleAdmin(user)) {
159                                                                 logger.error(EELFLoggerDelegate.errorLogger,
160                                                                                 "preHandle: User {} not authorized for path {} ", user.getOrgUserId(),
161                                                                                 portalApiPath);
162                                                                 EcompPortalUtils.setBadPermissions(user, response, portalApiPath);
163                                                                 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeRestApiAuthenticationError);
164                                                                 return false;
165                                                         } // failed to match
166
167                                                 } // is portalApi
168
169                                         } // requestURI
170                                 } // instance check
171                         } // not accessible
172                         else if (method.getBean() instanceof BasicAuthenticationController) {
173                                 return checkBasicAuth(request, response);
174                         }
175                         Object controllerObj = method.getBean();
176                         if (controllerObj instanceof SessionCommunicationController
177                                         || controllerObj instanceof SharedContextRestController
178                                         || controllerObj instanceof ExternalAppsRestfulController) {
179                                 // check user authentication for RESTful calls
180                                 String secretKey = null;
181                                 try {
182                                         epAdvice.loadServletRequestBasedDefaults(request, SecurityEventTypeEnum.INCOMING_REST_MESSAGE);
183                                         if (!remoteWebServiceCallService.verifyRESTCredential(secretKey, request.getHeader(EPCommonSystemProperties.UEB_KEY),
184                                                         request.getHeader("username"), request.getHeader("password"))) {
185                                                 throw new UrlAccessRestrictedException();
186                                         }
187                                 } catch (Exception e) {
188                                         logger.error(EELFLoggerDelegate.errorLogger, "preHandle: failed to authenticate RESTful service",
189                                                         e);
190                                         EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeRestApiAuthenticationError, e);
191                                         throw new UrlAccessRestrictedException();
192                                 }
193                         }
194
195                         if (controllerObj instanceof WebAnalyticsExtAppController) {
196                                 if (!remoteWebServiceCallService.verifyAppKeyCredential(request.getHeader(EPCommonSystemProperties.UEB_KEY))) {
197                                         logger.error(EELFLoggerDelegate.errorLogger,
198                                                         "preHandle: failed to verify app key for web analytics call");
199                                         throw new UrlAccessRestrictedException();
200                                 }
201                         }
202                 }
203
204                 handleSessionUpdates(request);
205                 return true;
206         }
207
208         /**
209          * Sets the status code and sends a response. Factors code out of many
210          * methods.
211          * 
212          * @param response
213          *            HttpServletResponse
214          * @param statusCode
215          *            HTTP status code like 404
216          * @param message
217          *            Message to send in a JSON error object
218          */
219         private void sendErrorResponse(HttpServletResponse response, final int statusCode, final String message)
220                         throws Exception {
221                 response.setStatus(statusCode);
222                 response.setContentType("application/json");
223                 response.getWriter().write("{\"error\":\"" + message + "\"}");
224                 response.getWriter().flush();
225         }
226
227         /**
228          * Gets HTTP basic authentication information from the request and checks
229          * whether those credentials are authorized for the request path.
230          * 
231          * @param request
232          *            HttpServletRequest
233          * @param response
234          *            HttpServletResponse
235          * @return True if the request is authorized, else false
236          * @throws Exception
237          */
238         private boolean checkBasicAuth(HttpServletRequest request, HttpServletResponse response) throws Exception {
239                 String uri = request.getRequestURI().toString();
240                 uri = uri.substring(uri.indexOf("/", 1));
241
242                 final String authHeader = request.getHeader(EPCommonSystemProperties.AUTHORIZATION);
243                 final String uebkey = request.getHeader(EPCommonSystemProperties.UEB_KEY);
244                 try{
245                         CadiWrap wrapReq = (CadiWrap) request;
246                                 logger.debug(EELFLoggerDelegate.debugLogger, "Entering in the loop as the uri contains auxapi : {}");
247                                 String nameSpace=PortalApiProperties.getProperty(PortalApiConstants.AUTH_NAMESPACE);
248                                 logger.debug(EELFLoggerDelegate.debugLogger, "namespace form the portal properties : {}",nameSpace);
249                                 Boolean accessallowed=AuthUtil.isAccessAllowed(request, nameSpace);
250                                 logger.debug(EELFLoggerDelegate.debugLogger, "AccessAllowed for the request and namespace : {}",accessallowed);
251                                 if(accessallowed){
252                                         logger.debug(EELFLoggerDelegate.debugLogger, "AccessAllowed is allowed: {}",accessallowed);
253
254                                         //String[] accountNamePassword = EcompPortalUtils.getUserNamePassword(authHeader);
255                                         //check ueb condition
256                                         if(uebkey !=null && !uebkey.isEmpty())
257                                         {
258                                                 EPApp application = appCacheService.getAppFromUeb(uebkey,1);
259                                                 if (application == null) {
260                                                         throw new Exception("Invalid credentials!");
261                                                 }
262                                                 else {
263                                                         final String appUsername = application.getUsername();
264                                                         logger.debug(EELFLoggerDelegate.debugLogger, "appUsername : {}",appUsername);
265
266                                                         String[] accountNamePassword = EcompPortalUtils.getUserNamePassword(authHeader);
267                                                         logger.debug(EELFLoggerDelegate.debugLogger, "accountNamePassword : {}",accountNamePassword);
268
269                                                         if (accountNamePassword == null || accountNamePassword.length != 2) {
270                                                                 final String msg = "failed to get username and password from Atuhorization header";
271                                                                 logger.debug(EELFLoggerDelegate.debugLogger, "checkBasicAuth Username and password failed to get: {}", msg);
272                                                                 sendErrorResponse(response, HttpServletResponse.SC_UNAUTHORIZED, msg);
273                                                                 return false;
274                                                         }
275                                                         if (appUsername.equals(accountNamePassword[0])) {
276                                                                 return true;
277                                                         }else{
278                                                                 final String msg = "failed to match the UserName from the application ";
279                                                                 logger.debug(EELFLoggerDelegate.debugLogger, "failed to match the UserName from the application checkBasicAuth Username and password failed to get: {}", msg);
280                                                                 sendErrorResponse(response, HttpServletResponse.SC_UNAUTHORIZED, msg);
281                                                                 return false;
282                                                         }
283                                                 }
284                                         }
285
286                                         return true;    
287                                 }
288                                 if(!accessallowed){
289                                         final String msg = "no authorization found";
290                                         logger.debug(EELFLoggerDelegate.debugLogger, "checkBasicAuth when no accessallowed: {}", msg);
291                                         sendErrorResponse(response, HttpServletResponse.SC_UNAUTHORIZED, msg);
292                                         return false;
293                                 }
294                                 return false;
295                         
296                 }catch(ClassCastException e){
297                         logger.debug(EELFLoggerDelegate.debugLogger, "Entering in the classcastexception block if the UN is not the mechid : {}");
298
299                         
300                         // Unauthorized access due to missing HTTP Authorization request header
301                         if (authHeader == null) {
302                                 final String msg = "no authorization found";
303                                 logger.debug(EELFLoggerDelegate.debugLogger, "checkBasicAuth: {}", msg);
304                                 sendErrorResponse(response, HttpServletResponse.SC_UNAUTHORIZED, msg);
305                                 return false;
306                         }
307
308                         String[] accountNamePassword = EcompPortalUtils.getUserNamePassword(authHeader);
309                         if (accountNamePassword == null || accountNamePassword.length != 2) {
310                                 final String msg = "failed to get username and password from Atuhorization header";
311                                 logger.debug(EELFLoggerDelegate.debugLogger, "checkBasicAuth: {}", msg);
312                                 sendErrorResponse(response, HttpServletResponse.SC_UNAUTHORIZED, msg);
313                                 return false;
314                         }
315
316                         if(uebkey !=null && !uebkey.isEmpty())
317                         {
318                                 EPApp application = appCacheService.getAppFromUeb(uebkey,1);
319                                 if (application == null) {
320                                         throw new Exception("Invalid credentials!");
321                                 }
322                                 else {
323                                         final String appUsername = application.getUsername();
324                                         final String dbDecryptedPwd = CipherUtil.decryptPKC(application.getAppPassword());
325                                         if (appUsername.equals(accountNamePassword[0]) && dbDecryptedPwd.equals(accountNamePassword[1])) {
326                                                 return true;
327                                         }
328                                 }
329                         }
330
331                         
332                         BasicAuthCredentials creds;
333                         try {
334                                 creds = basicAuthService.getBasicAuthCredentialByUsernameAndPassword(accountNamePassword[0],
335                                                 accountNamePassword[1]);
336                         } catch (Exception e1) {
337                                 logger.error(EELFLoggerDelegate.errorLogger, "checkBasicAuth failed to get credentials", e1);
338                                 final String msg = "Failed while getting basic authentication credential: ";
339                                 sendErrorResponse(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, msg);
340                                 throw e1;
341                         }
342
343                         // Unauthorized access due to invalid credentials (username and
344                         // password)
345                         if (creds == null || !creds.getUsername().equals(accountNamePassword[0])) {
346                                 final String msg = "Unauthorized: Access denied";
347                                 logger.debug(EELFLoggerDelegate.debugLogger, "checkBasicAuth: {}", msg);
348                                 sendErrorResponse(response, HttpServletResponse.SC_UNAUTHORIZED, msg);
349                                 return false;
350                         }
351
352                         // Unauthorized access due to inactive account
353                         if (creds.getIsActive().equals("N")) {
354                                 final String msg = "Unauthorized: The account is inactive";
355                                 logger.debug(EELFLoggerDelegate.debugLogger, "checkBasicAuth: {}", msg);
356                                 sendErrorResponse(response, HttpServletResponse.SC_UNAUTHORIZED, msg);
357                                 return false;
358                         }
359                 
360                 }catch (Exception e2) {
361                         logger.error(EELFLoggerDelegate.errorLogger, "checkBasicAuth failed to get credentials for some other exception", e2);
362                         final String msg = "Failed while getting basic authentication credential for some other exception: ";
363                         sendErrorResponse(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, msg);
364                         throw e2;
365                 }
366                 return true;
367
368
369 }
370
371         @SuppressWarnings("unused")
372         private String decrypted(String encrypted) throws Exception {
373                 String result = "";
374                 if (encrypted != null && encrypted.length() > 0) {
375                         try {
376                                 result = CipherUtil.decryptPKC(encrypted, SystemProperties.getProperty(SystemProperties.Decryption_Key));
377                         } catch (Exception e) {
378                                 logger.error(EELFLoggerDelegate.errorLogger, "decryptedPassword failed", e);
379                                 throw e;
380                         }
381                 }
382                 return result;
383         }
384
385         private String encrypted(String decryptedPwd) throws Exception {
386                 String result = "";
387                 if (decryptedPwd != null && decryptedPwd.length() > 0) {
388                         try {
389                                 result = CipherUtil.encryptPKC(decryptedPwd,
390                                                 SystemProperties.getProperty(SystemProperties.Decryption_Key));
391                         } catch (Exception e) {
392                                 logger.error(EELFLoggerDelegate.errorLogger, "encryptedPassword() failed", e);
393                                 throw e;
394                         }
395                 }
396                 return result;
397         }
398
399         private Boolean matchRoleFunctions(String portalApiPath, Set<? extends String> roleFunctions) {
400                 String[] path = portalApiPath.split("/");
401                 List<String> roleFunList = new ArrayList<>();
402                 if (path.length > 1) {
403                         roleFunList = roleFunctions.stream().filter(item -> item.startsWith(path[0])).collect(Collectors.toList());
404                         if (roleFunList.size() >= 1) {
405                                 for (String roleFunction : roleFunList) {
406                                         String[] roleFunctionArray = roleFunction.split("/");
407                                         boolean b = true;
408                                         if (roleFunctionArray.length == path.length) {
409                                                 for (int i = 0; i < roleFunctionArray.length; i++) {
410                                                         if (b) {
411                                                                 if (!roleFunctionArray[i].equals("*")) {
412                                                                         Pattern p = Pattern.compile(Pattern.quote(path[i]), Pattern.CASE_INSENSITIVE);
413                                                                         Matcher m = p.matcher(roleFunctionArray[i]);
414                                                                         b = m.matches();
415
416                                                                 }
417                                                         }
418                                                 }
419                                                         if (b)
420                                                                 return b;
421                                         }
422                                 }
423                         }
424                 } else {
425                         for (String roleFunction : roleFunctions) {
426                                 if (portalApiPath.matches(roleFunction))
427                                         return true;
428                         }
429                 }
430                 return false;
431         }
432         
433         
434
435         protected void handleSessionUpdates(HttpServletRequest request) {
436                 PortalTimeoutHandler.handleSessionUpdatesNative(request, null, null, null, null, manageService);
437         }
438         
439 }