Merge "MicroserviceParameter class DB constraints"
[portal.git] / ecomp-portal-BE-common / src / main / java / org / onap / portalapp / portal / interceptor / PortalResourceInterceptor.java
index fcd1763..146050a 100644 (file)
@@ -2,7 +2,9 @@
  * ============LICENSE_START==========================================
  * ONAP Portal
  * ===================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
+ * 
+ * Modification Copyright (C) 2018 IBM.
  * ===================================================================
  *
  * Unless otherwise specified, all software contained herein is licensed
@@ -37,9 +39,7 @@
  */
 package org.onap.portalapp.portal.interceptor;
 
-import java.nio.charset.Charset;
 import java.util.ArrayList;
-import java.util.Base64;
 import java.util.List;
 import java.util.Set;
 import java.util.regex.Matcher;
@@ -49,20 +49,25 @@ import java.util.stream.Collectors;
 import javax.servlet.http.HttpServletRequest;
 import javax.servlet.http.HttpServletResponse;
 
-import org.apache.commons.codec.binary.Hex;
+import org.mockito.internal.stubbing.answers.ThrowsException;
+import org.onap.aaf.cadi.CadiWrap;
 import org.onap.portalapp.controller.sessionmgt.SessionCommunicationController;
 import org.onap.portalapp.portal.controller.BasicAuthenticationController;
 import org.onap.portalapp.portal.controller.ExternalAppsRestfulController;
 import org.onap.portalapp.portal.controller.SharedContextRestController;
 import org.onap.portalapp.portal.controller.WebAnalyticsExtAppController;
 import org.onap.portalapp.portal.domain.BasicAuthCredentials;
+import org.onap.portalapp.portal.domain.EPApp;
 import org.onap.portalapp.portal.domain.EPEndpoint;
-import org.onap.portalapp.portal.domain.EPRole;
 import org.onap.portalapp.portal.domain.EPUser;
 import org.onap.portalapp.portal.logging.aop.EPEELFLoggerAdvice;
 import org.onap.portalapp.portal.logging.format.EPAppMessagesEnum;
 import org.onap.portalapp.portal.logging.logic.EPLogUtil;
+import org.onap.portalapp.portal.service.AdminRolesService;
+import org.onap.portalapp.portal.service.AppsCacheService;
 import org.onap.portalapp.portal.service.BasicAuthenticationCredentialService;
+import org.onap.portalapp.portal.service.ExternalAccessRolesService;
+import org.onap.portalapp.portal.utils.EPCommonSystemProperties;
 import org.onap.portalapp.portal.utils.EcompPortalUtils;
 import org.onap.portalapp.service.RemoteWebServiceCallService;
 import org.onap.portalapp.service.sessionmgt.ManageService;
@@ -72,15 +77,17 @@ import org.onap.portalsdk.core.exception.UrlAccessRestrictedException;
 import org.onap.portalsdk.core.interceptor.ResourceInterceptor;
 import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate;
 import org.onap.portalsdk.core.onboarding.listener.PortalTimeoutHandler;
+import org.onap.portalsdk.core.onboarding.util.AuthUtil;
 import org.onap.portalsdk.core.onboarding.util.CipherUtil;
+import org.onap.portalsdk.core.onboarding.util.PortalApiConstants;
+import org.onap.portalsdk.core.onboarding.util.PortalApiProperties;
 import org.onap.portalsdk.core.util.SystemProperties;
 import org.onap.portalsdk.core.util.SystemProperties.SecurityEventTypeEnum;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.web.method.HandlerMethod;
 
 public class PortalResourceInterceptor extends ResourceInterceptor {
-       private static final String APP_KEY = "uebkey";
-
+       
        private EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(PortalResourceInterceptor.class);
 
        @Autowired
@@ -88,9 +95,15 @@ public class PortalResourceInterceptor extends ResourceInterceptor {
 
        @Autowired
        private ManageService manageService;
+       
+       @Autowired
+       AppsCacheService appCacheService;
 
        @Autowired
        private EPEELFLoggerAdvice epAdvice;
+       
+       @Autowired
+       private AdminRolesService adminRolesService;
 
        @Autowired
        private BasicAuthenticationCredentialService basicAuthService;
@@ -137,10 +150,12 @@ public class PortalResourceInterceptor extends ResourceInterceptor {
                                                        // trivial
                                                        // call; otherwise, if it is, then check for the
                                                        // access
-                                                       if (matchRoleFunctions(portalApiPath, allRoleFunctions)
-                                                                       && !matchRoleFunctions(portalApiPath, roleFunctions)) {
-                                                               EPUser user = (EPUser) request.getSession().getAttribute(
-                                                                               SystemProperties.getProperty(SystemProperties.USER_ATTRIBUTE_NAME));
+                                                       EPUser user = (EPUser) request.getSession().getAttribute(
+                                                                       SystemProperties.getProperty(SystemProperties.USER_ATTRIBUTE_NAME));
+                                                       //RoleAdmin check is being added because the role belongs to partner application 
+                                                       //inorder to access portal api's, bypassing this with isRoleAdmin Check
+                                                       if ((EPUserUtils.matchRoleFunctions(portalApiPath, allRoleFunctions)
+                                                                       && !EPUserUtils.matchRoleFunctions(portalApiPath, roleFunctions)) && !adminRolesService.isRoleAdmin(user)) {
                                                                logger.error(EELFLoggerDelegate.errorLogger,
                                                                                "preHandle: User {} not authorized for path {} ", user.getOrgUserId(),
                                                                                portalApiPath);
@@ -165,7 +180,7 @@ public class PortalResourceInterceptor extends ResourceInterceptor {
                                String secretKey = null;
                                try {
                                        epAdvice.loadServletRequestBasedDefaults(request, SecurityEventTypeEnum.INCOMING_REST_MESSAGE);
-                                       if (!remoteWebServiceCallService.verifyRESTCredential(secretKey, request.getHeader(APP_KEY),
+                                       if (!remoteWebServiceCallService.verifyRESTCredential(secretKey, request.getHeader(EPCommonSystemProperties.UEB_KEY),
                                                        request.getHeader("username"), request.getHeader("password"))) {
                                                throw new UrlAccessRestrictedException();
                                        }
@@ -178,7 +193,7 @@ public class PortalResourceInterceptor extends ResourceInterceptor {
                        }
 
                        if (controllerObj instanceof WebAnalyticsExtAppController) {
-                               if (!remoteWebServiceCallService.verifyAppKeyCredential(request.getHeader(APP_KEY))) {
+                               if (!remoteWebServiceCallService.verifyAppKeyCredential(request.getHeader(EPCommonSystemProperties.UEB_KEY))) {
                                        logger.error(EELFLoggerDelegate.errorLogger,
                                                        "preHandle: failed to verify app key for web analytics call");
                                        throw new UrlAccessRestrictedException();
@@ -224,87 +239,143 @@ public class PortalResourceInterceptor extends ResourceInterceptor {
                String uri = request.getRequestURI().toString();
                uri = uri.substring(uri.indexOf("/", 1));
 
-               final String authHeader = request.getHeader("Authorization");
+               final String authHeader = request.getHeader(EPCommonSystemProperties.AUTHORIZATION);
+               final String uebkey = request.getHeader(EPCommonSystemProperties.UEB_KEY);
+               try{
+                       CadiWrap wrapReq = (CadiWrap) request;
+                               logger.debug(EELFLoggerDelegate.debugLogger, "Entering in the loop as the uri contains auxapi : {}");
+                               String nameSpace=PortalApiProperties.getProperty(PortalApiConstants.AUTH_NAMESPACE);
+                               logger.debug(EELFLoggerDelegate.debugLogger, "namespace form the portal properties : {}",nameSpace);
+                               Boolean accessallowed=AuthUtil.isAccessAllowed(request, nameSpace);
+                               logger.debug(EELFLoggerDelegate.debugLogger, "AccessAllowed for the request and namespace : {}",accessallowed);
+                               if(accessallowed){
+                                       logger.debug(EELFLoggerDelegate.debugLogger, "AccessAllowed is allowed: {}",accessallowed);
+
+                                       //String[] accountNamePassword = EcompPortalUtils.getUserNamePassword(authHeader);
+                                       //check ueb condition
+                                       if(uebkey !=null && !uebkey.isEmpty())
+                                       {
+                                               EPApp application = appCacheService.getAppFromUeb(uebkey,1);
+                                               if (application == null) {
+                                                       throw new Exception("Invalid credentials!");
+                                               }
+                                               else {
+                                                       final String appUsername = application.getUsername();
+                                                       logger.debug(EELFLoggerDelegate.debugLogger, "appUsername : {}",appUsername);
 
-               // Unauthorized access due to missing HTTP Authorization request header
-               if (authHeader == null) {
-                       final String msg = "no authorization found";
-                       logger.debug(EELFLoggerDelegate.debugLogger, "checkBasicAuth: {}", msg);
-                       sendErrorResponse(response, HttpServletResponse.SC_UNAUTHORIZED, msg);
-                       return false;
-               }
+                                                       String[] accountNamePassword = EcompPortalUtils.getUserNamePassword(authHeader);
+                                                       logger.debug(EELFLoggerDelegate.debugLogger, "accountNamePassword : {}",accountNamePassword);
 
-               String[] accountNamePassword = getUserNamePassword(authHeader);
-               if (accountNamePassword == null || accountNamePassword.length != 2) {
-                       final String msg = "failed to get username and password from Atuhorization header";
-                       logger.debug(EELFLoggerDelegate.debugLogger, "checkBasicAuth: {}", msg);
-                       sendErrorResponse(response, HttpServletResponse.SC_UNAUTHORIZED, msg);
-                       return false;
-               }
+                                                       if (accountNamePassword == null || accountNamePassword.length != 2) {
+                                                               final String msg = "failed to get username and password from Atuhorization header";
+                                                               logger.debug(EELFLoggerDelegate.debugLogger, "checkBasicAuth Username and password failed to get: {}", msg);
+                                                               sendErrorResponse(response, HttpServletResponse.SC_UNAUTHORIZED, msg);
+                                                               return false;
+                                                       }
+                                                       if (appUsername.equals(accountNamePassword[0])) {
+                                                               return true;
+                                                       }else{
+                                                               final String msg = "failed to match the UserName from the application ";
+                                                               logger.debug(EELFLoggerDelegate.debugLogger, "failed to match the UserName from the application checkBasicAuth Username and password failed to get: {}", msg);
+                                                               sendErrorResponse(response, HttpServletResponse.SC_UNAUTHORIZED, msg);
+                                                               return false;
+                                                       }
+                                               }
+                                       }
 
-               BasicAuthCredentials creds;
-               try {
-                       creds = basicAuthService.getBasicAuthCredentialByUsernameAndPassword(accountNamePassword[0],
-                                       accountNamePassword[1]);
-               } catch (Exception e) {
-                       logger.error(EELFLoggerDelegate.errorLogger, "checkBasicAuth failed to get credentials", e);
-                       final String msg = "Failed while getting basic authentication credential: ";
-                       sendErrorResponse(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, msg);
-                       throw e;
-               }
+                                       return true;    
+                               }
+                               if(!accessallowed){
+                                       final String msg = "no authorization found";
+                                       logger.debug(EELFLoggerDelegate.debugLogger, "checkBasicAuth when no accessallowed: {}", msg);
+                                       sendErrorResponse(response, HttpServletResponse.SC_UNAUTHORIZED, msg);
+                                       return false;
+                               }
+                               return false;
+                       
+               }catch(ClassCastException e){
+                       logger.debug(EELFLoggerDelegate.debugLogger, "Entering in the classcastexception block if the UN is not the mechid : {}");
+
+                       String secretKey = null;
+                       // Unauthorized access due to missing HTTP Authorization request header
+                       if (authHeader == null) {
+                               if (remoteWebServiceCallService.verifyRESTCredential(secretKey, request.getHeader(EPCommonSystemProperties.UEB_KEY),
+                                               request.getHeader("username"), request.getHeader("password"))) {
+                                       return true;
+                               }
+                               final String msg = "no authorization found";
+                               logger.debug(EELFLoggerDelegate.debugLogger, "checkBasicAuth: {}", msg);
+                               sendErrorResponse(response, HttpServletResponse.SC_UNAUTHORIZED, msg);
+                               return false;
+                       }
 
-               // Unauthorized access due to invalid credentials (username and
-               // password)
-               if (creds == null || !creds.getUsername().equals(accountNamePassword[0])) {
-                       final String msg = "Unauthorized: Access denied";
-                       logger.debug(EELFLoggerDelegate.debugLogger, "checkBasicAuth: {}", msg);
-                       sendErrorResponse(response, HttpServletResponse.SC_UNAUTHORIZED, msg);
-                       return false;
-               }
+                       String[] accountNamePassword = EcompPortalUtils.getUserNamePassword(authHeader);
+                       if (accountNamePassword == null || accountNamePassword.length != 2) {
+                               final String msg = "failed to get username and password from Atuhorization header";
+                               logger.debug(EELFLoggerDelegate.debugLogger, "checkBasicAuth: {}", msg);
+                               sendErrorResponse(response, HttpServletResponse.SC_UNAUTHORIZED, msg);
+                               return false;
+                       }
 
-               // Unauthorized access due to inactive account
-               if (creds.getIsActive().equals("N")) {
-                       final String msg = "Unauthorized: The account is inactive";
-                       logger.debug(EELFLoggerDelegate.debugLogger, "checkBasicAuth: {}", msg);
-                       sendErrorResponse(response, HttpServletResponse.SC_UNAUTHORIZED, msg);
-                       return false;
-               }
-               boolean isAllowedEp = false;
-               for (EPEndpoint ep : creds.getEndpoints()) {
-                       if (ep.getName().equals(uri)) {
-                               isAllowedEp = true;
-                               break;
+                       if(uebkey !=null && !uebkey.isEmpty())
+                       {
+                               EPApp application = appCacheService.getAppFromUeb(uebkey,1);
+                               if (application == null) {
+                                       throw new Exception("Invalid credentials!");
+                               }
+                               else {
+                                       final String appUsername = application.getUsername();
+                                       final String dbDecryptedPwd = CipherUtil.decryptPKC(application.getAppPassword());
+                                       if (appUsername.equals(accountNamePassword[0]) && dbDecryptedPwd.equals(accountNamePassword[1])) {
+                                               return true;
+                                       }
+                               }
                        }
-               }
 
-               // If user doesn't specify any endpoint, allow all endpoints for that
-               // account
-               if (creds.getEndpoints().size() == 0)
-                       isAllowedEp = true;
-
-               // Unauthorized access due to the invalid endpoints
-               if (!isAllowedEp) {
-                       final String msg = "Unauthorized: Endpoint access denied";
-                       logger.debug(EELFLoggerDelegate.debugLogger, "checkBasicAuth: {}", msg);
-                       sendErrorResponse(response, HttpServletResponse.SC_UNAUTHORIZED, msg);
-                       return false;
-               }
+                       
+                       BasicAuthCredentials creds;
+                       try {
+                               creds = basicAuthService.getBasicAuthCredentialByUsernameAndPassword(accountNamePassword[0],
+                                               accountNamePassword[1]);
+                       } catch (Exception e1) {
+                               logger.error(EELFLoggerDelegate.errorLogger, "checkBasicAuth failed to get credentials", e1);
+                               final String msg = "Failed while getting basic authentication credential: ";
+                               sendErrorResponse(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, msg);
+                               throw e1;
+                       }
+
+                       // Unauthorized access due to invalid credentials (username and
+                       // password)
+                       if (creds == null || !creds.getUsername().equals(accountNamePassword[0])) {
+                               final String msg = "Unauthorized: Access denied";
+                               logger.debug(EELFLoggerDelegate.debugLogger, "checkBasicAuth: {}", msg);
+                               sendErrorResponse(response, HttpServletResponse.SC_UNAUTHORIZED, msg);
+                               return false;
+                       }
 
-               // Made it to the end!
+                       // Unauthorized access due to inactive account
+                       if (creds.getIsActive().equals("N")) {
+                               final String msg = "Unauthorized: The account is inactive";
+                               logger.debug(EELFLoggerDelegate.debugLogger, "checkBasicAuth: {}", msg);
+                               sendErrorResponse(response, HttpServletResponse.SC_UNAUTHORIZED, msg);
+                               return false;
+                       }
+               
+               }catch (Exception e2) {
+                       logger.error(EELFLoggerDelegate.errorLogger, "checkBasicAuth failed to get credentials for some other exception", e2);
+                       final String msg = "Failed while getting basic authentication credential for some other exception: ";
+                       sendErrorResponse(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, msg);
+                       throw e2;
+               }
                return true;
-       }
 
-       private String[] getUserNamePassword(String authValue) {
-               String base64Credentials = authValue.substring("Basic".length()).trim();
-               String credentials = new String(Base64.getDecoder().decode(base64Credentials), Charset.forName("UTF-8"));
-               final String[] values = credentials.split(":", 2);
-               return values;
-       }
+
+}
 
        @SuppressWarnings("unused")
        private String decrypted(String encrypted) throws Exception {
                String result = "";
-               if (encrypted != null & encrypted.length() > 0) {
+               if (encrypted != null && encrypted.length() > 0) {
                        try {
                                result = CipherUtil.decryptPKC(encrypted, SystemProperties.getProperty(SystemProperties.Decryption_Key));
                        } catch (Exception e) {
@@ -317,7 +388,7 @@ public class PortalResourceInterceptor extends ResourceInterceptor {
 
        private String encrypted(String decryptedPwd) throws Exception {
                String result = "";
-               if (decryptedPwd != null & decryptedPwd.length() > 0) {
+               if (decryptedPwd != null && decryptedPwd.length() > 0) {
                        try {
                                result = CipherUtil.encryptPKC(decryptedPwd,
                                                SystemProperties.getProperty(SystemProperties.Decryption_Key));
@@ -329,41 +400,8 @@ public class PortalResourceInterceptor extends ResourceInterceptor {
                return result;
        }
 
-       private Boolean matchRoleFunctions(String portalApiPath, Set<? extends String> roleFunctions) {
-               String[] path = portalApiPath.split("/");
-               List<String> roleFunList = new ArrayList<>();
-               if (path.length > 1) {
-                       roleFunList = roleFunctions.stream().filter(item -> item.startsWith(path[0])).collect(Collectors.toList());
-                       if (roleFunList.size() >= 1) {
-                               for (String roleFunction : roleFunList) {
-                                       String[] roleFunctionArray = roleFunction.split("/");
-                                       boolean b = true;
-                                       if (roleFunctionArray.length == path.length) {
-                                               for (int i = 0; i < roleFunctionArray.length; i++) {
-                                                       if (b) {
-                                                               if (!roleFunctionArray[i].equals("*")) {
-                                                                       Pattern p = Pattern.compile(Pattern.quote(path[i]), Pattern.CASE_INSENSITIVE);
-                                                                       Matcher m = p.matcher(roleFunctionArray[i]);
-                                                                       b = m.matches();
-
-                                                               }
-                                                       }
-                                               }
-                                                       if (b)
-                                                               return b;
-                                       }
-                               }
-                       }
-               } else {
-                       for (String roleFunction : roleFunctions) {
-                               if (portalApiPath.matches(roleFunction))
-                                       return true;
-                       }
-               }
-               return false;
-       }
-
        protected void handleSessionUpdates(HttpServletRequest request) {
                PortalTimeoutHandler.handleSessionUpdatesNative(request, null, null, null, null, manageService);
        }
+       
 }