XSS Vulnerability fix in RoleManageController
[portal.git] / ecomp-portal-BE-common / src / main / java / org / onap / portalapp / portal / controller / RoleManageController.java
index 8f0558a..3fda539 100644 (file)
@@ -4,6 +4,8 @@
  * ===================================================================
  * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
  * ===================================================================
+ * Modifications Copyright (c) 2019 Samsung
+ * ===================================================================
  *
  * Unless otherwise specified, all software contained herein is licensed
  * under the Apache License, Version 2.0 (the "License");
@@ -33,7 +35,7 @@
  *
  * ============LICENSE_END============================================
  *
- * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ * 
  */
 package org.onap.portalapp.portal.controller;
 
@@ -48,6 +50,11 @@ import java.util.TreeSet;
 import javax.servlet.http.HttpServletRequest;
 import javax.servlet.http.HttpServletResponse;
 
+import javax.validation.ConstraintViolation;
+import javax.validation.Valid;
+import javax.validation.Validation;
+import javax.validation.Validator;
+import javax.validation.ValidatorFactory;
 import org.apache.commons.lang.StringUtils;
 import org.json.JSONObject;
 import org.onap.portalapp.controller.EPRestrictedBaseController;
@@ -60,6 +67,7 @@ import org.onap.portalapp.portal.domain.EPUser;
 import org.onap.portalapp.portal.domain.EcompAuditLog;
 import org.onap.portalapp.portal.ecomp.model.PortalRestResponse;
 import org.onap.portalapp.portal.ecomp.model.PortalRestStatusEnum;
+import org.onap.portalapp.portal.ecomp.model.UploadRoleFunctionExtSystem;
 import org.onap.portalapp.portal.exceptions.DuplicateRecordException;
 import org.onap.portalapp.portal.exceptions.InvalidApplicationException;
 import org.onap.portalapp.portal.exceptions.InvalidRoleException;
@@ -76,6 +84,7 @@ import org.onap.portalapp.portal.utils.EPCommonSystemProperties;
 import org.onap.portalapp.portal.utils.EcompPortalUtils;
 import org.onap.portalapp.portal.utils.PortalConstants;
 import org.onap.portalapp.util.EPUserUtils;
+import org.onap.portalapp.validation.SecureString;
 import org.onap.portalsdk.core.domain.AuditLog;
 import org.onap.portalsdk.core.domain.Role;
 import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate;
@@ -108,6 +117,8 @@ import com.fasterxml.jackson.databind.type.TypeFactory;
 @EnableAspectJAutoProxy
 @EPAuditLog
 public class RoleManageController extends EPRestrictedBaseController {
+       private static final ValidatorFactory VALIDATOR_FACTORY = Validation.buildDefaultValidatorFactory();
+
        private static final String PIPE = "|";
 
        private static final String ROLE_INVALID_CHARS = "%=():,\"\"";
@@ -193,7 +204,7 @@ public class RoleManageController extends EPRestrictedBaseController {
                                mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
                                CentralV2Role domainRole = externalAccessRolesService.getRoleInfo(roleId, requestedApp.getUebKey());
                                // role. toggle active ind
-                               boolean active = domainRole.isActive();
+                               boolean active = domainRole.getActive();
                                domainRole.setActive(!active);
 
                                String result = mapper.writeValueAsString(domainRole);
@@ -328,6 +339,7 @@ public class RoleManageController extends EPRestrictedBaseController {
                                                domainRole = new CentralV2Role();
                                                domainRole.setName(role.getName());
                                                domainRole.setPriority(role.getPriority());
+                                               domainRole.setActive(role.getActive());
                                                if (role.getChildRoles() != null && role.getChildRoles().size() > 0) {
                                                        for (Object childRole : childRoles) {
                                                                domainRole.addChildRole((CentralV2Role) childRole);
@@ -493,8 +505,17 @@ public class RoleManageController extends EPRestrictedBaseController {
        }
 
        @RequestMapping(value = { "/portalApi/role_function_list/saveRoleFunction/{appId}" }, method = RequestMethod.POST)
-       public PortalRestResponse<String> saveRoleFunction(HttpServletRequest request, HttpServletResponse response, @RequestBody CentralV2RoleFunction roleFunc,
+       public PortalRestResponse<String> saveRoleFunction(HttpServletRequest request, HttpServletResponse response, @Valid @RequestBody CentralV2RoleFunction roleFunc,
                        @PathVariable("appId") Long appId) throws Exception {
+               if (roleFunc!=null) {
+                       Validator validator = VALIDATOR_FACTORY.getValidator();
+                       Set<ConstraintViolation<CentralV2RoleFunction>> constraintViolations = validator.validate(roleFunc);
+
+                       if(!constraintViolations.isEmpty()){
+                               logger.error(EELFLoggerDelegate.errorLogger, "saveRoleFunction: Failed");
+                               return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, "Data is not valid", "ERROR");
+                       }
+               }
                EPUser user = EPUserUtils.getUserSession(request);
                boolean saveOrUpdateResponse = false;
                try {
@@ -527,27 +548,7 @@ public class RoleManageController extends EPRestrictedBaseController {
                                                String activityCode = (isSave)
                                                                ? EcompAuditLog.CD_ACTIVITY_EXTERNAL_AUTH_ADD_FUNCTION
                                                                : EcompAuditLog.CD_ACTIVITY_EXTERNAL_AUTH_UPDATE_FUNCTION;
-                                               logger.info(EELFLoggerDelegate.applicationLogger,
-                                                               "saveRoleFunction: succeeded for app {}, function {}", app.getId(), code);
-                                               AuditLog auditLog = getAuditInfo(requestedUser, activityCode);
-                                               auditLog.setComments(EcompPortalUtils.truncateString("saveRoleFunction role for app:"
-                                                               + app.getId() + " and function:'" + code + "'",
-                                                               PortalConstants.AUDIT_LOG_COMMENT_SIZE));
-                                               auditService.logActivity(auditLog, null);
-                                               MDC.put(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP,
-                                                               EPEELFLoggerAdvice.getCurrentDateTimeUTC());
-                                               MDC.put(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP,
-                                                               EPEELFLoggerAdvice.getCurrentDateTimeUTC());
-                                               EcompPortalUtils.calculateDateTimeDifferenceForLog(
-                                                               MDC.get(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP),
-                                                               MDC.get(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP));
-                                               logger.info(EELFLoggerDelegate.auditLogger,
-                                                               EPLogUtil.formatAuditLogMessage("RoleManageController.saveRoleFunction", activityCode,
-                                                                               String.valueOf(requestedUser.getId()), requestedUser.getOrgUserId(),
-                                                                               code));
-                                               MDC.remove(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP);
-                                               MDC.remove(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP);
-                                               MDC.remove(SystemProperties.MDC_TIMER);
+                                               logExterlaAuthRoleFunctionActivity(code, requestedUser, app, activityCode);
                                        }
                                } else
                                        throw new NonCentralizedAppException(requestedApp.getName() + " is not Centralized Application");
@@ -563,6 +564,30 @@ public class RoleManageController extends EPRestrictedBaseController {
                }
                return new PortalRestResponse<>(PortalRestStatusEnum.OK, "Saved Successfully!", "Success");
        }
+       
+       private void logExterlaAuthRoleFunctionActivity(String code, EPUser requestedUser, EPApp app, String activityCode) {
+               logger.info(EELFLoggerDelegate.applicationLogger,
+                               "saveRoleFunction: succeeded for app {}, function {}", app.getId(), code);
+               AuditLog auditLog = getAuditInfo(requestedUser, activityCode);
+               auditLog.setComments(EcompPortalUtils.truncateString("saveRoleFunction role for app:"
+                               + app.getId() + " and function:'" + code + "'",
+                               PortalConstants.AUDIT_LOG_COMMENT_SIZE));
+               auditService.logActivity(auditLog, null);
+               MDC.put(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP,
+                               EPEELFLoggerAdvice.getCurrentDateTimeUTC());
+               MDC.put(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP,
+                               EPEELFLoggerAdvice.getCurrentDateTimeUTC());
+               EcompPortalUtils.calculateDateTimeDifferenceForLog(
+                               MDC.get(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP),
+                               MDC.get(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP));
+               logger.info(EELFLoggerDelegate.auditLogger,
+                               EPLogUtil.formatAuditLogMessage("RoleManageController.saveRoleFunction", activityCode,
+                                               String.valueOf(requestedUser.getId()), requestedUser.getOrgUserId(),
+                                               code));
+               MDC.remove(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP);
+               MDC.remove(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP);
+               MDC.remove(SystemProperties.MDC_TIMER);
+       }
 
 
 
@@ -586,6 +611,19 @@ public class RoleManageController extends EPRestrictedBaseController {
        public PortalRestResponse<String> removeRoleFunction(HttpServletRequest request, HttpServletResponse response,
                        @RequestBody String roleFunc, @PathVariable("appId") Long appId) throws Exception {
                EPUser user = EPUserUtils.getUserSession(request);
+
+               if (roleFunc!=null) {
+                       SecureString secureString = new SecureString(roleFunc);
+
+                       Validator validator = VALIDATOR_FACTORY.getValidator();
+                       Set<ConstraintViolation<SecureString>> constraintViolations = validator.validate(secureString);
+
+                       if(!constraintViolations.isEmpty()){
+                               logger.error(EELFLoggerDelegate.errorLogger, "removeRoleFunction: Failed");
+                               return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, "Data is not valid", "ERROR");
+                       }
+               }
+
                try {
                        EPApp requestedApp = appService.getApp(appId);
                        if (isAuthorizedUser(user, requestedApp)) {
@@ -648,9 +686,21 @@ public class RoleManageController extends EPRestrictedBaseController {
 
        @RequestMapping(value = { "/portalApi/centralizedApps" }, method = RequestMethod.GET)
        public List<CentralizedApp> getCentralizedAppRoles(HttpServletRequest request, HttpServletResponse response, String userId) throws IOException {
+               if(userId!=null) {
+                       SecureString secureString = new SecureString(userId);
+
+                       Validator validator = VALIDATOR_FACTORY.getValidator();
+                       Set<ConstraintViolation<SecureString>> constraintViolations = validator.validate(secureString);
+
+                       if(!constraintViolations.isEmpty()){
+                               logger.error(EELFLoggerDelegate.errorLogger, "removeRoleFunction: Failed");
+                               return null;
+                       }
+               }
+
                EPUser user = EPUserUtils.getUserSession(request);
                List<CentralizedApp> applicationsList = null;
-                       if (adminRolesService.isAccountAdmin(user) || adminRolesService.isSuperAdmin(user)) {
+                       if (adminRolesService.isAccountAdmin(user) || adminRolesService.isSuperAdmin(user) || adminRolesService.isRoleAdmin(user)) {
                                applicationsList = externalAccessRolesService.getCentralizedAppsOfUser(userId);
                        } else {
                                logger.info(EELFLoggerDelegate.auditLogger,
@@ -688,7 +738,7 @@ public class RoleManageController extends EPRestrictedBaseController {
                                externalAccessRolesService.syncApplicationRolesWithEcompDB(app);
                        } else {
                                logger.info(EELFLoggerDelegate.auditLogger,
-                                               "RoleManageController.syncRoles, Unauthorized user:" + user.getOrgUserId());
+                                               "RoleManageController.syncRoles, Unauthorized user:{}", user != null ? user.getOrgUserId() : "");
                                EcompPortalUtils.setBadPermissions(user, response, "createAdmin");
                                return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, "Unauthorized User", "Failure");
                        }
@@ -707,10 +757,10 @@ public class RoleManageController extends EPRestrictedBaseController {
                        EPApp app = appService.getApp(appId);
                        if (isAuthorizedUser(user, app)) {
                                fieldsValidation(app);
-                               externalAccessRolesService.syncRoleFunctionFromExternalAccessSystem(app);;
+                               externalAccessRolesService.syncRoleFunctionFromExternalAccessSystem(app);
                        } else {
                                logger.info(EELFLoggerDelegate.auditLogger,
-                                               "RoleManageController.syncFunctions, Unauthorized user:" + user.getOrgUserId());
+                                               "RoleManageController.syncFunctions, Unauthorized user:{}", user != null ? user.getOrgUserId() : "");
                                EcompPortalUtils.setBadPermissions(user, response, "createAdmin");
                                return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, "Unauthorized User", "Failure");
                        }
@@ -732,7 +782,7 @@ public class RoleManageController extends EPRestrictedBaseController {
                Iterator<CentralV2Role> availableChildRolesIterator = availableChildRoles.iterator();
                while (availableChildRolesIterator.hasNext()) {
                        CentralV2Role role = availableChildRolesIterator.next();
-                       if (!role.isActive() || allParentRoles.contains(role) || role.getId().equals(roleId)) {
+                       if (!role.getActive() || allParentRoles.contains(role) || role.getId().equals(roleId)) {
                                availableChildRolesIterator.remove();
                        }
                }
@@ -763,7 +813,7 @@ public class RoleManageController extends EPRestrictedBaseController {
                app.getUebKey();
                List<EPApp> appInfo = externalAccessRolesService.getApp(app.getUebKey());
                if(appInfo.isEmpty()){
-                       throw new InvalidApplicationException("Invalid uebkey");
+                       throw new InvalidApplicationException("Invalid credentials");
                }
                if(!appInfo.isEmpty() && EcompPortalUtils.checkIfRemoteCentralAccessAllowed() && appInfo.get(0).getCentralAuth()){
                        ResponseEntity<String> response = externalAccessRolesService.getNameSpaceIfExists(appInfo.get(0));
@@ -783,4 +833,29 @@ public class RoleManageController extends EPRestrictedBaseController {
                EcompPortalUtils.setBadPermissions(user, response, "createAdmin");
                response.getWriter().write("Unauthorized User");
        }
+       
+       @RequestMapping(value = { "/portalApi/uploadRoleFunction/{appId}" }, method = RequestMethod.POST, produces = "application/json")
+       public PortalRestResponse<String> bulkUploadRoleFunc(HttpServletRequest request, HttpServletResponse response,
+                       @RequestBody UploadRoleFunctionExtSystem data, @PathVariable("appId") Long appId) {
+               EPUser user = EPUserUtils.getUserSession(request);
+               try {
+                       EPApp app = appService.getApp(appId);
+                       if (isAuthorizedUser(user, app)) {
+                               fieldsValidation(app);
+                               externalAccessRolesService.bulkUploadRoleFunc(data, app);
+                               String activityCode =  EcompAuditLog.CD_ACTIVITY_EXTERNAL_AUTH_UPDATE_ROLE_AND_FUNCTION;
+                               String code = data.getName()+","+data.getType()+ PIPE + data.getInstance() + PIPE + data.getAction();
+                               logExterlaAuthRoleFunctionActivity(code , user, app, activityCode);
+                       } else {
+                               logger.info(EELFLoggerDelegate.auditLogger,
+                                               "RoleManageController.syncRoles, Unauthorized user:{}", user != null ? user.getOrgUserId() : "");
+                               EcompPortalUtils.setBadPermissions(user, response, "createAdmin");
+                               return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, "Unauthorized User", "Failure");
+                       }
+               } catch (Exception e) {
+                       logger.error(EELFLoggerDelegate.errorLogger, "Failed bulkUploadRoleFunc!", e);
+                       return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, e.getMessage(), "Failed");
+               }
+               return new PortalRestResponse<>(PortalRestStatusEnum.OK, "Uploaded Role Function successfully!", "Success");
+       }
 }