diff options
Diffstat (limited to 'ecomp-portal-BE-os/src')
14 files changed, 301 insertions, 164 deletions
diff --git a/ecomp-portal-BE-os/src/main/java/org/onap/portalapp/authentication/OpenIdConnectLoginStrategy.java b/ecomp-portal-BE-os/src/main/java/org/onap/portalapp/authentication/OpenIdConnectLoginStrategy.java index 4306d1f8..456f0011 100644 --- a/ecomp-portal-BE-os/src/main/java/org/onap/portalapp/authentication/OpenIdConnectLoginStrategy.java +++ b/ecomp-portal-BE-os/src/main/java/org/onap/portalapp/authentication/OpenIdConnectLoginStrategy.java @@ -55,12 +55,9 @@ import org.springframework.util.StringUtils; import org.springframework.web.servlet.ModelAndView; public class OpenIdConnectLoginStrategy extends org.onap.portalsdk.core.auth.LoginStrategy implements org.onap.portalapp.authentication.LoginStrategy { - - private EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(OpenIdConnectLoginStrategy.class); - + private static final EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(OpenIdConnectLoginStrategy.class); private static final String GLOBAL_LOCATION_KEY = "Location"; - @SuppressWarnings("rawtypes") public boolean login(HttpServletRequest request, HttpServletResponse response) throws Exception{ logger.info("Attempting Login"); @@ -93,7 +90,7 @@ public class OpenIdConnectLoginStrategy extends org.onap.portalsdk.core.auth.Log String loginUrl = SystemProperties.getProperty(EPSystemProperties.LOGIN_URL_NO_RET_VAL); logger.info(EELFLoggerDelegate.errorLogger, "Authentication Mechanism: '" + authentication + "'."); - if (authentication == null || authentication.equals("") || authentication.trim().equals("OIDC")) { + if (authentication == null || "".equals(authentication) || "OIDC".equals(authentication.trim())) { response.sendRedirect("oid-login"); } else { logger.info(EELFLoggerDelegate.errorLogger, "No cookies are found, redirecting the request to '" + loginUrl + "'."); @@ -108,10 +105,10 @@ public class OpenIdConnectLoginStrategy extends org.onap.portalsdk.core.auth.Log } @Override - public ModelAndView doLogin(HttpServletRequest request, HttpServletResponse response) throws Exception { + public ModelAndView doLogin(HttpServletRequest request, HttpServletResponse response) throws PortalAPIException { String message = "Method not implmented; Cannot be called"; logger.error(EELFLoggerDelegate.errorLogger, message); - throw new Exception(message); + throw new PortalAPIException(message); } @Override diff --git a/ecomp-portal-BE-os/src/main/java/org/onap/portalapp/authentication/SimpleLoginStrategy.java b/ecomp-portal-BE-os/src/main/java/org/onap/portalapp/authentication/SimpleLoginStrategy.java index dc3f7601..a5f87908 100644 --- a/ecomp-portal-BE-os/src/main/java/org/onap/portalapp/authentication/SimpleLoginStrategy.java +++ b/ecomp-portal-BE-os/src/main/java/org/onap/portalapp/authentication/SimpleLoginStrategy.java @@ -40,6 +40,7 @@ package org.onap.portalapp.authentication; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; +import lombok.NoArgsConstructor; import org.onap.portalapp.command.EPLoginBean; import org.onap.portalapp.portal.service.EPLoginService; import org.onap.portalapp.portal.service.EPRoleFunctionService; @@ -54,18 +55,21 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.util.StringUtils; import org.springframework.web.servlet.ModelAndView; +@NoArgsConstructor public class SimpleLoginStrategy extends org.onap.portalsdk.core.auth.LoginStrategy implements LoginStrategy{ - - @Autowired + private static final String GLOBAL_LOCATION_KEY = "Location"; + private static final EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(SimpleLoginStrategy.class); + private EPLoginService loginService; + private EPRoleFunctionService ePRoleFunctionService; @Autowired - private EPRoleFunctionService ePRoleFunctionService; - - private static final String GLOBAL_LOCATION_KEY = "Location"; - - EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(SimpleLoginStrategy.class); - + public SimpleLoginStrategy(EPLoginService loginService, + EPRoleFunctionService ePRoleFunctionService) { + this.loginService = loginService; + this.ePRoleFunctionService = ePRoleFunctionService; + } + public boolean login(HttpServletRequest request, HttpServletResponse response) throws Exception{ logger.info("Attempting 'Simple' Login"); @@ -79,9 +83,7 @@ public class SimpleLoginStrategy extends org.onap.portalsdk.core.auth.LoginStrat commandBean = loginService.findUser(commandBean, (String)request.getAttribute(MenuProperties.MENU_PROPERTIES_FILENAME_KEY), null); // in case authentication has passed but user is not in the ONAP data base, return a Guest User to the home page. - if (commandBean.getUser() == null) { - } - else { + if (commandBean.getUser() != null) { // store the currently logged in user's information in the session EPUserUtils.setUserSession(request, commandBean.getUser(), commandBean.getMenu(), commandBean.getBusinessDirectMenu(), "", ePRoleFunctionService); logger.info(EELFLoggerDelegate.debugLogger, commandBean.getUser().getOrgUserId() + " exists in the the system."); @@ -96,15 +98,15 @@ public class SimpleLoginStrategy extends org.onap.portalsdk.core.auth.LoginStrat String authentication = SystemProperties.getProperty(SystemProperties.AUTHENTICATION_MECHANISM); String loginUrl = SystemProperties.getProperty(EPSystemProperties.LOGIN_URL_NO_RET_VAL); logger.info(EELFLoggerDelegate.errorLogger, "Authentication Mechanism: '" + authentication + "'."); - if (authentication == null || authentication.equals("") || authentication.trim().equals("BOTH")) { + if (authentication == null || authentication.isEmpty() || "BOTH".equals(authentication.trim())) { logger.info(EELFLoggerDelegate.errorLogger, "No cookies are found, redirecting the request to '" + loginUrl + "'."); response.setStatus(HttpServletResponse.SC_MOVED_TEMPORARILY); - response.setHeader(GLOBAL_LOCATION_KEY, loginUrl); //returnUrl + "/index.htm"); + response.setHeader(GLOBAL_LOCATION_KEY, loginUrl); }else { logger.info(EELFLoggerDelegate.errorLogger, "No cookies are found, redirecting the request to '" + loginUrl + "'."); response.setStatus(HttpServletResponse.SC_MOVED_TEMPORARILY); - response.setHeader(GLOBAL_LOCATION_KEY, loginUrl); //returnUrl + "/index.htm"); + response.setHeader(GLOBAL_LOCATION_KEY, loginUrl); } } catch(Exception e) { logger.error(EELFLoggerDelegate.errorLogger, "login failed", e); @@ -116,10 +118,10 @@ public class SimpleLoginStrategy extends org.onap.portalsdk.core.auth.LoginStrat } @Override - public ModelAndView doLogin(HttpServletRequest request, HttpServletResponse response) throws Exception { + public ModelAndView doLogin(HttpServletRequest request, HttpServletResponse response) throws PortalAPIException { String message = "Method not implmented; Cannot be called"; logger.error(EELFLoggerDelegate.errorLogger, message); - throw new Exception(message); + throw new PortalAPIException(message); } @Override diff --git a/ecomp-portal-BE-os/src/main/java/org/onap/portalapp/controller/LoginController.java b/ecomp-portal-BE-os/src/main/java/org/onap/portalapp/controller/LoginController.java index 0ba7bdc6..56064b99 100644 --- a/ecomp-portal-BE-os/src/main/java/org/onap/portalapp/controller/LoginController.java +++ b/ecomp-portal-BE-os/src/main/java/org/onap/portalapp/controller/LoginController.java @@ -39,6 +39,7 @@ package org.onap.portalapp.controller; import static com.att.eelf.configuration.Configuration.MDC_KEY_REQUEST_ID; +import java.io.IOException; import java.net.MalformedURLException; import java.net.URL; import java.net.URLDecoder; @@ -68,8 +69,10 @@ import org.onap.portalsdk.core.menu.MenuProperties; import org.onap.portalsdk.core.util.SystemProperties; import org.slf4j.MDC; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.HttpStatus; import org.springframework.stereotype.Controller; import org.springframework.util.StopWatch; +import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; @@ -409,4 +412,9 @@ public class LoginController extends EPUnRestrictedBaseController implements Log this.sharedContextService = sharedContextService; } + @ExceptionHandler(Exception.class) + protected void handleBadRequests(Exception e, HttpServletResponse response) throws IOException { + logger.warn(EELFLoggerDelegate.errorLogger, "Handling bad request", e); + response.sendError(HttpStatus.BAD_REQUEST.value()); + } } diff --git a/ecomp-portal-BE-os/src/main/java/org/onap/portalapp/controller/ONAPLoginController.java b/ecomp-portal-BE-os/src/main/java/org/onap/portalapp/controller/ONAPLoginController.java index 1da1d1bb..98cd790f 100644 --- a/ecomp-portal-BE-os/src/main/java/org/onap/portalapp/controller/ONAPLoginController.java +++ b/ecomp-portal-BE-os/src/main/java/org/onap/portalapp/controller/ONAPLoginController.java @@ -37,12 +37,10 @@ */ package org.onap.portalapp.controller; -import java.util.HashMap; -import java.util.Map; - import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; +import lombok.NoArgsConstructor; import org.onap.portalsdk.core.auth.LoginStrategy; import org.onap.portalsdk.core.controller.UnRestrictedBaseController; import org.onap.portalsdk.core.onboarding.listener.PortalTimeoutHandler; @@ -57,14 +55,20 @@ import org.springframework.web.servlet.ModelAndView; @Controller @RequestMapping("/") +@NoArgsConstructor public class ONAPLoginController extends UnRestrictedBaseController { - @Autowired - ProfileService service; - @Autowired + private ProfileService service; private LoginService loginService; - @Autowired private LoginStrategy loginStrategy; - String viewName; + private String viewName; + + @Autowired + public ONAPLoginController(ProfileService service, LoginService loginService, + LoginStrategy loginStrategy) { + this.service = service; + this.loginService = loginService; + this.loginStrategy = loginStrategy; + } @RequestMapping(value = { "/doLogin" }, method = RequestMethod.GET) public ModelAndView doLogin(HttpServletRequest request, HttpServletResponse response) throws Exception { @@ -80,14 +84,6 @@ public class ONAPLoginController extends UnRestrictedBaseController { PortalTimeoutHandler.sessionCreated(jSessionId, jSessionId, AppUtils.getSession(request)); } - public String getViewName() { - return viewName; - } - - public void setViewName(String viewName) { - this.viewName = viewName; - } - public LoginService getLoginService() { return loginService; } @@ -96,4 +92,13 @@ public class ONAPLoginController extends UnRestrictedBaseController { this.loginService = loginService; } + @Override + public String getViewName() { + return viewName; + } + + @Override + public void setViewName(String viewName) { + this.viewName = viewName; + } } diff --git a/ecomp-portal-BE-os/src/main/java/org/onap/portalapp/controller/ONAPWelcomeController.java b/ecomp-portal-BE-os/src/main/java/org/onap/portalapp/controller/ONAPWelcomeController.java index 26564a04..4d3c82a2 100644 --- a/ecomp-portal-BE-os/src/main/java/org/onap/portalapp/controller/ONAPWelcomeController.java +++ b/ecomp-portal-BE-os/src/main/java/org/onap/portalapp/controller/ONAPWelcomeController.java @@ -44,9 +44,11 @@ import javax.annotation.Resource; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; +import lombok.NoArgsConstructor; import org.mitre.openid.connect.client.SubjectIssuerGrantedAuthority; import org.onap.portalapp.controller.EPRestrictedBaseController; import org.onap.portalapp.portal.logging.aop.EPAuditLog; +import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.EnableAspectJAutoProxy; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; @@ -56,12 +58,11 @@ import org.springframework.web.servlet.ModelAndView; @Controller @RequestMapping("/") -@org.springframework.context.annotation.Configuration +@Configuration @EnableAspectJAutoProxy @EPAuditLog +@NoArgsConstructor public class ONAPWelcomeController extends EPRestrictedBaseController{ - String viewName; - @RequestMapping(value = "/index.htm", method = RequestMethod.GET) public String getIndexPage(HttpServletRequest request) { return "/index"; @@ -72,14 +73,6 @@ public class ONAPWelcomeController extends EPRestrictedBaseController{ return "forward:/index.html"; } - protected String getViewName() { - return viewName; - } - - protected void setViewName(String viewName) { - this.viewName = viewName; - } - // TODO Need to revisit this as its conflicting with Spring Security; check web.xml's oid-context.xml config //@Resource(name = "namedAdmins") private Set<SubjectIssuerGrantedAuthority> admins; diff --git a/ecomp-portal-BE-os/src/main/java/org/onap/portalapp/controller/PeerBroadcastSocket.java b/ecomp-portal-BE-os/src/main/java/org/onap/portalapp/controller/PeerBroadcastSocket.java index cbc34337..c80419f9 100644 --- a/ecomp-portal-BE-os/src/main/java/org/onap/portalapp/controller/PeerBroadcastSocket.java +++ b/ecomp-portal-BE-os/src/main/java/org/onap/portalapp/controller/PeerBroadcastSocket.java @@ -39,65 +39,34 @@ */ package org.onap.portalapp.controller; +import com.fasterxml.jackson.databind.ObjectMapper; import java.io.IOException; -import java.util.Hashtable; +import java.util.HashMap; import java.util.Map; - +import java.util.Optional; import javax.websocket.OnClose; import javax.websocket.OnMessage; import javax.websocket.OnOpen; import javax.websocket.Session; import javax.websocket.server.ServerEndpoint; - import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; -import com.fasterxml.jackson.databind.ObjectMapper; @ServerEndpoint("/opencontact") public class PeerBroadcastSocket { + private static final EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(PeerBroadcastSocket.class); + private static final ObjectMapper mapper = new ObjectMapper(); - EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(PeerBroadcastSocket.class); - - public final static Map<String, Object> channelMap = new Hashtable<String, Object>(); - public Map<String, String> sessionMap = new Hashtable<String, String>(); - ObjectMapper mapper = new ObjectMapper(); + protected static final Map<String, Object> channelMap = new HashMap<>(); + private Map<String, String> sessionMap = new HashMap<>(); @OnMessage public void message(String message, Session session) { try { - // JSONObject jsonObject = new JSONObject(message); - @SuppressWarnings("unchecked") Map<String, Object> jsonObject = mapper.readValue(message, Map.class); - try { - Object from = jsonObject.get("from"); - if (from != null) { - if(channelMap.get(from.toString()) == null) { - channelMap.put(from.toString(), session); - sessionMap.put(session.getId(), from.toString()); - } - } - } catch (Exception je) { - logger.error(EELFLoggerDelegate.errorLogger, "Failed to read value" + je.getMessage()); - } - - try { - Object to = jsonObject.get("to"); - if (to == null) - return; - Object toSessionObj = channelMap.get(to); - /*if (toSessionObj != null) { - Session toSession = null; - toSession = (Session) toSessionObj; - toSession.getBasicRemote().sendText(message); - } -*/ - } catch (Exception ex) { - logger.error(EELFLoggerDelegate.errorLogger, "Failed to send text" + ex.getMessage()); - } - + save(jsonObject, session); } catch (Exception ex) { logger.error(EELFLoggerDelegate.errorLogger, "Failed" + ex.getMessage()); } - } @OnOpen @@ -122,5 +91,13 @@ public class PeerBroadcastSocket { logger.info(EELFLoggerDelegate.debugLogger, "Channel closed"); } + private void save(Map<String, Object> jsonObject, Session session) { + final Optional<String> from = Optional.of(jsonObject.get("from").toString()); + if (from.isPresent() && channelMap.get(from.get()) == null) { + this.channelMap.put(from.toString(), session); + this.sessionMap.put(session.getId(), from.toString()); + } + } + } diff --git a/ecomp-portal-BE-os/src/main/java/org/onap/portalapp/filter/SecurityXssFilter.java b/ecomp-portal-BE-os/src/main/java/org/onap/portalapp/filter/SecurityXssFilter.java index 25eee828..703019f9 100644 --- a/ecomp-portal-BE-os/src/main/java/org/onap/portalapp/filter/SecurityXssFilter.java +++ b/ecomp-portal-BE-os/src/main/java/org/onap/portalapp/filter/SecurityXssFilter.java @@ -1,9 +1,9 @@ - /*- * ============LICENSE_START========================================== * ONAP Portal * =================================================================== * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * Modifications Copyright (c) 2019 Samsung * =================================================================== * * Unless otherwise specified, all software contained herein is licensed @@ -36,6 +36,7 @@ * * */ + package org.onap.portalapp.filter; import java.io.BufferedReader; @@ -48,7 +49,6 @@ import java.util.Enumeration; import javax.servlet.FilterChain; import javax.servlet.ReadListener; -import javax.servlet.ServletException; import javax.servlet.ServletInputStream; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequestWrapper; @@ -62,7 +62,7 @@ import org.springframework.web.filter.OncePerRequestFilter; public class SecurityXssFilter extends OncePerRequestFilter { - private EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(SecurityXssFilter.class); + private EELFLoggerDelegate sxLogger = EELFLoggerDelegate.getLogger(SecurityXssFilter.class); private static final String APPLICATION_JSON = "application/json"; @@ -120,40 +120,47 @@ public class SecurityXssFilter extends OncePerRequestFilter { @Override public void setReadListener(ReadListener readListener) { - + // do nothing } - } } @Override protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) - throws ServletException, IOException { + throws IOException { StringBuilder requestURL = new StringBuilder(request.getRequestURL().toString()); - String queryString = request.getQueryString(); - String requestUrl = ""; - if (queryString == null) { - requestUrl = requestURL.toString(); - } else { - requestUrl = requestURL.append('?').append(queryString).toString(); - } - validateRequest(requestUrl, response); + String queryString = request.getQueryString(); + String requestUrl; + + if (queryString == null) { + requestUrl = requestURL.toString(); + } else { + requestUrl = requestURL.append('?').append(queryString).toString(); + } + + validateRequest(requestUrl, response); StringBuilder headerValues = new StringBuilder(); Enumeration<String> headerNames = request.getHeaderNames(); + while (headerNames.hasMoreElements()) { - String key = (String) headerNames.nextElement(); + String key = headerNames.nextElement(); String value = request.getHeader(key); headerValues.append(value); } + validateRequest(headerValues.toString(), response); + if (validateRequestType(request)) { request = new RequestWrapper(request); String requestData = IOUtils.toString(request.getInputStream(), StandardCharsets.UTF_8.toString()); validateRequest(requestData, response); - filterChain.doFilter(request, response); + } - } else { + try { filterChain.doFilter(request, response); + } catch (Exception e) { + sxLogger.warn(EELFLoggerDelegate.errorLogger, "Handling bad request", e); + response.sendError(org.springframework.http.HttpStatus.BAD_REQUEST.value(), "Handling bad request"); } } @@ -171,9 +178,8 @@ public class SecurityXssFilter extends OncePerRequestFilter { throw new SecurityException(ERROR_BAD_REQUEST); } } catch (Exception e) { - logger.error(EELFLoggerDelegate.errorLogger, "doFilterInternal() failed due to BAD_REQUEST", e); + sxLogger.error(EELFLoggerDelegate.errorLogger, "doFilterInternal() failed due to BAD_REQUEST", e); response.getWriter().close(); - return; } } -}
\ No newline at end of file +} diff --git a/ecomp-portal-BE-os/src/main/java/org/onap/portalapp/portal/controller/AppsOSController.java b/ecomp-portal-BE-os/src/main/java/org/onap/portalapp/portal/controller/AppsOSController.java index ed540551..915c5e08 100644 --- a/ecomp-portal-BE-os/src/main/java/org/onap/portalapp/portal/controller/AppsOSController.java +++ b/ecomp-portal-BE-os/src/main/java/org/onap/portalapp/portal/controller/AppsOSController.java @@ -40,8 +40,13 @@ package org.onap.portalapp.portal.controller; import java.util.HashMap; import java.util.Map; +import java.util.Set; import javax.servlet.http.HttpServletRequest; +import javax.validation.ConstraintViolation; +import javax.validation.Validation; +import javax.validation.Validator; +import javax.validation.ValidatorFactory; import org.json.JSONObject; import org.onap.portalapp.portal.controller.AppsController; import org.onap.portalapp.portal.domain.EPUser; @@ -53,6 +58,7 @@ import org.onap.portalapp.portal.service.EPAppService; import org.onap.portalapp.portal.service.PersUserAppService; import org.onap.portalapp.portal.service.UserService; import org.onap.portalapp.util.EPUserUtils; +import org.onap.portalapp.validation.SecureString; import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.EnableAspectJAutoProxy; @@ -67,6 +73,7 @@ import org.springframework.web.bind.annotation.RestController; @EnableAspectJAutoProxy @EPAuditLog public class AppsOSController extends AppsController { + private static final ValidatorFactory validatorFactory = Validation.buildDefaultValidatorFactory(); static final String FAILURE = "failure"; EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(AppsOSController.class); @@ -113,9 +120,20 @@ public class AppsOSController extends AppsController { @RequestMapping(value = { "/portalApi/currentUserProfile/{loginId}" }, method = RequestMethod.GET, produces = "application/json") public String getCurrentUserProfile(HttpServletRequest request, @PathVariable("loginId") String loginId) { + + if(loginId != null){ + Validator validator = validatorFactory.getValidator(); + SecureString secureString = new SecureString(loginId); + Set<ConstraintViolation<SecureString>> constraintViolations = validator.validate(secureString); + + if (!constraintViolations.isEmpty()){ + return "loginId is not valid"; + } + } + - Map<String,String> map = new HashMap<String,String>(); - EPUser user = null; + Map<String,String> map = new HashMap<>(); + EPUser user; try { user = (EPUser) userService.getUserByUserId(loginId).get(0); map.put("firstName", user.getFirstName()); @@ -128,7 +146,7 @@ public class AppsOSController extends AppsController { logger.error(EELFLoggerDelegate.errorLogger, "Failed to get user info", e); } - JSONObject j = new JSONObject(map);; + JSONObject j = new JSONObject(map); return j.toString(); } diff --git a/ecomp-portal-BE-os/src/main/java/org/onap/portalapp/portal/controller/DashboardSearchResultController.java b/ecomp-portal-BE-os/src/main/java/org/onap/portalapp/portal/controller/DashboardSearchResultController.java index 0be57120..1dff6040 100644 --- a/ecomp-portal-BE-os/src/main/java/org/onap/portalapp/portal/controller/DashboardSearchResultController.java +++ b/ecomp-portal-BE-os/src/main/java/org/onap/portalapp/portal/controller/DashboardSearchResultController.java @@ -48,7 +48,6 @@ import java.util.Map; import javax.servlet.http.HttpServletRequest; import org.onap.portalapp.controller.EPRestrictedBaseController; -import org.onap.portalapp.portal.controller.DashboardSearchResultController; import org.onap.portalapp.portal.domain.EPUser; import org.onap.portalapp.portal.ecomp.model.PortalRestResponse; import org.onap.portalapp.portal.ecomp.model.PortalRestStatusEnum; @@ -57,6 +56,8 @@ import org.onap.portalapp.portal.service.DashboardSearchService; import org.onap.portalapp.portal.transport.CommonWidget; import org.onap.portalapp.portal.transport.CommonWidgetMeta; import org.onap.portalapp.util.EPUserUtils; +import org.onap.portalapp.validation.DataValidator; +import org.onap.portalapp.validation.SecureString; import org.onap.portalsdk.core.domain.support.CollaborateList; import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; import org.springframework.beans.factory.annotation.Autowired; @@ -71,6 +72,7 @@ import org.springframework.web.bind.annotation.RestController; public class DashboardSearchResultController extends EPRestrictedBaseController { private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(DashboardSearchResultController.class); + private DataValidator dataValidator = new DataValidator(); @Autowired private DashboardSearchService searchService; @@ -86,7 +88,12 @@ public class DashboardSearchResultController extends EPRestrictedBaseController @RequestMapping(value = "/widgetData", method = RequestMethod.GET, produces = "application/json") public PortalRestResponse<CommonWidgetMeta> getWidgetData(HttpServletRequest request, @RequestParam String resourceType) { - return new PortalRestResponse<CommonWidgetMeta>(PortalRestStatusEnum.OK, "success", + if (resourceType !=null){ + SecureString secureString = new SecureString(resourceType); + if (!dataValidator.isValid(secureString)) + return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, "Provided data is invalid", null); + } + return new PortalRestResponse<>(PortalRestStatusEnum.OK, "success", searchService.getWidgetData(resourceType)); } @@ -100,9 +107,14 @@ public class DashboardSearchResultController extends EPRestrictedBaseController @RequestMapping(value = "/widgetDataBulk", method = RequestMethod.POST, produces = "application/json") public PortalRestResponse<String> saveWidgetDataBulk(@RequestBody CommonWidgetMeta commonWidgetMeta) { logger.debug(EELFLoggerDelegate.debugLogger, "saveWidgetDataBulk: argument is {}", commonWidgetMeta); - if (commonWidgetMeta.getCategory() == null || commonWidgetMeta.getCategory().trim().equals("")) + if (commonWidgetMeta.getCategory() == null || commonWidgetMeta.getCategory().trim().equals("")){ return new PortalRestResponse<String>(PortalRestStatusEnum.ERROR, "ERROR", "Category cannot be null or empty"); + }else { + if(!dataValidator.isValid(commonWidgetMeta)) + return new PortalRestResponse<String>(PortalRestStatusEnum.ERROR, "ERROR", + "Category is not valid"); + } // validate dates for (CommonWidget cw : commonWidgetMeta.getItems()) { String err = validateCommonWidget(cw); @@ -123,13 +135,18 @@ public class DashboardSearchResultController extends EPRestrictedBaseController @RequestMapping(value = "/widgetData", method = RequestMethod.POST, produces = "application/json") public PortalRestResponse<String> saveWidgetData(@RequestBody CommonWidget commonWidget) { logger.debug(EELFLoggerDelegate.debugLogger, "saveWidgetData: argument is {}", commonWidget); - if (commonWidget.getCategory() == null || commonWidget.getCategory().trim().equals("")) - return new PortalRestResponse<String>(PortalRestStatusEnum.ERROR, "ERROR", + if (commonWidget.getCategory() == null || commonWidget.getCategory().trim().equals("")){ + return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, "ERROR", "Cateogry cannot be null or empty"); + }else { + if(!dataValidator.isValid(commonWidget)) + return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, "ERROR", + "Category is not valid"); + } String err = validateCommonWidget(commonWidget); if (err != null) - return new PortalRestResponse<String>(PortalRestStatusEnum.ERROR, err, null); - return new PortalRestResponse<String>(PortalRestStatusEnum.OK, "success", + return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, err, null); + return new PortalRestResponse<>(PortalRestStatusEnum.OK, "success", searchService.saveWidgetData(commonWidget)); } @@ -165,7 +182,10 @@ public class DashboardSearchResultController extends EPRestrictedBaseController @RequestMapping(value = "/deleteData", method = RequestMethod.POST, produces = "application/json") public PortalRestResponse<String> deleteWidgetData(@RequestBody CommonWidget commonWidget) { logger.debug(EELFLoggerDelegate.debugLogger, "deleteWidgetData: argument is {}", commonWidget); - return new PortalRestResponse<String>(PortalRestStatusEnum.OK, "success", + if(!dataValidator.isValid(commonWidget)) + return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, "ERROR", + "Data is not valid"); + return new PortalRestResponse<>(PortalRestStatusEnum.OK, "success", searchService.deleteWidgetData(commonWidget)); } @@ -180,16 +200,24 @@ public class DashboardSearchResultController extends EPRestrictedBaseController @RequestMapping(value = "/allPortal", method = RequestMethod.GET, produces = "application/json") public PortalRestResponse<Map<String, List<SearchResultItem>>> searchPortal(HttpServletRequest request, @RequestParam String searchString) { + if(searchString!=null){ + SecureString secureString = new SecureString(searchString); + if(!dataValidator.isValid(secureString)){ + return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, + "searchPortal: User object is invalid", + null); + } + } EPUser user = EPUserUtils.getUserSession(request); try { if (user == null) { return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, "searchPortal: User object is null? - check logs", - new HashMap<String, List<SearchResultItem>>()); + new HashMap<>()); } else if (searchString == null || searchString.trim().length() == 0) { return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, "searchPortal: String string is null", - new HashMap<String, List<SearchResultItem>>()); + new HashMap<>()); } else { logger.debug(EELFLoggerDelegate.debugLogger, "searchPortal: user {}, search string '{}'", user.getLoginId(), searchString); @@ -200,7 +228,7 @@ public class DashboardSearchResultController extends EPRestrictedBaseController } catch (Exception e) { logger.error(EELFLoggerDelegate.errorLogger, "searchPortal failed", e); return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, e.getMessage() + " - check logs.", - new HashMap<String, List<SearchResultItem>>()); + new HashMap<>()); } } diff --git a/ecomp-portal-BE-os/src/main/webapp/WEB-INF/conf/sql.properties b/ecomp-portal-BE-os/src/main/webapp/WEB-INF/conf/sql.properties index 83779052..8663cd44 100644 --- a/ecomp-portal-BE-os/src/main/webapp/WEB-INF/conf/sql.properties +++ b/ecomp-portal-BE-os/src/main/webapp/WEB-INF/conf/sql.properties @@ -291,19 +291,6 @@ random.string = select ( 'Z' || round(random() * 1000000000000)) scheduler.user.emails = SELECT au.user_id FROM (SELECT rs.schedule_id, rs.rep_id FROM cr_report_schedule rs WHERE rs.enabled_yn='Y' AND rs.start_date <= now() AND rs.end_date >= now() AND rs.run_date IS NOT NULL AND rs.schedule_id = [p_schedule_id] ) x, cr_report r, fn_user au WHERE x.rep_id = r.rep_id AND au.user_id IN (SELECT rsu.user_id FROM cr_report_schedule_users rsu WHERE rsu.schedule_id = x.schedule_id and rsu.schedule_id = [p_schedule_id] UNION SELECT ur.user_id FROM fn_user_role ur WHERE ur.role_id IN (SELECT rsu2.role_id FROM cr_report_schedule_users rsu2 WHERE rsu2.schedule_id = x.schedule_id and rsu2.schedule_id = [p_schedule_id])) - -# my logins - -app.query = SELECT APP_ID, ML_APP_NAME, MOTS_ID from fn_app where ((enabled = 'Y' and open = 'N') or app_id = 1 ) - -user.log.query = SELECT DISTINCT IFNULL(ORG_USER_ID, '') CUID, '' AWID, CONCAT('"',IFNULL(ORG_USER_ID, ''),'"') APPLICATIONUSERID, CONCAT('"',IFNULL(FIRST_NAME, ''),'"') FIRST_NAME, CONCAT('"',substr(IFNULL(MIDDLE_NAME, ''), 0, 1),'"') MIDDLE_INITIAL, CONCAT('"',IFNULL(LAST_NAME, ''),'"') LAST_NAME, IFNULL(DATE_FORMAT(LAST_LOGIN_DATE, '%Y/%m/%d'), '') LAST_LOGON_DATE, DATE_FORMAT(CREATED_DATE, '%Y/%m/%d') ACCOUNT_ACTIVATION_DATE, IFNULL(DATE_FORMAT(MODIFIED_DATE, '%Y/%m/%d'), '') LAST_DATE_ACCOUNT_MODIFIED, '' LAST_PASSWORD_CHANGE_DATE, CONCAT('"',IFNULL(FIRST_NAME, ''),' ',IFNULL(MIDDLE_NAME, ''),' ',IFNULL(LAST_NAME, ''),'"') FULL_USER_NAME, '' NT_ID, IFNULL(EMAIL, '') EMAIL FROM FN_USER FU, FN_USER_ROLE FUR, FN_ROLE FR WHERE FU.USER_ID = FUR.USER_ID and FUR.ROLE_ID = FR.ROLE_ID and ((FUR.APP_ID = 1 and FUR.APP_ID = ? and FR.ROLE_NAME <> 'Standard User') or (FUR.APP_ID = ? and FUR.APP_ID <> 1)) and FU.ACTIVE_YN = 'Y' and FU.org_user_id is not null order by 1 - -profile.log.query = SELECT DISTINCT CONCAT('"' , ROLE_NAME , '"') PROFILE_NAME, '""' SECURITY_SETTINGS FROM FN_ROLE FR, FN_USER_ROLE FUR WHERE FUR.ROLE_ID = FR.ROLE_ID and FR.ACTIVE_YN = 'Y' and ((FUR.APP_ID = 1 and FUR.APP_ID = ? and FR.ROLE_NAME <> 'Standard User') or (FUR.APP_ID = ? and FUR.APP_ID <> 1)) ORDER BY 1 - -user.profile.log.query = SELECT DISTINCT IFNULL(ORG_USER_ID, '') CUID, '' AWID, CONCAT('"' , IFNULL(ORG_USER_ID, '') , '"') APPLICATIONUSERID , CONCAT('"' , ROLE_NAME , '"') PROFILE_NAME FROM FN_USER A, FN_USER_ROLE B, FN_ROLE C WHERE A.USER_ID = B.USER_ID AND B.ROLE_ID = C.ROLE_ID AND A.ACTIVE_YN = 'Y' AND C.ACTIVE_YN = 'Y' AND a.ORG_USER_ID is not null AND ((B.APP_ID = 1 and B.APP_ID = ? and C.ROLE_NAME <> 'Standard User') or (B.APP_ID = ? and B.APP_ID <> 1)) ORDER BY 1 - -all.accounts.log.query = SELECT DISTINCT IFNULL(ORG_USER_ID, '') CUID, (case when A.ACTIVE_YN='Y' then 'ACTIVE' else 'INACTIVE' end) ACTIVE_YN, CONCAT('"' , IFNULL(ORG_USER_ID, '') , '"') APPLICATIONUSERID , IFNULL(DATE_FORMAT(LAST_LOGIN_DATE, '%Y/%m/%d'), '') LAST_LOGON_DATE, '' LAST_PASSWORD_CHANGE_DATE, CONCAT('"' , ROLE_NAME , '"') PROFILE_NAME FROM FN_USER A, FN_USER_ROLE B, FN_ROLE C WHERE A.USER_ID = B.USER_ID AND B.ROLE_ID = C.ROLE_ID AND a.ORG_USER_ID is not null AND ((B.APP_ID = 1 and B.APP_ID = ? and C.ROLE_NAME <> 'Standard User') or (B.APP_ID = ? and B.APP_ID <> 1)) ORDER BY 1 - # basic sql seq.next.val = SELECT nextval('[sequenceName]') AS id diff --git a/ecomp-portal-BE-os/src/main/webapp/WEB-INF/jsp/login.jsp b/ecomp-portal-BE-os/src/main/webapp/WEB-INF/jsp/login.jsp index 8d80d334..99c5af4f 100644 --- a/ecomp-portal-BE-os/src/main/webapp/WEB-INF/jsp/login.jsp +++ b/ecomp-portal-BE-os/src/main/webapp/WEB-INF/jsp/login.jsp @@ -174,7 +174,8 @@ app.controller("externalLoginController", function ($scope) { success:function (response){ if(response.success=="success"){ //window.location.href = 'applicationsHome'; - window.location.href= "<%=frontUrl%>" + window.location.href= "<%=frontUrl%>", + sessionStorage.setItem('userId',$scope.loginId) }else{ $("#errorInfo span").text(response); //$("#errorInfo").text = response; diff --git a/ecomp-portal-BE-os/src/main/webapp/WEB-INF/web.xml b/ecomp-portal-BE-os/src/main/webapp/WEB-INF/web.xml index 1181a2fd..af712d4e 100644 --- a/ecomp-portal-BE-os/src/main/webapp/WEB-INF/web.xml +++ b/ecomp-portal-BE-os/src/main/webapp/WEB-INF/web.xml @@ -106,32 +106,32 @@ <filter-name>SecurityXssFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> - <!-- <filter> - <filter-name>CadiAuthFilter</filter-name> - <filter-class>org.onap.portalsdk.core.onboarding.crossapi.CadiAuthFilter</filter-class> - <init-param> - <param-name>cadi_prop_files</param-name> - Add Absolute path of cadi.properties - <param-value>{Path}/cadi.properties - </param-value> - </init-param> - Add param values with comma delimited values - <init-param> - <param-name>include_url_endpoints</param-name> - <param-value>/auxapi/*</param-value> - </init-param> - <init-param> - <param-name>exclude_url_endpoints</param-name> - <param-value>/api/v3/analytics,/api/v3/storeAnalytics</param-value> - </init-param> - </filter> - <filter-mapping> - <filter-name>CadiAuthFilter</filter-name> - <url-pattern>/auxapi/v3/*</url-pattern> - </filter-mapping> - <filter-mapping> - <filter-name>CadiAuthFilter</filter-name> - <url-pattern>/auxapi/v4/*</url-pattern> +<!-- <filter> --> +<!-- <filter-name>CadiAuthFilter</filter-name> --> +<!-- <filter-class>org.onap.portalsdk.core.onboarding.crossapi.CadiAuthFilter</filter-class> --> +<!-- <init-param> --> +<!-- <param-name>cadi_prop_files</param-name> --> +<!-- Add Absolute path of cadi.properties --> +<!-- <param-value>{Path}/cadi.properties --> +<!-- </param-value> --> +<!-- </init-param> --> +<!-- Add param values with comma delimited values --> +<!-- <init-param> --> +<!-- <param-name>include_url_endpoints</param-name> --> +<!-- <param-value>/auxapi/*</param-value> --> +<!-- </init-param> --> +<!-- <init-param> --> +<!-- <param-name>exclude_url_endpoints</param-name> --> +<!-- <param-value>/api/v3/analytics,/api/v3/storeAnalytics</param-value> --> +<!-- </init-param> --> +<!-- </filter> --> +<!-- <filter-mapping> --> +<!-- <filter-name>CadiAuthFilter</filter-name> --> +<!-- <url-pattern>/auxapi/v3/*</url-pattern> --> +<!-- </filter-mapping> --> +<!-- <filter-mapping> --> +<!-- <filter-name>CadiAuthFilter</filter-name> --> +<!-- <url-pattern>/auxapi/v4/*</url-pattern> --> - </filter-mapping> --> +<!-- </filter-mapping> --> </web-app> diff --git a/ecomp-portal-BE-os/src/test/java/org/onap/portalapp/portal/controller/AppsOSControllerTest.java b/ecomp-portal-BE-os/src/test/java/org/onap/portalapp/portal/controller/AppsOSControllerTest.java index 0596e749..15fe1dd9 100644 --- a/ecomp-portal-BE-os/src/test/java/org/onap/portalapp/portal/controller/AppsOSControllerTest.java +++ b/ecomp-portal-BE-os/src/test/java/org/onap/portalapp/portal/controller/AppsOSControllerTest.java @@ -176,6 +176,17 @@ public class AppsOSControllerTest { } @Test + public void getCurrentUserProfileXSSTest() { + String loginId = "<iframe/src=\"data:text/html,<svg onload=alert(1)>\">"; + EPUser user = mockUser.mockEPUser(); + List<EPUser> expectedList = new ArrayList<>(); + expectedList.add(user); + Mockito.when(userService.getUserByUserId(loginId)).thenReturn(expectedList); + String expectedString = appsOSController.getCurrentUserProfile(mockedRequest, loginId); + assertEquals("loginId is not valid", expectedString); + } + + @Test public void getCurrentUserProfileExceptionTest() { String loginId = "guestT"; EPUser user = mockUser.mockEPUser(); diff --git a/ecomp-portal-BE-os/src/test/java/org/onap/portalapp/portal/controller/DashboardSearchResultControllerTest.java b/ecomp-portal-BE-os/src/test/java/org/onap/portalapp/portal/controller/DashboardSearchResultControllerTest.java index 9edf99e7..ff588daa 100644 --- a/ecomp-portal-BE-os/src/test/java/org/onap/portalapp/portal/controller/DashboardSearchResultControllerTest.java +++ b/ecomp-portal-BE-os/src/test/java/org/onap/portalapp/portal/controller/DashboardSearchResultControllerTest.java @@ -99,6 +99,18 @@ public class DashboardSearchResultControllerTest { } @Test + public void getWidgetDataXSSTest() { + String resourceType = "\"<IMG SRC=\\\"jav\\tascript:alert('XSS');\\\">\""; + PortalRestResponse expectedPortalRestResponse = new PortalRestResponse<>(); + expectedPortalRestResponse.setMessage("Provided data is invalid"); + expectedPortalRestResponse.setStatus(PortalRestStatusEnum.ERROR); + Mockito.when(searchService.getWidgetData(resourceType)).thenReturn(null); + PortalRestResponse acutualPoratlRestResponse = dashboardSearchResultController + .getWidgetData(mockedRequest, resourceType); + assertEquals(acutualPoratlRestResponse, expectedPortalRestResponse); + } + + @Test public void saveWidgetDataBulkIfCatrgoryNullTest() { PortalRestResponse<String> ecpectedPortalRestResponse = new PortalRestResponse<String>(); ecpectedPortalRestResponse.setMessage("ERROR"); @@ -152,6 +164,82 @@ public class DashboardSearchResultControllerTest { } @Test + public void saveWidgetDataBulkXSSTest() { + PortalRestResponse<String> ecpectedPortalRestResponse = new PortalRestResponse<>(); + ecpectedPortalRestResponse.setMessage("ERROR"); + ecpectedPortalRestResponse.setResponse("Category is not valid"); + ecpectedPortalRestResponse.setStatus(PortalRestStatusEnum.ERROR); + + CommonWidgetMeta commonWidgetMeta = new CommonWidgetMeta(); + commonWidgetMeta.setCategory("test"); + + List<CommonWidget> commonWidgetList = new ArrayList<>(); + CommonWidget commonWidget = new CommonWidget(); + commonWidget.setId((long) 1); + commonWidget.setCategory("test"); + commonWidget.setHref("\"<IMG SRC=\\\"jav\\tascript:alert('XSS');\\\">\""); + commonWidget.setTitle("test_title"); + commonWidget.setContent("test_content"); + commonWidget.setEventDate(null); + commonWidget.setSortOrder(1); + + commonWidgetList.add(commonWidget); + + commonWidgetMeta.setItems(commonWidgetList); + + Mockito.when(searchService.saveWidgetDataBulk(commonWidgetMeta)).thenReturn(null); + + PortalRestResponse<String> actualPortalRestResponse = dashboardSearchResultController + .saveWidgetDataBulk(commonWidgetMeta); + assertEquals(ecpectedPortalRestResponse, actualPortalRestResponse); + } + + @Test + public void saveWidgetDataXSSTest() { + PortalRestResponse<String> expectedPortalRestResponse = new PortalRestResponse<>(); + expectedPortalRestResponse.setMessage("ERROR"); + expectedPortalRestResponse.setResponse("Category is not valid"); + expectedPortalRestResponse.setStatus(PortalRestStatusEnum.ERROR); + CommonWidget commonWidget = new CommonWidget(); + commonWidget.setId((long) 1); + commonWidget.setCategory("test"); + commonWidget.setHref("\"<IMG SRC=\"jav\\tascript:alert('XSS');\">\""); + commonWidget.setTitle("test_title"); + commonWidget.setContent("test_content"); + commonWidget.setEventDate(null); + commonWidget.setSortOrder(1); + + Mockito.when(searchService.saveWidgetData(commonWidget)).thenReturn(null); + + PortalRestResponse<String> actualPortalRestResponse = dashboardSearchResultController + .saveWidgetData(commonWidget); + assertEquals(expectedPortalRestResponse, actualPortalRestResponse); + + } + + @Test + public void deleteWidgetDataXSSTest() { + PortalRestResponse<String> expectedPortalRestResponse = new PortalRestResponse<>(); + expectedPortalRestResponse.setMessage("ERROR"); + expectedPortalRestResponse.setResponse("Data is not valid"); + expectedPortalRestResponse.setStatus(PortalRestStatusEnum.ERROR); + CommonWidget commonWidget = new CommonWidget(); + commonWidget.setId((long) 1); + commonWidget.setCategory("test"); + commonWidget.setHref("test_href"); + commonWidget.setTitle("\"<IMG SRC=\"jav\\tascript:alert('XSS');\">\""); + commonWidget.setContent("test_content"); + commonWidget.setEventDate(null); + commonWidget.setSortOrder(1); + Mockito.when(searchService.deleteWidgetData(commonWidget)).thenReturn(null); + + PortalRestResponse<String> actualPortalRestResponse = dashboardSearchResultController + .deleteWidgetData(commonWidget); + + assertEquals(expectedPortalRestResponse, actualPortalRestResponse); + } + + @Test public void saveWidgetDataIfCatagoryNullTest() { PortalRestResponse<String> ecpectedPortalRestResponse = new PortalRestResponse<String>(); ecpectedPortalRestResponse.setMessage("ERROR"); @@ -340,6 +428,22 @@ public class DashboardSearchResultControllerTest { } @Test + public void searchPortalXSS() { + EPUser user = mockUser.mockEPUser(); + Mockito.when(EPUserUtils.getUserSession(mockedRequest)).thenReturn(user); + String searchString = "<script>alert(“XSS”)</script> "; + + PortalRestResponse<Map<String, List<SearchResultItem>>> expectedResult = new PortalRestResponse<Map<String, List<SearchResultItem>>>(); + expectedResult.setMessage("searchPortal: User object is invalid"); + expectedResult.setStatus(PortalRestStatusEnum.ERROR); + + PortalRestResponse<Map<String, List<SearchResultItem>>> actualResult = dashboardSearchResultController + .searchPortal(mockedRequest, searchString); + assertEquals(actualResult, expectedResult); + + } + + @Test public void searchPortalIfSearchExcptionTest() { EPUser user = mockUser.mockEPUser(); ; |