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