diff options
Diffstat (limited to 'ecomp-portal-BE-common/src/test/java')
19 files changed, 1006 insertions, 209 deletions
diff --git a/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/controller/AppsControllerExternalRequestTest.java b/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/controller/AppsControllerExternalRequestTest.java index 847d4744..9d3c7785 100644 --- a/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/controller/AppsControllerExternalRequestTest.java +++ b/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/controller/AppsControllerExternalRequestTest.java @@ -133,6 +133,24 @@ public class AppsControllerExternalRequestTest extends MockitoTestSuite { } @Test + public void postPortalAdminXSSTest() { + PortalRestResponse<String> expectedportalRestResponse = new PortalRestResponse<String>(); + expectedportalRestResponse.setMessage("Data is not valid"); + expectedportalRestResponse.setResponse(null); + PortalRestStatusEnum portalRestStatusEnum = null; + expectedportalRestResponse.setStatus(portalRestStatusEnum.ERROR); + EPUser user = mockUser.mockEPUser(); + user.setEmail("“><script>alert(“XSS”)</script>"); + user.setLoginPwd("pwd"); + user.setLoginId("Test"); + Mockito.when(EPUserUtils.getUserSession(mockedRequest)).thenReturn(user); + Mockito.when(userService.getUserByUserId(user.getOrgUserId())).thenThrow(nullPointerException); + PortalRestResponse<String> actualPortalRestResponse = appsControllerExternalRequest + .postPortalAdmin(mockedRequest, mockedResponse, user); + assertEquals(expectedportalRestResponse, actualPortalRestResponse); + } + + @Test public void postPortalAdminCreateUserIfNotFoundTest() throws Exception { PortalRestResponse<String> expectedportalRestResponse = new PortalRestResponse<String>(); expectedportalRestResponse.setMessage(null); @@ -277,6 +295,36 @@ public class AppsControllerExternalRequestTest extends MockitoTestSuite { } @Test + public void postOnboardAppExternalXSSTest() { + PortalRestResponse<String> expectedportalRestResponse = new PortalRestResponse<String>(); + expectedportalRestResponse.setMessage( + "Data is not valid"); + expectedportalRestResponse.setResponse(null); + PortalRestStatusEnum portalRestStatusEnum = null; + expectedportalRestResponse.setStatus(portalRestStatusEnum.ERROR); + + OnboardingApp expectedOnboardingApp = new OnboardingApp();; + expectedOnboardingApp.name = "test"; + expectedOnboardingApp.url="test.com"; + expectedOnboardingApp.restUrl="<script>alert(/XSS”)</script>"; + expectedOnboardingApp.myLoginsAppOwner="testUser"; + expectedOnboardingApp.restrictedApp=false; + expectedOnboardingApp.isOpen=true; + expectedOnboardingApp.isEnabled=true; + EPUser user = mockUser.mockEPUser(); + user.setEmail("guestT@test.portal.onap.org"); + user.setLoginPwd("pwd"); + user.setLoginId("Test"); + List<EPUser> expectedList = new ArrayList<EPUser>(); + expectedList.add(user); + + PortalRestResponse<String> actualPortalRestResponse = appsControllerExternalRequest + .postOnboardAppExternal(mockedRequest, mockedResponse, expectedOnboardingApp); + assertEquals(expectedportalRestResponse, actualPortalRestResponse); + + } + + @Test public void putOnboardAppExternalifAppNullTest() { PortalRestResponse<String> expectedportalRestResponse = new PortalRestResponse<String>(); expectedportalRestResponse.setMessage("Unexpected value for field: id"); @@ -293,6 +341,38 @@ public class AppsControllerExternalRequestTest extends MockitoTestSuite { } @Test + public void putOnboardAppExternalXSSTest() { + PortalRestResponse<String> expectedportalRestResponse = new PortalRestResponse<String>(); + expectedportalRestResponse.setMessage( + "Data is not valid"); + expectedportalRestResponse.setResponse(null); + PortalRestStatusEnum portalRestStatusEnum = null; + expectedportalRestResponse.setStatus(portalRestStatusEnum.ERROR); + + OnboardingApp expectedOnboardingApp = new OnboardingApp();; + expectedOnboardingApp.name = "test"; + expectedOnboardingApp.url="test.com"; + expectedOnboardingApp.restUrl="<script>alert(/XSS”)</script>"; + expectedOnboardingApp.myLoginsAppOwner="testUser"; + expectedOnboardingApp.restrictedApp=false; + expectedOnboardingApp.isOpen=true; + expectedOnboardingApp.isEnabled=true; + EPUser user = mockUser.mockEPUser(); + user.setEmail("guestT@test.portal.onap.org"); + user.setLoginPwd("pwd"); + user.setLoginId("Test"); + List<EPUser> expectedList = new ArrayList<EPUser>(); + expectedList.add(user); + + Long appId = (long) 1; + + PortalRestResponse<String> actualPortalRestResponse = appsControllerExternalRequest + .putOnboardAppExternal(mockedRequest, mockedResponse, appId, expectedOnboardingApp); + assertEquals(expectedportalRestResponse, actualPortalRestResponse); + + } + + @Test public void putOnboardAppExternalIfOnboardingAppDetailsNullTest() { PortalRestResponse<String> expectedportalRestResponse = new PortalRestResponse<String>(); expectedportalRestResponse.setMessage( diff --git a/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/controller/AppsControllerTest.java b/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/controller/AppsControllerTest.java index ff37fd50..4df1c2ac 100644 --- a/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/controller/AppsControllerTest.java +++ b/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/controller/AppsControllerTest.java @@ -1,9 +1,11 @@ /*- - * ============LICENSE_START========================================== + * ============LICENSE_START========================================== * ONAP Portal * =================================================================== * 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"); @@ -88,7 +90,10 @@ import org.powermock.api.mockito.PowerMockito; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import org.springframework.http.HttpEntity; +import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; +import org.springframework.web.client.HttpClientErrorException; @RunWith(PowerMockRunner.class) @PrepareForTest({SystemProperties.class,AppUtils.class, EPUserUtils.class, MediaType.class}) @@ -546,7 +551,7 @@ public class AppsControllerTest extends MockitoTestSuite{ List<AppsResponse> atualApps = new ArrayList<AppsResponse>(); Mockito.when(adminRolesService.isSuperAdmin(user)).thenReturn(true); - Mockito.when(appService.getAllApps(false)).thenReturn(expectedApps); + Mockito.when(appService.getAllApplications(false)).thenReturn(expectedApps); atualApps = appsController.getApps(mockedRequest, mockedResponse); assertEquals(expectedApps, atualApps); } @@ -564,7 +569,7 @@ public class AppsControllerTest extends MockitoTestSuite{ EPUser user = mockUser.mockEPUser(); Mockito.when(EPUserUtils.getUserSession(mockedRequest)).thenReturn(user); Mockito.when(adminRolesService.isSuperAdmin(user)).thenReturn(true); - Mockito.when(appService.getAllApps(false)).thenThrow(nullPointerException); + Mockito.when(appService.getAllApplications(false)).thenThrow(nullPointerException); assertNull(appsController.getApps(mockedRequest, mockedResponse)); } @@ -723,23 +728,110 @@ public class AppsControllerTest extends MockitoTestSuite{ } @Test - public void putOnboardingAppTest() { + public void putOnboardingAppTest() throws Exception { EPUser user = mockUser.mockEPUser(); Mockito.when(EPUserUtils.getUserSession(mockedRequest)).thenReturn(user); OnboardingApp OnboardingApp = new OnboardingApp(); + OnboardingApp.isCentralAuth = true; + OnboardingApp.nameSpace = "test1"; FieldsValidator expectedFieldValidator = new FieldsValidator(); expectedFieldValidator.setHttpStatusCode((long) 200); expectedFieldValidator.setFields(null); expectedFieldValidator.setErrorCode(null); + EPApp OnboardingApp1 = new EPApp(); + OnboardingApp1.setCentralAuth(false); + OnboardingApp1.setNameSpace("test"); + Mockito.when(appService.getApp(Matchers.anyLong())).thenReturn(OnboardingApp1); Mockito.when(adminRolesService.isSuperAdmin(user)).thenReturn(true); + ResponseEntity<String> response = new ResponseEntity<>(HttpStatus.OK); + Mockito.when(appService.checkIfNameSpaceIsValid(Matchers.anyString())).thenReturn(response); Mockito.when(appService.modifyOnboardingApp(OnboardingApp, user)).thenReturn(expectedFieldValidator); + Mockito.when(mockedResponse.getStatus()).thenReturn(200); FieldsValidator actualFieldValidator = appsController.putOnboardingApp(mockedRequest, OnboardingApp, mockedResponse); assertEquals(expectedFieldValidator, actualFieldValidator); } + + @Test + public void putOnboardingApp2Test() throws Exception { + EPUser user = mockUser.mockEPUser(); + Mockito.when(EPUserUtils.getUserSession(mockedRequest)).thenReturn(user); + OnboardingApp onboardingApp = new OnboardingApp(); + onboardingApp.isCentralAuth = true; + onboardingApp.nameSpace = "com.test1"; + EPApp app = new EPApp(); + app.setNameSpace("com.test "); + FieldsValidator expectedFieldValidator = new FieldsValidator(); + expectedFieldValidator.setHttpStatusCode((long) 200); + expectedFieldValidator.setFields(null); + expectedFieldValidator.setErrorCode(null); + Mockito.when(adminRolesService.isSuperAdmin(user)).thenReturn(false); + Mockito.when(adminRolesService.isAccountAdminOfApplication(Matchers.any(EPUser.class),Matchers.any(EPApp.class))).thenReturn(true); + ResponseEntity<String> response = new ResponseEntity<>(HttpStatus.OK); + Mockito.when(appService.checkIfNameSpaceIsValid("com.test1")).thenReturn(response); + Mockito.when(appService.getApp(Matchers.anyLong())).thenReturn(app); + Mockito.when(mockedResponse.getStatus()).thenReturn(200); + Mockito.when(appService.modifyOnboardingApp(Matchers.any(OnboardingApp.class), Matchers.any(EPUser.class))).thenReturn(expectedFieldValidator); + FieldsValidator actualFieldValidator = appsController.putOnboardingApp(mockedRequest, onboardingApp, + mockedResponse); + } + + + @Test - public void putOnboardingAppIfSuperAdminTest() { + public void putOnboardingApp4Test() throws Exception { + EPUser user = mockUser.mockEPUser(); + Mockito.when(EPUserUtils.getUserSession(mockedRequest)).thenReturn(user); + OnboardingApp onboardingApp = new OnboardingApp(); + onboardingApp.isCentralAuth = false; + onboardingApp.nameSpace = "com.test1"; + EPApp app = new EPApp(); + app.setCentralAuth(false); + app.setNameSpace("com.test "); + FieldsValidator expectedFieldValidator = new FieldsValidator(); + expectedFieldValidator.setHttpStatusCode((long) 404); + Mockito.when(adminRolesService.isSuperAdmin(user)).thenReturn(false); + Mockito.when(adminRolesService.isAccountAdminOfAnyActiveorInactiveApplication(Matchers.any(EPUser.class),Matchers.any(EPApp.class))).thenReturn(true); + ResponseEntity<String> response = new ResponseEntity<>(HttpStatus.OK); + + HttpClientErrorException exception = new HttpClientErrorException(HttpStatus.FORBIDDEN); + Mockito.when(appService.checkIfNameSpaceIsValid("com.test1")).thenThrow(exception); + Mockito.when(appService.getApp(Matchers.anyLong())).thenReturn(app); + Mockito.when(mockedResponse.getStatus()).thenReturn(200); + Mockito.when(appService.modifyOnboardingApp(Matchers.any(OnboardingApp.class), Matchers.any(EPUser.class))).thenReturn(expectedFieldValidator); + FieldsValidator actualFieldValidator = appsController.putOnboardingApp(mockedRequest, onboardingApp, + mockedResponse); + assertEquals(expectedFieldValidator.getHttpStatusCode(), actualFieldValidator.getHttpStatusCode()); + } + + @Test + public void putOnboardingApp5Test() throws Exception { + EPUser user = mockUser.mockEPUser(); + Mockito.when(EPUserUtils.getUserSession(mockedRequest)).thenReturn(user); + OnboardingApp onboardingApp = new OnboardingApp(); + onboardingApp.isCentralAuth = true; + onboardingApp.nameSpace = "com.test1"; + EPApp app = new EPApp(); + app.setNameSpace("com.test "); + FieldsValidator expectedFieldValidator = new FieldsValidator(); + expectedFieldValidator.setHttpStatusCode((long) 400); + Mockito.when(adminRolesService.isSuperAdmin(user)).thenReturn(false); + Mockito.when(adminRolesService.isAccountAdminOfApplication(Matchers.any(EPUser.class),Matchers.any(EPApp.class))).thenReturn(true); + ResponseEntity<String> response = new ResponseEntity<>(HttpStatus.OK); + + HttpClientErrorException exception = new HttpClientErrorException(HttpStatus.BAD_REQUEST); + Mockito.when(appService.checkIfNameSpaceIsValid("com.test1")).thenThrow(exception); + Mockito.when(appService.getApp(Matchers.anyLong())).thenReturn(app); + Mockito.when(mockedResponse.getStatus()).thenReturn(400); + Mockito.when(appService.modifyOnboardingApp(Matchers.any(OnboardingApp.class), Matchers.any(EPUser.class))).thenReturn(expectedFieldValidator); + FieldsValidator actualFieldValidator = appsController.putOnboardingApp(mockedRequest, onboardingApp, + mockedResponse); + } + + + @Test + public void putOnboardingAppIfSuperAdminTest() throws Exception { EPUser user = mockUser.mockEPUser(); Mockito.when(EPUserUtils.getUserSession(mockedRequest)).thenReturn(user); FieldsValidator expectedFieldValidator = null; @@ -750,7 +842,7 @@ public class AppsControllerTest extends MockitoTestSuite{ } @Test - public void putOnboardingAppExceptionTest() { + public void putOnboardingAppExceptionTest() throws Exception { EPUser user = mockUser.mockEPUser(); Mockito.when(EPUserUtils.getUserSession(mockedRequest)).thenReturn(user); OnboardingApp OnboardingApp = new OnboardingApp(); @@ -758,6 +850,13 @@ public class AppsControllerTest extends MockitoTestSuite{ Mockito.when(appService.modifyOnboardingApp(OnboardingApp, user)).thenThrow(nullPointerException); assertNull(appsController.putOnboardingApp(mockedRequest, OnboardingApp, mockedResponse)); } + + @Test + public void putOnboardingAppNullUserTest() throws Exception { + Mockito.when(EPUserUtils.getUserSession(mockedRequest)).thenThrow(nullPointerException); + Mockito.when(mockedResponse.getStatus()).thenReturn(200); + assertNull(appsController.putOnboardingApp(mockedRequest, new OnboardingApp(), mockedResponse)); + } @Test public void postOnboardingAppTest() { diff --git a/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/controller/AuxApiRequestMapperControllerTest.java b/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/controller/AuxApiRequestMapperControllerTest.java index 9d3ac1e2..e7303313 100644 --- a/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/controller/AuxApiRequestMapperControllerTest.java +++ b/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/controller/AuxApiRequestMapperControllerTest.java @@ -639,7 +639,7 @@ public class AuxApiRequestMapperControllerTest { Mockito.when(AopUtils.isAopProxy(Matchers.anyObject())).thenReturn(false); Mockito.when(mockedRequest.getMethod()).thenReturn("POST"); EpNotificationItem notificationItem = new EpNotificationItem(); - assertNull(auxApiRequestMapperController.publishNotification(mockedRequest, notificationItem, mockedResponse)); + assertNotNull(auxApiRequestMapperController.publishNotification(mockedRequest, notificationItem, mockedResponse)); } @Test diff --git a/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/controller/DashboardSearchResultControllerTest.java b/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/controller/DashboardSearchResultControllerTest.java index 839b9fd5..34667853 100644 --- a/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/controller/DashboardSearchResultControllerTest.java +++ b/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/controller/DashboardSearchResultControllerTest.java @@ -93,7 +93,7 @@ public class DashboardSearchResultControllerTest { @Test public void getWidgetDataTest() { String resourceType = "test"; - PortalRestResponse<CommonWidgetMeta> ecpectedPortalRestResponse = new PortalRestResponse<CommonWidgetMeta>(); + PortalRestResponse<CommonWidgetMeta> ecpectedPortalRestResponse = new PortalRestResponse<>(); ecpectedPortalRestResponse.setMessage("success"); ecpectedPortalRestResponse.setResponse(null); ecpectedPortalRestResponse.setStatus(PortalRestStatusEnum.OK); @@ -105,8 +105,21 @@ public class DashboardSearchResultControllerTest { } @Test + public void getWidgetDataXSSTest() { + String resourceType = "\"<IMG SRC=\\\"jav\\tascript:alert('XSS');\\\">\""; + PortalRestResponse expectedPortalRestResponse = new PortalRestResponse<>(); + expectedPortalRestResponse.setMessage("resourceType: String string is not valid"); + expectedPortalRestResponse.setResponse(""); + expectedPortalRestResponse.setStatus(PortalRestStatusEnum.ERROR); + Mockito.when(searchService.getWidgetData(resourceType)).thenReturn(null); + PortalRestResponse acutualPoratlRestResponse = dashboardSearchResultController + .getWidgetData(mockedRequest, resourceType); + assertEquals(expectedPortalRestResponse,acutualPoratlRestResponse); + } + + @Test public void saveWidgetDataBulkTest() { - PortalRestResponse<String> ecpectedPortalRestResponse = new PortalRestResponse<String>(); + PortalRestResponse<String> ecpectedPortalRestResponse = new PortalRestResponse<>(); ecpectedPortalRestResponse.setMessage("success"); ecpectedPortalRestResponse.setResponse(null); ecpectedPortalRestResponse.setStatus(PortalRestStatusEnum.OK); @@ -114,7 +127,7 @@ public class DashboardSearchResultControllerTest { CommonWidgetMeta commonWidgetMeta = new CommonWidgetMeta(); commonWidgetMeta.setCategory("test"); - List<CommonWidget> commonWidgetList = new ArrayList<CommonWidget>(); + List<CommonWidget> commonWidgetList = new ArrayList<>(); CommonWidget commonWidget = new CommonWidget(); commonWidget.setId((long) 1); commonWidget.setCategory("test"); @@ -136,8 +149,39 @@ 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 saveWidgetDataBulkIfCategoryNullTest() { - PortalRestResponse<String> ecpectedPortalRestResponse = new PortalRestResponse<String>(); + PortalRestResponse<String> ecpectedPortalRestResponse = new PortalRestResponse<>(); ecpectedPortalRestResponse.setMessage("java.text.ParseException: Unparseable date: \"1\""); ecpectedPortalRestResponse.setResponse(null); ecpectedPortalRestResponse.setStatus(PortalRestStatusEnum.ERROR); @@ -145,7 +189,7 @@ public class DashboardSearchResultControllerTest { CommonWidgetMeta commonWidgetMeta = new CommonWidgetMeta(); commonWidgetMeta.setCategory("test"); - List<CommonWidget> commonWidgetList = new ArrayList<CommonWidget>(); + List<CommonWidget> commonWidgetList = new ArrayList<>(); CommonWidget commonWidget = new CommonWidget(); commonWidget.setId(null); commonWidget.setCategory(null); @@ -166,7 +210,7 @@ public class DashboardSearchResultControllerTest { @Test public void saveWidgetDataTest() { - PortalRestResponse<String> ecpectedPortalRestResponse = new PortalRestResponse<String>(); + PortalRestResponse<String> ecpectedPortalRestResponse = new PortalRestResponse<>(); ecpectedPortalRestResponse.setMessage("success"); ecpectedPortalRestResponse.setResponse(null); ecpectedPortalRestResponse.setStatus(PortalRestStatusEnum.OK); @@ -188,10 +232,33 @@ public class DashboardSearchResultControllerTest { } @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 saveWidgetDataExceptionTest() { - PortalRestResponse<String> ecpectedPortalRestResponse = new PortalRestResponse<String>(); + PortalRestResponse<String> ecpectedPortalRestResponse = new PortalRestResponse<>(); ecpectedPortalRestResponse.setMessage("ERROR"); - ecpectedPortalRestResponse.setResponse("Cateogry cannot be null or empty"); + ecpectedPortalRestResponse.setResponse("Category cannot be null or empty"); ecpectedPortalRestResponse.setStatus(PortalRestStatusEnum.ERROR); CommonWidget commonWidget = new CommonWidget(); commonWidget.setId((long) 1); @@ -212,7 +279,7 @@ public class DashboardSearchResultControllerTest { @Test public void saveWidgetDataDateErrorTest() { - PortalRestResponse<String> ecpectedPortalRestResponse = new PortalRestResponse<String>(); + PortalRestResponse<String> ecpectedPortalRestResponse = new PortalRestResponse<>(); ecpectedPortalRestResponse.setMessage("java.text.ParseException: Unparseable date: \"1\""); ecpectedPortalRestResponse.setResponse(null); ecpectedPortalRestResponse.setStatus(PortalRestStatusEnum.ERROR); @@ -233,8 +300,9 @@ public class DashboardSearchResultControllerTest { } + @Test public void deleteWidgetDataTest() { - PortalRestResponse<String> ecpectedPortalRestResponse = new PortalRestResponse<String>(); + PortalRestResponse<String> ecpectedPortalRestResponse = new PortalRestResponse<>(); ecpectedPortalRestResponse.setMessage("success"); ecpectedPortalRestResponse.setResponse(null); ecpectedPortalRestResponse.setStatus(PortalRestStatusEnum.OK); @@ -255,14 +323,36 @@ public class DashboardSearchResultControllerTest { } @Test + public void deleteWidgetDataXSSTest() { + PortalRestResponse<String> expectedPortalRestResponse = new PortalRestResponse<>(); + expectedPortalRestResponse.setMessage("ERROR"); + expectedPortalRestResponse.setResponse("CommonWidget 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 searchPortalIfUserIsNull() { EPUser user = null; Mockito.when(EPUserUtils.getUserSession(mockedRequest)).thenReturn(user); String searchString = "test"; - PortalRestResponse<Map<String, List<SearchResultItem>>> expectedResult = new PortalRestResponse<Map<String, List<SearchResultItem>>>(); + PortalRestResponse<Map<String, List<SearchResultItem>>> expectedResult = new PortalRestResponse<>(); expectedResult.setMessage("searchPortal: User object is null? - check logs"); - expectedResult.setResponse(new HashMap<String, List<SearchResultItem>>()); + expectedResult.setResponse(new HashMap<>()); expectedResult.setStatus(PortalRestStatusEnum.ERROR); PortalRestResponse<Map<String, List<SearchResultItem>>> actualResult = dashboardSearchResultController .searchPortal(mockedRequest, searchString); @@ -272,13 +362,12 @@ public class DashboardSearchResultControllerTest { @Test public void searchPortalIfSearchStringNullTest() { EPUser user = mockUser.mockEPUser(); - ; Mockito.when(EPUserUtils.getUserSession(mockedRequest)).thenReturn(user); String searchString = null; - PortalRestResponse<Map<String, List<SearchResultItem>>> expectedResult = new PortalRestResponse<Map<String, List<SearchResultItem>>>(); + PortalRestResponse<Map<String, List<SearchResultItem>>> expectedResult = new PortalRestResponse<>(); expectedResult.setMessage("searchPortal: String string is null"); - expectedResult.setResponse(new HashMap<String, List<SearchResultItem>>()); + expectedResult.setResponse(new HashMap<>()); expectedResult.setStatus(PortalRestStatusEnum.ERROR); PortalRestResponse<Map<String, List<SearchResultItem>>> actualResult = dashboardSearchResultController @@ -289,10 +378,9 @@ public class DashboardSearchResultControllerTest { @Test public void searchPortalIfSearchTest() { EPUser user = mockUser.mockEPUser(); - ; Mockito.when(EPUserUtils.getUserSession(mockedRequest)).thenReturn(user); String searchString = "test"; - List<SearchResultItem> searchResultItemList = new ArrayList<SearchResultItem>(); + List<SearchResultItem> searchResultItemList = new ArrayList<>(); SearchResultItem searchResultItem = new SearchResultItem(); searchResultItem.setId((long) 1); @@ -301,10 +389,10 @@ public class DashboardSearchResultControllerTest { searchResultItem.setTarget("test_target"); searchResultItem.setUuid("test_UUId"); searchResultItemList.add(searchResultItem); - Map<String, List<SearchResultItem>> expectedResultMap = new HashMap<String, List<SearchResultItem>>(); + Map<String, List<SearchResultItem>> expectedResultMap = new HashMap<>(); expectedResultMap.put(searchString, searchResultItemList); - PortalRestResponse<Map<String, List<SearchResultItem>>> expectedResult = new PortalRestResponse<Map<String, List<SearchResultItem>>>(); + PortalRestResponse<Map<String, List<SearchResultItem>>> expectedResult = new PortalRestResponse<>(); expectedResult.setMessage("success"); expectedResult.setResponse(expectedResultMap); expectedResult.setStatus(PortalRestStatusEnum.OK); @@ -319,13 +407,12 @@ public class DashboardSearchResultControllerTest { @Test public void searchPortalIfSearchExcptionTest() { EPUser user = mockUser.mockEPUser(); - ; Mockito.when(EPUserUtils.getUserSession(mockedRequest)).thenReturn(user); String searchString = "test"; - PortalRestResponse<Map<String, List<SearchResultItem>>> expectedResult = new PortalRestResponse<Map<String, List<SearchResultItem>>>(); + PortalRestResponse<Map<String, List<SearchResultItem>>> expectedResult = new PortalRestResponse<>(); expectedResult.setMessage("null - check logs."); - expectedResult.setResponse(new HashMap<String, List<SearchResultItem>>()); + expectedResult.setResponse(new HashMap<>()); expectedResult.setStatus(PortalRestStatusEnum.ERROR); Mockito.when(searchService.searchResults(user.getLoginId(), searchString)).thenThrow(nullPointerException); @@ -336,9 +423,8 @@ public class DashboardSearchResultControllerTest { @Test public void getActiveUsersTest() { - List<String> expectedActiveUsers = new ArrayList<String>(); + List<String> expectedActiveUsers = new ArrayList<>(); EPUser user = mockUser.mockEPUser(); - ; Mockito.when(EPUserUtils.getUserSession(mockedRequest)).thenReturn(user); String userId = user.getOrgUserId(); Mockito.when(searchService.getRelatedUsers(userId)).thenReturn(expectedActiveUsers); @@ -349,7 +435,7 @@ public class DashboardSearchResultControllerTest { @Test public void getActiveUsersExceptionTest() { - List<String> expectedActiveUsers = new ArrayList<String>(); + List<String> expectedActiveUsers = new ArrayList<>(); EPUser user = mockUser.mockEPUser(); Mockito.when(EPUserUtils.getUserSession(mockedRequest)).thenReturn(user); String userId = user.getOrgUserId(); @@ -363,7 +449,7 @@ public class DashboardSearchResultControllerTest { public void activeUsersTest() { EPUser user = mockUser.mockEPUser(); Mockito.when(EPUserUtils.getUserSession(mockedRequest)).thenReturn(user); - PortalRestResponse<List<String>> expectedResult = new PortalRestResponse<List<String>>(); + PortalRestResponse<List<String>> expectedResult = new PortalRestResponse<>(); expectedResult.setMessage("success"); expectedResult.setResponse(new ArrayList<>()); expectedResult.setStatus(PortalRestStatusEnum.OK); @@ -377,7 +463,7 @@ public class DashboardSearchResultControllerTest { public void activeUsersIfUserNullTest() { EPUser user = null; Mockito.when(EPUserUtils.getUserSession(mockedRequest)).thenReturn(user); - PortalRestResponse<List<String>> expectedResult = new PortalRestResponse<List<String>>(); + PortalRestResponse<List<String>> expectedResult = new PortalRestResponse<>(); expectedResult.setMessage("User object is null? - check logs"); expectedResult.setResponse(new ArrayList<>()); expectedResult.setStatus(PortalRestStatusEnum.ERROR); @@ -390,7 +476,7 @@ public class DashboardSearchResultControllerTest { public void activeUsersExceptionTest() { EPUser user = mockUser.mockEPUser(); Mockito.when(EPUserUtils.getUserSession(mockedRequest)).thenReturn(user); - PortalRestResponse<List<String>> expectedResult = new PortalRestResponse<List<String>>(); + PortalRestResponse<List<String>> expectedResult = new PortalRestResponse<>(); expectedResult.setMessage("null - check logs."); expectedResult.setResponse(new ArrayList<>()); expectedResult.setStatus(PortalRestStatusEnum.ERROR); diff --git a/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/controller/ExternalAppsRestfulControllerTest.java b/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/controller/ExternalAppsRestfulControllerTest.java index 73978a33..d8f98bb9 100644 --- a/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/controller/ExternalAppsRestfulControllerTest.java +++ b/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/controller/ExternalAppsRestfulControllerTest.java @@ -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"); @@ -38,8 +40,9 @@ package org.onap.portalapp.portal.controller; import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; +import static org.mockito.Matchers.any; import java.util.ArrayList; import java.util.Calendar; @@ -54,18 +57,15 @@ import javax.servlet.http.HttpServletResponse; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; +import org.mockito.ArgumentCaptor; import org.mockito.InjectMocks; -import org.mockito.Matchers; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.MockitoAnnotations; -import org.onap.portalapp.portal.controller.ExternalAppsRestfulController; import org.onap.portalapp.portal.core.MockEPUser; import org.onap.portalapp.portal.domain.EPApp; +import org.onap.portalapp.portal.domain.EPRole; import org.onap.portalapp.portal.domain.EPUser; -import org.onap.portalapp.portal.domain.UserRole; -import org.onap.portalapp.portal.ecomp.model.PortalRestResponse; -import org.onap.portalapp.portal.ecomp.model.PortalRestStatusEnum; import org.onap.portalapp.portal.framework.MockitoTestSuite; import org.onap.portalapp.portal.service.AdminRolesService; import org.onap.portalapp.portal.service.AdminRolesServiceImpl; @@ -82,7 +82,6 @@ import org.onap.portalapp.portal.transport.FavoritesFunctionalMenuItemJson; import org.onap.portalapp.portal.transport.FunctionalMenuItem; import org.onap.portalapp.portal.utils.EPCommonSystemProperties; import org.onap.portalapp.portal.utils.EcompPortalUtils; -import org.onap.portalsdk.core.menu.MenuBuilder; import org.onap.portalsdk.core.onboarding.crossapi.PortalAPIResponse; import org.onap.portalsdk.core.service.DataAccessService; import org.onap.portalsdk.core.service.DataAccessServiceImpl; @@ -247,88 +246,124 @@ public class ExternalAppsRestfulControllerTest { .getFavoritesForUser(mockedRequest, mockedResponse); assertEquals(actaulFavorites.size(), 1); } - - @Test(expected=NullPointerException.class) - public void publishNotificationTest() throws Exception{ - EPApp appTest=new EPApp(); - Mockito.when(mockedRequest.getHeader("uebkey")).thenReturn("RxH3983AHiyBOQmj"); - appTest.setUebKey("123456"); - String appKey="123456"; - EpNotificationItem notificationItem=new EpNotificationItem(); - List<Long> roleList = new ArrayList<Long>(); - Long role1 = (long) 1; - roleList.add(role1); - notificationItem.setRoleIds(roleList); - notificationItem.setIsForAllRoles("N"); - notificationItem.setIsForOnlineUsers("N"); - notificationItem.setActiveYn("Y"); - notificationItem.setPriority(1L); - notificationItem.setMsgHeader("testHeader"); - notificationItem.setMsgDescription("Test Description"); - Date currentDate = new Date(); - Calendar c = Calendar.getInstance(); - c.setTime(currentDate); - c.add(Calendar.DATE, 1); - Date currentDatePlusOne = c.getTime(); - notificationItem.setStartTime(currentDate); - notificationItem.setEndTime(currentDatePlusOne); - notificationItem.setCreatedDate(c.getTime()); - - PortalAPIResponse actualPortalRestResponse = new PortalAPIResponse(true, appKey); - PortalAPIResponse expectedPortalRestResponse = new PortalAPIResponse(true, appKey); - expectedPortalRestResponse.setMessage("SUCCESS"); - expectedPortalRestResponse.setStatus("ok"); - Map<String, String> params = new HashMap<>(); - params.put("appKey", "1234567"); - - Mockito.when(DataAccessService.executeNamedQuery("getMyAppDetailsByUebKey", params, null)).thenReturn(null); - Mockito.when(userNotificationService.saveNotification(notificationItem)).thenReturn("Test"); - actualPortalRestResponse = externalAppsRestfulController.publishNotification(mockedRequest, notificationItem); - assertTrue(actualPortalRestResponse.equals(expectedPortalRestResponse)); - - } - - @Test(expected=NullPointerException.class) - public void publishNotificationTest1() throws Exception{ - EpNotificationItem notificationItem=new EpNotificationItem(); - List<Long> roleList = new ArrayList<Long>(); - Long role1 = (long) 1; - roleList.add(role1); - notificationItem.setRoleIds(roleList); - notificationItem.setIsForAllRoles("N"); - notificationItem.setIsForOnlineUsers("N"); - notificationItem.setActiveYn("Y"); - notificationItem.setPriority(1L); - notificationItem.setMsgHeader("testHeader"); - notificationItem.setMsgDescription("Test Description"); - Date currentDate = new Date(); - Calendar c = Calendar.getInstance(); - c.setTime(currentDate); - c.add(Calendar.DATE, 1); - Date currentDatePlusOne = c.getTime(); - notificationItem.setStartTime(currentDate); - notificationItem.setEndTime(currentDatePlusOne); - notificationItem.setCreatedDate(c.getTime()); - - //PowerMockito.mockStatic(EPApp.class); - - List<EPApp> appList = new ArrayList<>(); - EPApp app = mockApp(); - app.setId((long) 1); - appList.add(app); - - final Map<String, String> appUebkeyParams = new HashMap<>(); - appUebkeyParams.put("appKey", "test-ueb-key"); - - Mockito.when(DataAccessService.executeNamedQuery("getMyAppDetailsByUebKey", appUebkeyParams, null)) - .thenReturn(appList); - //EPApp epApp=new EPApp(); - - Mockito.when(mockedRequest.getHeader("uebkey")).thenReturn("RxH3983AHiyBOQmj"); + @Test + public void publishNotificationTest_Success() throws Exception { + // input + EpNotificationItem notificationItem = new EpNotificationItem(); + List<Long> roleList = new ArrayList<Long>(); + Long role1 = 1L; + roleList.add(role1); + notificationItem.setRoleIds(roleList); + notificationItem.setPriority(1L); + notificationItem.setMsgHeader("testHeader"); + notificationItem.setMsgDescription("Test Description"); + Date currentDate = new Date(); + Calendar c = Calendar.getInstance(); + c.setTime(currentDate); + c.add(Calendar.DATE, 1); + Date currentDatePlusOne = c.getTime(); + notificationItem.setStartTime(currentDate); + notificationItem.setEndTime(currentDatePlusOne); - externalAppsRestfulController.publishNotification(mockedRequest, notificationItem); + // mock calls + Mockito.when(mockedRequest.getHeader("uebkey")).thenReturn("RxH3983AHiyBOQmj"); + Map<String, String> params = new HashMap<>(); + params.put("appKey", "RxH3983AHiyBOQmj"); + List<EPApp> apps = new ArrayList<>(); + EPApp app = new EPApp(); + app.setId(123L); + apps.add(app); + Mockito.when(DataAccessService.executeNamedQuery("getMyAppDetailsByUebKey", params, null)).thenReturn(apps); + EPRole role = new EPRole(); + role.setId(543L); + Mockito.when(epRoleService.getRole(123L, 1L)).thenReturn(role); + + // run + Mockito.when(userNotificationService.saveNotification(notificationItem)).thenReturn("Test"); + PortalAPIResponse response = externalAppsRestfulController.publishNotification(mockedRequest, notificationItem); + // verify answer + assertNotNull(response); + assertEquals("ok", response.getStatus()); + assertEquals("success", response.getMessage()); + ArgumentCaptor<EpNotificationItem> capture = ArgumentCaptor.forClass(EpNotificationItem.class); + Mockito.verify(userNotificationService).saveNotification(capture.capture()); + assertNotNull(capture.getValue()); + EpNotificationItem createdNofification = capture.getValue(); + assertNotNull(createdNofification.getRoleIds()); + assertEquals(1, createdNofification.getRoleIds().size()); + assertEquals(543L, createdNofification.getRoleIds().get(0).longValue()); + } + + @Test + public void publishNotificationTest_EmptyAppHeader() throws Exception { + // input + EpNotificationItem notificationItem = new EpNotificationItem(); + List<Long> roleList = new ArrayList<Long>(); + Long role1 = 1L; + roleList.add(role1); + notificationItem.setRoleIds(roleList); + notificationItem.setPriority(1L); + notificationItem.setMsgHeader("testHeader"); + notificationItem.setMsgDescription("Test Description"); + Date currentDate = new Date(); + Calendar c = Calendar.getInstance(); + c.setTime(currentDate); + c.add(Calendar.DATE, 1); + Date currentDatePlusOne = c.getTime(); + notificationItem.setStartTime(currentDate); + notificationItem.setEndTime(currentDatePlusOne); + + Mockito.when(mockedRequest.getHeader("uebkey")).thenReturn(null); + final Map<String, String> params = new HashMap<>(); + params.put("appKey", null); + Mockito.when(DataAccessService.executeNamedQuery("getMyAppDetailsByUebKey", params, null)) + .thenThrow(NullPointerException.class); + + PortalAPIResponse response = externalAppsRestfulController.publishNotification(mockedRequest, notificationItem); + assertNotNull(response); + assertEquals("ok", response.getStatus()); + assertEquals("success", response.getMessage()); + ArgumentCaptor<EpNotificationItem> capture = ArgumentCaptor.forClass(EpNotificationItem.class); + Mockito.verify(userNotificationService).saveNotification(capture.capture()); + assertNotNull(capture.getValue()); + EpNotificationItem createdNofification = capture.getValue(); + assertNotNull(createdNofification.getRoleIds()); + assertEquals(0, createdNofification.getRoleIds().size()); + } + + @Test + public void publishNotificationTest_ErrorResponse() throws Exception { + // input + EpNotificationItem notificationItem = new EpNotificationItem(); + List<Long> roleList = new ArrayList<Long>(); + Long role1 = 1L; + roleList.add(role1); + notificationItem.setRoleIds(roleList); + notificationItem.setPriority(1L); + notificationItem.setMsgHeader("testHeader"); + notificationItem.setMsgDescription("Test Description"); + Date currentDate = new Date(); + Calendar c = Calendar.getInstance(); + c.setTime(currentDate); + c.add(Calendar.DATE, 1); + Date currentDatePlusOne = c.getTime(); + notificationItem.setStartTime(currentDate); + notificationItem.setEndTime(currentDatePlusOne); + + Mockito.when(mockedRequest.getHeader("uebkey")).thenReturn(null); + final Map<String, String> params = new HashMap<>(); + params.put("appKey", null); + Mockito.when(DataAccessService.executeNamedQuery("getMyAppDetailsByUebKey", params, null)) + .thenThrow(NullPointerException.class); + Mockito.when(userNotificationService.saveNotification(any(EpNotificationItem.class))). + thenThrow(new NullPointerException("expected message")); + + PortalAPIResponse response = externalAppsRestfulController.publishNotification(mockedRequest, notificationItem); + assertNotNull(response); + assertEquals("error", response.getStatus()); + assertEquals("expected message", response.getMessage()); + } - } } diff --git a/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/controller/MicroserviceControllerTest.java b/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/controller/MicroserviceControllerTest.java index 21d0cf70..81e1f8b2 100644 --- a/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/controller/MicroserviceControllerTest.java +++ b/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/controller/MicroserviceControllerTest.java @@ -96,7 +96,7 @@ public class MicroserviceControllerTest extends MockitoTestSuite{ @SuppressWarnings("rawtypes") @Mock - ResponseEntity<List<WidgetCatalog>> ans = new ResponseEntity<List<WidgetCatalog>>(HttpStatus.OK); + ResponseEntity<List<WidgetCatalog>> ans = new ResponseEntity<>(HttpStatus.OK); @Before public void setup() { @@ -114,11 +114,10 @@ public class MicroserviceControllerTest extends MockitoTestSuite{ @Test public void createMicroserviceIfServiceDataNullTest() throws Exception { - PortalRestResponse<String> expectedportalRestResponse = new PortalRestResponse<String>(); + PortalRestResponse<String> expectedportalRestResponse = new PortalRestResponse<>(); expectedportalRestResponse.setMessage("FAILURE"); expectedportalRestResponse.setResponse("MicroserviceData cannot be null or empty"); - PortalRestStatusEnum portalRestStatusEnum = null; - expectedportalRestResponse.setStatus(portalRestStatusEnum.ERROR); + expectedportalRestResponse.setStatus(PortalRestStatusEnum.ERROR); MicroserviceData microserviceData = null; PortalRestResponse<String> actualportalRestResponse = microserviceController.createMicroservice(mockedRequest, mockedResponse, microserviceData); @@ -127,23 +126,35 @@ public class MicroserviceControllerTest extends MockitoTestSuite{ @Test public void createMicroserviceTest() throws Exception { - PortalRestResponse<String> expectedportalRestResponse = new PortalRestResponse<String>(); + PortalRestResponse<String> expectedportalRestResponse = new PortalRestResponse<>(); expectedportalRestResponse.setMessage("SUCCESS"); expectedportalRestResponse.setResponse(""); - PortalRestStatusEnum portalRestStatusEnum = null; - expectedportalRestResponse.setStatus(portalRestStatusEnum.OK); + expectedportalRestResponse.setStatus(PortalRestStatusEnum.OK); PortalRestResponse<String> actualportalRestResponse = microserviceController.createMicroservice(mockedRequest, mockedResponse, microserviceData); assertEquals(actualportalRestResponse, expectedportalRestResponse); } @Test + public void createMicroserviceXSSTest() throws Exception { + PortalRestResponse<String> expectedportalRestResponse = new PortalRestResponse<>(); + expectedportalRestResponse.setMessage("ERROR"); + expectedportalRestResponse.setResponse("MicroserviceData is not valid"); + expectedportalRestResponse.setStatus(PortalRestStatusEnum.ERROR); + MicroserviceData XSSMicroserviceData = new MicroserviceData(); + XSSMicroserviceData.setActive("<script>alert(123);</script>"); + XSSMicroserviceData.setName("<script>alert(/XSS”)</script>"); + PortalRestResponse<String> actualportalRestResponse = microserviceController.createMicroservice(mockedRequest, + mockedResponse, XSSMicroserviceData); + assertEquals(expectedportalRestResponse, actualportalRestResponse); + } + + @Test public void createMicroserviceExceptionTest() throws Exception { - PortalRestResponse<String> expectedportalRestResponse = new PortalRestResponse<String>(); + PortalRestResponse<String> expectedportalRestResponse = new PortalRestResponse<>(); expectedportalRestResponse.setMessage("FAILURE"); expectedportalRestResponse.setResponse(null); - PortalRestStatusEnum portalRestStatusEnum = null; - expectedportalRestResponse.setStatus(portalRestStatusEnum.ERROR); + expectedportalRestResponse.setStatus(PortalRestStatusEnum.ERROR); Mockito.when(microserviceService.saveMicroservice(microserviceData)).thenReturn((long) 1); Mockito.when(microserviceData.getParameterList()).thenThrow(nullPointerException); PortalRestResponse<String> actualportalRestResponse = microserviceController.createMicroservice(mockedRequest, @@ -159,12 +170,11 @@ public class MicroserviceControllerTest extends MockitoTestSuite{ } @Test - public void updateMicroserviceIfServiceISNullTest() throws Exception { - PortalRestResponse<String> expectedportalRestResponse = new PortalRestResponse<String>(); + public void updateMicroserviceIfServiceISNullTest() { + PortalRestResponse<String> expectedportalRestResponse = new PortalRestResponse<>(); expectedportalRestResponse.setMessage("FAILURE"); expectedportalRestResponse.setResponse("MicroserviceData cannot be null or empty"); - PortalRestStatusEnum portalRestStatusEnum = null; - expectedportalRestResponse.setStatus(portalRestStatusEnum.ERROR); + expectedportalRestResponse.setStatus(PortalRestStatusEnum.ERROR); MicroserviceData microserviceData = null; PortalRestResponse<String> actualportalRestResponse = microserviceController.updateMicroservice(mockedRequest, mockedResponse, 1, microserviceData); @@ -172,24 +182,36 @@ public class MicroserviceControllerTest extends MockitoTestSuite{ } @Test - public void updateMicroserviceTest() throws Exception { - PortalRestResponse<String> expectedportalRestResponse = new PortalRestResponse<String>(); + public void updateMicroserviceTest() { + PortalRestResponse<String> expectedportalRestResponse = new PortalRestResponse<>(); expectedportalRestResponse.setMessage("SUCCESS"); expectedportalRestResponse.setResponse(""); - PortalRestStatusEnum portalRestStatusEnum = null; - expectedportalRestResponse.setStatus(portalRestStatusEnum.OK); + expectedportalRestResponse.setStatus(PortalRestStatusEnum.OK); PortalRestResponse<String> actualportalRestResponse = microserviceController.updateMicroservice(mockedRequest, - mockedResponse, 1, microserviceData); + mockedResponse, 1, microserviceData); assertEquals(actualportalRestResponse, expectedportalRestResponse); } @Test - public void updateMicroserviceExceptionTest() throws Exception { - PortalRestResponse<String> expectedportalRestResponse = new PortalRestResponse<String>(); + public void updateMicroserviceXSSTest() { + PortalRestResponse<String> expectedportalRestResponse = new PortalRestResponse<>(); + expectedportalRestResponse.setMessage("ERROR"); + expectedportalRestResponse.setResponse("MicroserviceData is not valid"); + expectedportalRestResponse.setStatus(PortalRestStatusEnum.ERROR); + MicroserviceData XSSMicroserviceData = new MicroserviceData(); + XSSMicroserviceData.setActive("<script>alert(123);</script>"); + XSSMicroserviceData.setName("<script>alert(/XSS”)</script>"); + PortalRestResponse<String> actualportalRestResponse = microserviceController.updateMicroservice(mockedRequest, + mockedResponse, 1, XSSMicroserviceData); + assertEquals(expectedportalRestResponse, actualportalRestResponse); + } + + @Test + public void updateMicroserviceExceptionTest() { + PortalRestResponse<String> expectedportalRestResponse = new PortalRestResponse<>(); expectedportalRestResponse.setMessage("FAILURE"); expectedportalRestResponse.setResponse(null); - PortalRestStatusEnum portalRestStatusEnum = null; - expectedportalRestResponse.setStatus(portalRestStatusEnum.ERROR); + expectedportalRestResponse.setStatus(PortalRestStatusEnum.ERROR); Mockito.when(microserviceController.updateMicroservice(mockedRequest, mockedResponse, 1, microserviceData)) .thenThrow(nullPointerException); PortalRestResponse<String> actualportalRestResponse = microserviceController.updateMicroservice(mockedRequest, @@ -198,14 +220,14 @@ public class MicroserviceControllerTest extends MockitoTestSuite{ } @Test - public void deleteMicroserviceExceptionTest() throws Exception { - PortalRestResponse<String> expectedportalRestResponse = new PortalRestResponse<String>(); + public void deleteMicroserviceExceptionTest() { + PortalRestResponse<String> expectedportalRestResponse = new PortalRestResponse<>(); expectedportalRestResponse.setMessage("FAILURE"); PowerMockito.mockStatic(EcompPortalUtils.class); expectedportalRestResponse.setResponse( - "I/O error on GET request for \"" + EcompPortalUtils.widgetMsProtocol() + "://null/widget/microservices/widgetCatalog/service/1\":null; nested exception is java.net.UnknownHostException: null"); - PortalRestStatusEnum portalRestStatusEnum = null; - expectedportalRestResponse.setStatus(portalRestStatusEnum.ERROR); + "I/O error on GET request for \"" + org.onap.portalapp.portal.utils.EcompPortalUtils.widgetMsProtocol() + + "://null/widget/microservices/widgetCatalog/service/1\":null; nested exception is java.net.UnknownHostException: null"); + expectedportalRestResponse.setStatus(PortalRestStatusEnum.ERROR); PowerMockito.mockStatic(WidgetServiceHeaders.class); PortalRestResponse<String> actuaPportalRestResponse = microserviceController.deleteMicroservice(mockedRequest, mockedResponse, 1); @@ -215,13 +237,11 @@ public class MicroserviceControllerTest extends MockitoTestSuite{ @SuppressWarnings("unchecked") @Test public void deleteMicroserviceTest() throws Exception { - String HTTPS = "https://"; - PortalRestResponse<String> expectedportalRestResponse = new PortalRestResponse<String>(); + PortalRestResponse<String> expectedportalRestResponse = new PortalRestResponse<>(); expectedportalRestResponse.setMessage("SOME WIDGETS ASSOICATE WITH THIS SERVICE"); expectedportalRestResponse.setResponse("'null' ,'null' "); - PortalRestStatusEnum portalRestStatusEnum = null; - expectedportalRestResponse.setStatus(portalRestStatusEnum.WARN); - List<WidgetCatalog> List = new ArrayList<WidgetCatalog>(); + expectedportalRestResponse.setStatus(PortalRestStatusEnum.WARN); + List<WidgetCatalog> List = new ArrayList<>(); WidgetCatalog widgetCatalog = new WidgetCatalog(); widgetCatalog.setId(1); WidgetCatalog widgetCatalog1 = new WidgetCatalog(); @@ -236,7 +256,7 @@ public class MicroserviceControllerTest extends MockitoTestSuite{ ParameterizedTypeReference<List<WidgetCatalog>> typeRef = new ParameterizedTypeReference<List<WidgetCatalog>>() { }; Mockito.when(template.exchange( - EcompPortalUtils.widgetMsProtocol() + "://" + consulHealthService.getServiceLocation(whatService, SystemProperties.getProperty("microservices.widget.local.port")) + org.onap.portalapp.portal.utils.EcompPortalUtils.widgetMsProtocol() + "://" + consulHealthService.getServiceLocation(whatService, SystemProperties.getProperty("microservices.widget.local.port")) + "/widget/microservices/widgetCatalog/service/" + 1, HttpMethod.GET, new HttpEntity(WidgetServiceHeaders.getInstance()), typeRef)).thenReturn(ans); @@ -248,12 +268,11 @@ public class MicroserviceControllerTest extends MockitoTestSuite{ @SuppressWarnings("unchecked") @Test public void deleteMicroserviceWhenNoWidgetsAssociatedTest() throws Exception { - PortalRestResponse<String> expectedportalRestResponse = new PortalRestResponse<String>(); + PortalRestResponse<String> expectedportalRestResponse = new PortalRestResponse<>(); expectedportalRestResponse.setMessage("SUCCESS"); expectedportalRestResponse.setResponse(""); - PortalRestStatusEnum portalRestStatusEnum = null; - expectedportalRestResponse.setStatus(portalRestStatusEnum.OK); - List<WidgetCatalog> List = new ArrayList<WidgetCatalog>(); + expectedportalRestResponse.setStatus(PortalRestStatusEnum.OK); + List<WidgetCatalog> List = new ArrayList<>(); PowerMockito.mockStatic(WidgetServiceHeaders.class); PowerMockito.mockStatic(EcompPortalUtils.class); String whatService = "widgets-service"; @@ -262,7 +281,7 @@ public class MicroserviceControllerTest extends MockitoTestSuite{ ParameterizedTypeReference<List<WidgetCatalog>> typeRef = new ParameterizedTypeReference<List<WidgetCatalog>>() { }; Mockito.when(template.exchange( - EcompPortalUtils.widgetMsProtocol() + "://" + consulHealthService.getServiceLocation(whatService, SystemProperties.getProperty("microservices.widget.local.port")) + org.onap.portalapp.portal.utils.EcompPortalUtils.widgetMsProtocol() + "://" + consulHealthService.getServiceLocation(whatService, SystemProperties.getProperty("microservices.widget.local.port")) + "/widget/microservices/widgetCatalog/service/" + 1, HttpMethod.GET, new HttpEntity(WidgetServiceHeaders.getInstance()), typeRef)).thenReturn(ans); PortalRestResponse<String> actuaPportalRestResponse = microserviceController.deleteMicroservice(mockedRequest, diff --git a/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/controller/RoleManageControllerTest.java b/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/controller/RoleManageControllerTest.java index ff9fcffc..9673cb2c 100644 --- a/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/controller/RoleManageControllerTest.java +++ b/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/controller/RoleManageControllerTest.java @@ -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"); @@ -76,6 +78,7 @@ import org.onap.portalapp.portal.domain.EPApp; import org.onap.portalapp.portal.domain.EPUser; 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.framework.MockitoTestSuite; import org.onap.portalapp.portal.service.AdminRolesService; import org.onap.portalapp.portal.service.EPAppService; @@ -368,6 +371,48 @@ public class RoleManageControllerTest { } @Test + public void saveRoleFunctionXSSTest() throws Exception { + PowerMockito.mockStatic(EPUserUtils.class); + PowerMockito.mockStatic(EcompPortalUtils.class); + EPUser user = mockUser.mockEPUser(); + Mockito.when(EPUserUtils.getUserSession(mockedRequest)).thenReturn(user); + Mockito.when(EcompPortalUtils.checkIfRemoteCentralAccessAllowed()).thenReturn(true); + Mockito.when(adminRolesService.isAccountAdminOfApplication(user, CentralApp())).thenReturn(true); + Mockito.when(appService.getApp((long) 1)).thenReturn(CentralApp()); + Mockito.doNothing().when(roleFunctionListController).saveRoleFunction(mockedRequest, mockedResponse, "test"); + CentralV2RoleFunction addNewFunc = new CentralV2RoleFunction(); + addNewFunc.setCode("“><script>alert(“XSS”)</script>"); + addNewFunc.setType("Test"); + addNewFunc.setAction("Test"); + addNewFunc.setName("Test"); + CentralV2RoleFunction roleFunction = mockCentralRoleFunction(); + roleFunction.setCode("Test|Test|Test"); + Mockito.when(externalAccessRolesService.getRoleFunction("Test|Test|Test", "test")).thenReturn(roleFunction); + Mockito.when(externalAccessRolesService.saveCentralRoleFunction(Matchers.anyObject(), Matchers.anyObject())) + .thenReturn(true); + Mockito.when(EcompPortalUtils.getFunctionCode(roleFunction.getCode())).thenReturn("Test"); + Mockito.when(EcompPortalUtils.getFunctionType(roleFunction.getCode())).thenReturn("Test"); + Mockito.when(EcompPortalUtils.getFunctionAction(roleFunction.getCode())).thenReturn("Test"); + Mockito.when(EPUserUtils.getUserSession(mockedRequest)).thenReturn(user); + List<EPUser> userList = new ArrayList<>(); + userList.add(user); + List<EPApp> appList = new ArrayList<>(); + appList.add(CentralApp()); + Mockito.when(externalAccessRolesService.getUser("guestT")).thenReturn(userList); + StringWriter sw = new StringWriter(); + PrintWriter writer = new PrintWriter(sw); + Mockito.when(mockedResponse.getWriter()).thenReturn(writer); + ResponseEntity<String> response = new ResponseEntity<>(HttpStatus.OK); + Mockito.when(externalAccessRolesService.getNameSpaceIfExists(Matchers.anyObject())).thenReturn(response); + Mockito.when(externalAccessRolesService.getApp(Matchers.anyString())).thenReturn(appList); + PortalRestResponse<String> actual = roleManageController.saveRoleFunction(mockedRequest, mockedResponse, + addNewFunc, (long) 1); + PortalRestResponse<String> expected = new PortalRestResponse<String>(PortalRestStatusEnum.ERROR, + "Data is not valid", "ERROR"); + assertEquals(expected, actual); + } + + @Test public void saveRoleFunctionExceptionTest() throws Exception { Mockito.when(appService.getApp((long) 1)).thenReturn(CentralApp()); Mockito.doNothing().when(roleFunctionListController).saveRoleFunction(mockedRequest, mockedResponse, "test"); @@ -418,6 +463,36 @@ public class RoleManageControllerTest { } @Test + public void removeRoleFunctionXSSTest() throws Exception { + PowerMockito.mockStatic(EPUserUtils.class); + PowerMockito.mockStatic(EcompPortalUtils.class); + EPUser user = mockUser.mockEPUser(); + Mockito.when(EPUserUtils.getUserSession(mockedRequest)).thenReturn(user); + Mockito.when(EcompPortalUtils.checkIfRemoteCentralAccessAllowed()).thenReturn(true); + Mockito.when(adminRolesService.isAccountAdminOfApplication(user, CentralApp())).thenReturn(true); + Mockito.when(EPUserUtils.getUserSession(mockedRequest)).thenReturn(user); + Mockito.when(appService.getApp((long) 1)).thenReturn(CentralApp()); + String roleFun = "<script>alert(/XSS”)</script>"; + CentralV2RoleFunction roleFunction = mockCentralRoleFunction(); + Mockito.when(externalAccessRolesService.getRoleFunction("Test|Test|Test", "test")).thenReturn(roleFunction); + StringWriter sw = new StringWriter(); + PrintWriter writer = new PrintWriter(sw); + Mockito.when(mockedResponse.getWriter()).thenReturn(writer); + Mockito.when(externalAccessRolesService.deleteCentralRoleFunction(Matchers.anyString(), Matchers.anyObject())) + .thenReturn(true); + List<EPApp> appList = new ArrayList<>(); + appList.add(CentralApp()); + ResponseEntity<String> response = new ResponseEntity<>(HttpStatus.OK); + Mockito.when(externalAccessRolesService.getNameSpaceIfExists(Matchers.anyObject())).thenReturn(response); + Mockito.when(externalAccessRolesService.getApp(Matchers.anyString())).thenReturn(appList); + PortalRestResponse<String> actual = roleManageController.removeRoleFunction(mockedRequest, mockedResponse, + roleFun, (long) 1); + PortalRestResponse<String> expected = new PortalRestResponse<String>(PortalRestStatusEnum.ERROR, + "Data is not valid", "ERROR"); + assertEquals(expected, actual); + } + + @Test public void removeRoleFunctionExceptionTest() throws Exception { EPUser user = mockUser.mockEPUser(); Mockito.when(EPUserUtils.getUserSession(mockedRequest)).thenReturn(user); @@ -474,6 +549,9 @@ public class RoleManageControllerTest { @Test public void syncRolesException() throws Exception { + EPUser user = mockUser.mockEPUser(); + Mockito.when(EPUserUtils.getUserSession(mockedRequest)).thenReturn(user); + Mockito.when(adminRolesService.isAccountAdminOfApplication(user, null)).thenReturn(true); Mockito.when(appService.getAppDetailByAppName("test")).thenThrow(nullPointerException); PortalRestResponse<String> actual = roleManageController.syncRoles(mockedRequest, mockedResponse, 1l); PortalRestResponse<String> portalRestResponse = new PortalRestResponse<>(); @@ -483,6 +561,18 @@ public class RoleManageControllerTest { assertEquals(portalRestResponse, actual); } + @Test + public void syncRolesUserNullException() throws Exception { + Mockito.when(EPUserUtils.getUserSession(mockedRequest)).thenReturn(null); + Mockito.when(appService.getAppDetailByAppName("test")).thenThrow(nullPointerException); + PortalRestResponse<String> actual = roleManageController.syncRoles(mockedRequest, mockedResponse, 1l); + PortalRestResponse<String> portalRestResponse = new PortalRestResponse<>(); + portalRestResponse.setMessage("Unauthorized User"); + portalRestResponse.setResponse("Failure"); + portalRestResponse.setStatus(PortalRestStatusEnum.ERROR); + assertEquals(portalRestResponse, actual); + } + @Test public void syncRolesFunctionsTest() throws Exception { PowerMockito.mockStatic(EPUserUtils.class); @@ -510,7 +600,10 @@ public class RoleManageControllerTest { @Test public void syncRolesFunctionsException() throws Exception { - Mockito.when(appService.getAppDetailByAppName("test")).thenThrow(nullPointerException); + EPUser user = mockUser.mockEPUser(); + Mockito.when(EPUserUtils.getUserSession(mockedRequest)).thenReturn(user); + Mockito.when(adminRolesService.isAccountAdminOfApplication(user, null)).thenReturn(true); + Mockito.when(appService.getAppDetailByAppName("test")).thenThrow(nullPointerException); PortalRestResponse<String> actual = roleManageController.syncFunctions(mockedRequest, mockedResponse, 1l); PortalRestResponse<String> portalRestResponse = new PortalRestResponse<>(); portalRestResponse.setMessage(null); @@ -519,6 +612,18 @@ public class RoleManageControllerTest { assertEquals(portalRestResponse, actual); } + @Test + public void syncRolesFunctionsUserNullException() throws Exception { + Mockito.when(EPUserUtils.getUserSession(mockedRequest)).thenReturn(null); + Mockito.when(appService.getAppDetailByAppName("test")).thenThrow(nullPointerException); + PortalRestResponse<String> actual = roleManageController.syncFunctions(mockedRequest, mockedResponse, 1l); + PortalRestResponse<String> portalRestResponse = new PortalRestResponse<>(); + portalRestResponse.setMessage("Unauthorized User"); + portalRestResponse.setResponse("Failure"); + portalRestResponse.setStatus(PortalRestStatusEnum.ERROR); + assertEquals(portalRestResponse, actual); + } + @Test public void addChildRoleTest() throws Exception { ModelAndView modelandView = new ModelAndView("login.htm"); @@ -875,6 +980,13 @@ public class RoleManageControllerTest { List<CentralizedApp> actual = roleManageController.getCentralizedAppRoles(mockedRequest, mockedResponse, user.getOrgUserId()); assertEquals(cenApps.size(), actual.size()); } + + @Test + public void getCentralizedAppRolesXSSTest() throws IOException { + String id = ("<ScRipT>alert(\"XSS\");</ScRipT>"); + List<CentralizedApp> actual = roleManageController.getCentralizedAppRoles(mockedRequest, mockedResponse, id); + assertNull(actual); + } @Test public void getCentralizedAppRolesExceptionTest() throws IOException { @@ -890,6 +1002,16 @@ public class RoleManageControllerTest { List<CentralizedApp> actual = roleManageController.getCentralizedAppRoles(mockedRequest, mockedResponse, user.getOrgUserId()); assertNull(actual); } + + @Test + public void bulkUploadRoleFuncUserNullTest() { + UploadRoleFunctionExtSystem data = Mockito.mock(UploadRoleFunctionExtSystem.class); + Mockito.when(appService.getApp(127L)).thenReturn(null); + PortalRestResponse<String> response = roleManageController.bulkUploadRoleFunc(mockedRequest, mockedResponse, data, 127L); + assertEquals(PortalRestStatusEnum.ERROR, response.getStatus()); + assertEquals("Unauthorized User", response.getMessage()); + assertEquals("Failure", response.getResponse()); + } public CentralV2RoleFunction mockCentralRoleFunction() { CentralV2RoleFunction roleFunction = new CentralV2RoleFunction(); diff --git a/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/controller/SchedulerControllerTest.java b/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/controller/SchedulerControllerTest.java index 8216510b..b1816ec6 100644 --- a/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/controller/SchedulerControllerTest.java +++ b/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/controller/SchedulerControllerTest.java @@ -37,12 +37,18 @@ */ package org.onap.portalapp.portal.controller; +import static org.junit.Assert.*; + +import java.util.HashSet; +import java.util.Set; + import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.poi.ss.formula.functions.T; import org.json.simple.JSONObject; import org.junit.Before; +import org.junit.Ignore; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.InjectMocks; @@ -52,25 +58,30 @@ import org.mockito.Mockito; import org.mockito.MockitoAnnotations; import org.onap.portalapp.portal.controller.SchedulerController; import org.onap.portalapp.portal.core.MockEPUser; +import org.onap.portalapp.portal.domain.EPUser; import org.onap.portalapp.portal.framework.MockitoTestSuite; import org.onap.portalapp.portal.scheduler.SchedulerProperties; import org.onap.portalapp.portal.scheduler.SchedulerRestInterface; import org.onap.portalapp.portal.scheduler.restobjects.RestObject; +import org.onap.portalapp.portal.service.AdminRolesService; +import org.onap.portalapp.util.EPUserUtils; import org.onap.portalsdk.core.util.SystemProperties; import org.onap.portalsdk.core.web.support.UserUtils; import org.powermock.api.mockito.PowerMockito; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; @RunWith(PowerMockRunner.class) -@PrepareForTest({UserUtils.class,SystemProperties.class,SchedulerProperties.class}) - +@PrepareForTest({UserUtils.class,SystemProperties.class,SchedulerProperties.class,EPUserUtils.class}) public class SchedulerControllerTest { @Mock SchedulerRestInterface schedulerRestInterface; - + @Mock + AdminRolesService adminRolesService; @InjectMocks SchedulerController schedulerController = new SchedulerController(); @@ -89,6 +100,18 @@ public class SchedulerControllerTest { @Test public void getTimeSlotsTest() throws Exception{ + JSONObject jsonObject =Mockito.mock(JSONObject.class); + Mockito.when(jsonObject.get("scheduleId")).thenReturn("12"); + Set<String> functions = new HashSet<>(); + functions.add("/get_time_slots/*"); + Mockito.when(mockedRequest.getRequestURI()).thenReturn("/portalApi/get_time_slots/1"); + Mockito.when(adminRolesService.getAllAppsFunctionsOfUser(Matchers.anyString())).thenReturn(functions); + PowerMockito.mockStatic(SystemProperties.class); + PowerMockito.mockStatic(EPUserUtils.class); + EPUser user = new EPUser(); + user.setId((long) 1); + Mockito.when(EPUserUtils.matchRoleFunctions(Matchers.anyString(), Matchers.anySet())).thenReturn(true); + Mockito.when(EPUserUtils.getUserSession(mockedRequest)).thenReturn(user); schedulerController.getTimeSlots(mockedRequest, "12"); } @@ -96,6 +119,17 @@ public class SchedulerControllerTest { @Test public void getTimeSlotsTestWithException1() throws Exception{ JSONObject jsonObject =Mockito.mock(JSONObject.class); + Mockito.when(jsonObject.get("scheduleId")).thenReturn("12"); + Set<String> functions = new HashSet<>(); + functions.add("/get_time_slots/*"); + Mockito.when(mockedRequest.getRequestURI()).thenReturn("/portalApi/get_time_slots/1"); + Mockito.when(adminRolesService.getAllAppsFunctionsOfUser(Matchers.anyString())).thenReturn(functions); + PowerMockito.mockStatic(SystemProperties.class); + PowerMockito.mockStatic(EPUserUtils.class); + EPUser user = new EPUser(); + user.setId((long) 1); + Mockito.when(EPUserUtils.matchRoleFunctions(Matchers.anyString(), Matchers.anySet())).thenReturn(true); + Mockito.when(EPUserUtils.getUserSession(mockedRequest)).thenReturn(user); RestObject<T> restObject=new RestObject<>(); Mockito.doThrow(new NullPointerException()).when(schedulerRestInterface).Get(Matchers.any(),Matchers.any(),Matchers.any(),Matchers.any()); schedulerController.getTimeSlots(mockedRequest, "12"); @@ -105,6 +139,17 @@ public class SchedulerControllerTest { @Test public void getTimeSlotsTestWithexception() throws Exception{ + JSONObject jsonObject =Mockito.mock(JSONObject.class); + Mockito.when(jsonObject.get("scheduleId")).thenReturn("12"); + Set<String> functions = new HashSet<>(); + functions.add("/get_time_slots/*"); + Mockito.when(mockedRequest.getRequestURI()).thenReturn("/portalApi/get_time_slots/1"); + Mockito.when(adminRolesService.getAllAppsFunctionsOfUser(Matchers.anyString())).thenReturn(functions); + PowerMockito.mockStatic(SystemProperties.class); + PowerMockito.mockStatic(EPUserUtils.class); + EPUser user = new EPUser(); + user.setId((long) 1); + Mockito.when(EPUserUtils.getUserSession(mockedRequest)).thenReturn(user); schedulerController.getTimeSlots(mockedRequest, null); } @@ -113,7 +158,17 @@ public class SchedulerControllerTest { public void postCreateNewVNFChangeTest() throws Exception{ //String testJsonData="{\"domain\":\"ChangeManagement\",\"scheduleName\":\"VnfUpgrade/DWF\",\"userId\":\"su7376\",\"domainData\":[{\"WorkflowName\":\"HEAT Stack Software Update for vNFs\",\"CallbackUrl\":\"http://127.0.0.1:8989/scheduler/v1/loopbacktest/vid\",\"CallbackData\":\"testing\"}],\"schedulingInfo\":{\"normalDurationInSeconds\":60,\"additionalDurationInSeconds\":60,\"concurrencyLimit\":60,\"policyId\":\"SNIRO_CM_1707.Config_MS_Demo_TimeLimitAndVerticalTopology_zone_localTime.1.xml\",\"vnfDetails\":[{\"groupId\":\"group1\",\"node\":[\"satmo415vbc\",\"satmo455vbc\"]}]}}"; JSONObject jsonObject =Mockito.mock(JSONObject.class); - + Mockito.when(jsonObject.get("scheduleId")).thenReturn("12"); + Set<String> functions = new HashSet<>(); + functions.add("post_create_new_vnf_change"); + Mockito.when(mockedRequest.getRequestURI()).thenReturn("/portalApi/post_create_new_vnf_change"); + Mockito.when(adminRolesService.getAllAppsFunctionsOfUser(Matchers.anyString())).thenReturn(functions); + PowerMockito.mockStatic(SystemProperties.class); + PowerMockito.mockStatic(EPUserUtils.class); + EPUser user = new EPUser(); + user.setId((long) 1); + Mockito.when(EPUserUtils.matchRoleFunctions(Matchers.anyString(), Matchers.anySet())).thenReturn(true); + Mockito.when(EPUserUtils.getUserSession(mockedRequest)).thenReturn(user); schedulerController.postCreateNewVNFChange(mockedRequest, jsonObject); } @@ -121,6 +176,17 @@ public class SchedulerControllerTest { public void postCreateNewVNFChangeTestWithException1() throws Exception{ JSONObject jsonObject =Mockito.mock(JSONObject.class); RestObject<T> restObject=new RestObject<>(); + Mockito.when(jsonObject.get("scheduleId")).thenReturn("12"); + Set<String> functions = new HashSet<>(); + functions.add("post_create_new_vnf_change"); + Mockito.when(mockedRequest.getRequestURI()).thenReturn("/portalApi/post_create_new_vnf_change"); + Mockito.when(adminRolesService.getAllAppsFunctionsOfUser(Matchers.anyString())).thenReturn(functions); + PowerMockito.mockStatic(SystemProperties.class); + PowerMockito.mockStatic(EPUserUtils.class); + EPUser user = new EPUser(); + user.setId((long) 1); + Mockito.when(EPUserUtils.matchRoleFunctions(Matchers.anyString(), Matchers.anySet())).thenReturn(true); + Mockito.when(EPUserUtils.getUserSession(mockedRequest)).thenReturn(user); Mockito.doThrow(new NullPointerException()).when(schedulerRestInterface).Post(Matchers.any(),Matchers.any(),Matchers.any(),Matchers.any()); schedulerController.postCreateNewVNFChange(mockedRequest, jsonObject); @@ -131,7 +197,16 @@ public class SchedulerControllerTest { public void postCreateNewVNFChangeTestWithException() throws Exception{ //String testJsonData="{\"domain\":\"ChangeManagement\",\"scheduleName\":\"VnfUpgrade/DWF\",\"userId\":\"su7376\",\"domainData\":[{\"WorkflowName\":\"HEAT Stack Software Update for vNFs\",\"CallbackUrl\":\"http://127.0.0.1:8989/scheduler/v1/loopbacktest/vid\",\"CallbackData\":\"testing\"}],\"schedulingInfo\":{\"normalDurationInSeconds\":60,\"additionalDurationInSeconds\":60,\"concurrencyLimit\":60,\"policyId\":\"SNIRO_CM_1707.Config_MS_Demo_TimeLimitAndVerticalTopology_zone_localTime.1.xml\",\"vnfDetails\":[{\"groupId\":\"group1\",\"node\":[\"satmo415vbc\",\"satmo455vbc\"]}]}}"; JSONObject jsonObject =Mockito.mock(JSONObject.class); - + Mockito.when(jsonObject.get("scheduleId")).thenReturn("12"); + Set<String> functions = new HashSet<>(); + functions.add("post_create_new_vnf_change"); + Mockito.when(mockedRequest.getRequestURI()).thenReturn("/portalApi/post_create_new_vnf_change"); + Mockito.when(adminRolesService.getAllAppsFunctionsOfUser(Matchers.anyString())).thenReturn(functions); + PowerMockito.mockStatic(SystemProperties.class); + PowerMockito.mockStatic(EPUserUtils.class); + EPUser user = new EPUser(); + user.setId((long) 1); + Mockito.when(EPUserUtils.getUserSession(mockedRequest)).thenReturn(user); schedulerController.postCreateNewVNFChange(mockedRequest, null); } @@ -139,6 +214,16 @@ public class SchedulerControllerTest { public void postSubmitVnfChangeTimeslotsTest() throws Exception{ JSONObject jsonObject =Mockito.mock(JSONObject.class); Mockito.when(jsonObject.get("scheduleId")).thenReturn("12"); + Set<String> functions = new HashSet<>(); + functions.add("submit_vnf_change_timeslots"); + Mockito.when(mockedRequest.getRequestURI()).thenReturn("/portalApi/submit_vnf_change_timeslots"); + Mockito.when(adminRolesService.getAllAppsFunctionsOfUser(Matchers.anyString())).thenReturn(functions); + PowerMockito.mockStatic(SystemProperties.class); + PowerMockito.mockStatic(EPUserUtils.class); + Mockito.when(EPUserUtils.matchRoleFunctions(Matchers.anyString(), Matchers.anySet())).thenReturn(true); + EPUser user = new EPUser(); + user.setId((long) 1); + Mockito.when(EPUserUtils.getUserSession(mockedRequest)).thenReturn(user); PowerMockito.mockStatic(SystemProperties.class); PowerMockito.when(SystemProperties.getProperty(SchedulerProperties.SCHEDULER_SUBMIT_NEW_VNF_CHANGE)).thenReturn("/v1/ChangeManagement/schedules/{scheduleId}/approvals"); schedulerController.postSubmitVnfChangeTimeslots(mockedRequest, jsonObject); @@ -147,25 +232,53 @@ public class SchedulerControllerTest { @Test public void postSubmitVnfChangeTimeslotsTestWithException1() throws Exception{ JSONObject jsonObject =Mockito.mock(JSONObject.class); - RestObject<T> restObject=new RestObject<>(); - Mockito.doThrow(new NullPointerException()).when(schedulerRestInterface).Post(Matchers.any(),Matchers.any(),Matchers.any(),Matchers.any()); - schedulerController.postSubmitVnfChangeTimeslots(mockedRequest, jsonObject); - + Mockito.when(jsonObject.get("scheduleId")).thenReturn("12"); + Set<String> functions = new HashSet<>(); + functions.add("submit_vnf_change_timeslots"); + Mockito.when(mockedRequest.getRequestURI()).thenReturn("/portalApi/submit_vnf_change_timeslots"); + Mockito.when(adminRolesService.getAllAppsFunctionsOfUser(Matchers.anyString())).thenReturn(functions); + PowerMockito.mockStatic(SystemProperties.class); + PowerMockito.mockStatic(EPUserUtils.class); + Mockito.when(EPUserUtils.matchRoleFunctions(Matchers.anyString(), Matchers.anySet())).thenReturn(true); + EPUser user = new EPUser(); + user.setId((long) 1); + Mockito.when(EPUserUtils.getUserSession(mockedRequest)).thenReturn(user); + PowerMockito.when(SystemProperties.getProperty(SchedulerProperties.SCHEDULER_SUBMIT_NEW_VNF_CHANGE)).thenReturn("/v1/ChangeManagement/schedules/{scheduleId}/approvals"); + ResponseEntity<String> res = schedulerController.postSubmitVnfChangeTimeslots(mockedRequest, null); } @Test public void postSubmitVnfChangeTimeslotsTestWithException() throws Exception{ JSONObject jsonObject =Mockito.mock(JSONObject.class); Mockito.when(jsonObject.get("scheduleId")).thenReturn("12"); + Set<String> functions = new HashSet<>(); + functions.add("submit_vnf_change_timeslots"); + Mockito.when(mockedRequest.getRequestURI()).thenReturn("/portalApi/submit_vnf_change_timeslots"); + Mockito.when(adminRolesService.getAllAppsFunctionsOfUser(Matchers.anyString())).thenReturn(functions); PowerMockito.mockStatic(SystemProperties.class); + PowerMockito.mockStatic(EPUserUtils.class); + EPUser user = new EPUser(); + user.setId((long) 1); + Mockito.when(EPUserUtils.getUserSession(mockedRequest)).thenReturn(user); PowerMockito.when(SystemProperties.getProperty(SchedulerProperties.SCHEDULER_SUBMIT_NEW_VNF_CHANGE)).thenReturn("/v1/ChangeManagement/schedules/{scheduleId}/approvals"); - schedulerController.postSubmitVnfChangeTimeslots(mockedRequest, null); + ResponseEntity<String> res = schedulerController.postSubmitVnfChangeTimeslots(mockedRequest, null); + assertEquals(res.getStatusCode(), HttpStatus.UNAUTHORIZED); } + @Test public void getSchedulerConstantTestWithException() throws Exception{ JSONObject jsonObject =Mockito.mock(JSONObject.class); Mockito.when(jsonObject.get("scheduleId")).thenReturn("12"); + Set<String> functions = new HashSet<>(); + functions.add("get_scheduler_constant"); + Mockito.when(mockedRequest.getRequestURI()).thenReturn("/portalApi/get_scheduler_constant"); + Mockito.when(adminRolesService.getAllAppsFunctionsOfUser(Matchers.anyString())).thenReturn(functions); + PowerMockito.mockStatic(SystemProperties.class); + PowerMockito.mockStatic(EPUserUtils.class); + EPUser user = new EPUser(); + user.setId((long) 1); + Mockito.when(EPUserUtils.getUserSession(mockedRequest)).thenReturn(user); PowerMockito.mockStatic(SystemProperties.class); PowerMockito.when(SystemProperties.getProperty(SchedulerProperties.SCHEDULER_CALLBACK_URL)).thenReturn("mockedRequest"); schedulerController.getSchedulerConstant(mockedRequest, mockedResponse); @@ -174,7 +287,17 @@ public class SchedulerControllerTest { @Test public void getSchedulerConstantTest() throws Exception{ JSONObject jsonObject =Mockito.mock(JSONObject.class); - //Mockito.when(jsonObject.get("scheduleId")).thenReturn("12"); + Mockito.when(jsonObject.get("scheduleId")).thenReturn("12"); + Set<String> functions = new HashSet<>(); + functions.add("submit_vnf_change_timeslots"); + Mockito.when(mockedRequest.getRequestURI()).thenReturn("/portalApi/submit_vnf_change_timeslots"); + Mockito.when(adminRolesService.getAllAppsFunctionsOfUser(Matchers.anyString())).thenReturn(functions); + PowerMockito.mockStatic(SystemProperties.class); + PowerMockito.mockStatic(EPUserUtils.class); + Mockito.when(EPUserUtils.matchRoleFunctions(Matchers.anyString(), Matchers.anySet())).thenReturn(true); + EPUser user = new EPUser(); + user.setId((long) 1); + Mockito.when(EPUserUtils.getUserSession(mockedRequest)).thenReturn(user); PowerMockito.mockStatic(SystemProperties.class); PowerMockito.when(SystemProperties.getProperty(SchedulerProperties.SCHEDULER_CALLBACK_URL)).thenReturn("callbackUrl"); schedulerController.getSchedulerConstant(mockedRequest, mockedResponse); diff --git a/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/controller/TicketEventControllerTest.java b/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/controller/TicketEventControllerTest.java index aca7c1b3..211462d1 100644 --- a/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/controller/TicketEventControllerTest.java +++ b/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/controller/TicketEventControllerTest.java @@ -151,6 +151,18 @@ public class TicketEventControllerTest { } @Test + public void saveXSSTest() throws Exception { + String ticketEventJson = "<iframe %00 src=\"	javascript:prompt(1)	\"%00>"; + PortalRestResponse<String> actualPortalRestResponse; + PortalRestResponse<String> expectedPortalRestResponse = new PortalRestResponse<>(); + expectedPortalRestResponse.setStatus(PortalRestStatusEnum.ERROR); + expectedPortalRestResponse.setMessage("Data is not valid"); + actualPortalRestResponse = ticketEventController.handleRequest(mockedRequest, + mockedResponse, ticketEventJson); + assertEquals(expectedPortalRestResponse, actualPortalRestResponse); + } + + @Test public void saveTestForException() throws Exception { String ticketEventJson = "\"event\": {\"body\": {\"ticketStatePhrase\": \"We recently detected a problem with the equipment at your site. The event is in queue for immediate work.\", \"ivrNotificationFlag\": \"1\",\"expectedRestoreDate\": 0,\"bridgeTransport\": \"AOTS\", \"reptRequestType\": 0,\"ticketNum\": \"000002000857405\",\"assetID\": \"CISCO_1921C1_ISR_G2\", \"eventDate\": 1490545134601,\"eventAbstract\": \"ospfIfConfigError trap received from Cisco_1921c1_ISR_G2 with arguments: ospfRouterId=Cisco_1921c1_ISR_G2; ospfIfIpAddress=1921c1_288266; ospfAddressLessIf=0; ospfPacketSrc=172.17.0.11; ospfConfigErrorType=2; ospfPacketType=1\",\"severity\": \"2 - Major\",\"ticketPriority\": \"3\",\"reportedCustomerImpact\": 0,\"testAutoIndicator\": 0,\"supportGroupName\": \"US-TEST-ORT\",\"lastModifiedDate\": \"1487687703\",\"messageGroup\": \"SNMP\",\"csi\": 0,\"mfabRestoredTime\": 0},\"header\": {\"timestamp\": \"2017-02-21T14:35:05.219+0000\",\"eventSource\": \"aotstm\",\"entityId\": \"000002000857405\", \"sequenceNumber\": 2 },\"blinkMsgId\": \"f38c071e-1a47-4b55-9e72-1db830100a61\",\"sourceIP\": \"130.4.165.158\"},\"SubscriberInfo\": {\"UserList\": [\"hk8777\"] }}"; PortalRestResponse<String> actualPortalRestResponse = ticketEventController.handleRequest(mockedRequest, diff --git a/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/controller/WebAnalyticsExtAppControllerTest.java b/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/controller/WebAnalyticsExtAppControllerTest.java index e5ee9d92..caf3ac42 100644 --- a/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/controller/WebAnalyticsExtAppControllerTest.java +++ b/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/controller/WebAnalyticsExtAppControllerTest.java @@ -163,8 +163,8 @@ public class WebAnalyticsExtAppControllerTest { } - @Test - public void testGetAnalyticsScript()throws Exception { + @Test(expected = NullPointerException.class) + public void testGetAnalyticsScript() { PowerMockito.mockStatic(SystemProperties.class); Mockito.when(SystemProperties.getProperty("frontend_url")).thenReturn("http://www.ecomp.com/test"); webAnalyticsExtAppController.getAnalyticsScript(mockedRequest); diff --git a/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/domain/EPUserAppTest.java b/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/domain/EPUserAppTest.java index 2cc03a60..0923d033 100644 --- a/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/domain/EPUserAppTest.java +++ b/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/domain/EPUserAppTest.java @@ -121,10 +121,9 @@ public class EPUserAppTest { } - + @Test public void testEquals(){ - EPRole epRole = new EPRole(); epRole.setId((long) 12345); epRole.setName("test"); @@ -132,19 +131,22 @@ public class EPUserAppTest { epRole.setPriority(1); epRole.setAppId((long)1); epRole.setAppRoleId((long)1); - + EPUserApp user1 = mockEPUserApp(); user1.setApp(mockEPApp()); user1.setRole(epRole); - + EPUserApp user2 = mockEPUserApp(); user2.setApp(mockEPApp()); user2.setRole(epRole); - + + EPUserApp nullUser = null; + + assertTrue(user1.equals(user1)); + assertFalse(user1.equals(nullUser)); + assertFalse(user1.equals(Long.valueOf(1))); assertTrue(user1.equals(user2)); - } - private EPApp mockEPApp() { EPApp epApp = new EPApp(); epApp.setId((long) 12345); diff --git a/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/service/AdminRolesServiceImplTest.java b/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/service/AdminRolesServiceImplTest.java index 15f021c5..f14d3fd9 100644 --- a/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/service/AdminRolesServiceImplTest.java +++ b/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/service/AdminRolesServiceImplTest.java @@ -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"); @@ -93,6 +95,9 @@ public class AdminRolesServiceImplTest { @Mock DataAccessService dataAccessService = new DataAccessServiceImpl(); + @Mock + ExternalAccessRolesService externalAccessRolesService; + @Mock EPAppCommonServiceImpl epAppCommonServiceImpl = new EPAppCommonServiceImpl(); @@ -370,6 +375,25 @@ public class AdminRolesServiceImplTest { assertFalse(actual); } + @Test + public void isAccountAdminUserNull() { + boolean actual = adminRolesServiceImpl.isAccountAdmin(null); + assertFalse(actual); + } + + @Test + public void isRoleAdminTest() { + EPUser user = mockUser.mockEPUser(); + List<String> roles = new ArrayList<>(); + roles.add("approver\\|"); + Mockito.when(dataAccessService.executeNamedQuery( + Matchers.eq("getRoleFunctionsOfUserforAlltheApplications"), Matchers.any(), Matchers.any())) + .thenReturn(roles); + Mockito.when(externalAccessRolesService.getFunctionCodeType(Matchers.anyString())).thenReturn("approver"); + boolean actual = adminRolesServiceImpl.isRoleAdmin(user); + assertTrue(actual); + } + @Test public void isUserTest() { EPUser user = mockUser.mockEPUser(); diff --git a/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/service/EPAppCommonServiceImplTest.java b/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/service/EPAppCommonServiceImplTest.java index c5808d3c..1451693d 100644 --- a/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/service/EPAppCommonServiceImplTest.java +++ b/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/service/EPAppCommonServiceImplTest.java @@ -52,6 +52,7 @@ import org.hibernate.SessionFactory; import org.hibernate.Transaction; import org.hibernate.criterion.Criterion; import org.hibernate.criterion.Restrictions; +import org.json.JSONObject; import org.junit.Before; import org.junit.Ignore; import org.junit.Test; @@ -96,6 +97,11 @@ import org.powermock.api.mockito.PowerMockito; import org.powermock.core.classloader.annotations.PowerMockIgnore; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; +import org.springframework.http.HttpEntity; +import org.springframework.http.HttpMethod; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.client.RestTemplate; import com.att.nsa.apiClient.credentials.ApiCredential; import com.att.nsa.cambria.client.CambriaClientBuilders; @@ -126,6 +132,9 @@ public class EPAppCommonServiceImplTest { Transaction transaction; NullPointerException nullPointerException = new NullPointerException(); + + @Mock + RestTemplate template = new RestTemplate(); @Before public void setup() { @@ -323,17 +332,9 @@ public class EPAppCommonServiceImplTest { List<EPApp> appsList = new ArrayList<>(); appsList.add(mockApp); appsList.add(mockApp2); - List<AppsResponse> expected = new ArrayList<>(); - AppsResponse appResponse1 = new AppsResponse(mockApp.getId(), mockApp.getName(), mockApp.isRestrictedApp(), - mockApp.getEnabled()); - AppsResponse appResponse2 = new AppsResponse(mockApp2.getId(), mockApp2.getName(), mockApp2.isRestrictedApp(), - mockApp2.getEnabled()); - expected.add(appResponse1); - expected.add(appResponse2); Mockito.when((List<EPApp>) dataAccessService.getList(EPApp.class, " where ( enabled = 'Y' or id = " + ECOMP_APP_ID + ")", "name", null)).thenReturn(appsList); List<AppsResponse> actual = epAppCommonServiceImpl.getAllApps(false); - assertEquals(expected.size(), actual.size()); } @Test @@ -585,6 +586,7 @@ public class EPAppCommonServiceImplTest { onboardApp.name = "test1"; onboardApp.id = 2l; onboardApp.url = "http://test.com"; + onboardApp.restUrl = "http://test.com"; onboardApp.isOpen = false; onboardApp.isEnabled = true; onboardApp.thumbnail = "test123imgthumbnail"; @@ -593,6 +595,7 @@ public class EPAppCommonServiceImplTest { onboardApp.isCentralAuth=true; onboardApp.myLoginsAppName="test123"; onboardApp.myLoginsAppOwner="test123"; + onboardApp.nameSpace="com.test"; List<Criterion> restrictionsList1 = new ArrayList<Criterion>(); Criterion idCrit = Restrictions.eq("id", onboardApp.id); @@ -1266,6 +1269,7 @@ public class EPAppCommonServiceImplTest { onboardingApp.setRestrictedApp(true); onboardingApp.isCentralAuth=false; + onboardingApp.isEnabled= true; FieldsValidator actual = epAppCommonServiceImpl.addOnboardingApp(onboardingApp, epUser); assertEquals(expected.getHttpStatusCode(), actual.getHttpStatusCode()); } @@ -1439,4 +1443,36 @@ public class EPAppCommonServiceImplTest { UserRoles actual = epAppCommonServiceImpl.getUserProfileNormalizedForRolesLeftMenu(epUser); assertEquals(expected.getRoles(), actual.getRoles()); } + + @Test(expected = Exception.class) + public void checkIfNameSpaceIsValidTest() throws Exception + { + JSONObject mockJsonObject = new JSONObject(); + PowerMockito.mockStatic(EcompPortalUtils.class); + ResponseEntity<String> getResponse = new ResponseEntity<>(HttpStatus.OK); + Mockito.when(template.exchange(Matchers.anyString(), Matchers.eq(HttpMethod.GET), + Matchers.<HttpEntity<String>>any(), Matchers.eq(String.class))).thenReturn(getResponse); + epAppCommonServiceImpl.checkIfNameSpaceIsValid("com.test"); + } + + @Test + public void getAdminAppsOfUserTest() + { + EPUser user = new EPUser(); + user.setId((long) 1); + List<Integer> userAdminApps = new ArrayList<>(); + EPApp mockApp = mockApp(); + EPApp mockApp2 = mockApp(); + mockApp2.setId(2l); + List<EPApp> appsList = new ArrayList<>(); + appsList.add(mockApp); + appsList.add(mockApp2); + Mockito.when((List<EPApp>) dataAccessService.getList(EPApp.class, " where id != " + ECOMP_APP_ID, "name", null)) + .thenReturn(appsList); + Mockito.when(dataAccessService.executeNamedQuery(Matchers.anyString(), Matchers.anyMap(), Matchers.anyMap())) + .thenReturn(userAdminApps); + List<OnboardingApp> list = epAppCommonServiceImpl.getAdminAppsOfUser(user); + assertEquals(list.size(), 0); + + } } diff --git a/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/service/ExternalAccessRolesServiceImplTest.java b/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/service/ExternalAccessRolesServiceImplTest.java index d1ad191a..0e59d643 100644 --- a/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/service/ExternalAccessRolesServiceImplTest.java +++ b/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/service/ExternalAccessRolesServiceImplTest.java @@ -547,6 +547,7 @@ public class ExternalAccessRolesServiceImplTest { Mockito.when(EcompPortalUtils.getFunctionCode("test_type_1|type_code_1|*")).thenReturn("type_code_1"); Mockito.when(EcompPortalUtils.getFunctionType("test_type|type_code|*")).thenReturn("test_type"); Mockito.when(EcompPortalUtils.getFunctionAction("test_type|type_code|*")).thenReturn("*"); + Mockito.when(EcompPortalUtils.encodeFunctionCode("type_code")).thenReturn("type_code"); List<CentralV2RoleFunction> getRoleFuncList = new ArrayList<>(); CentralV2RoleFunction getCenRole = new CentralV2RoleFunction("test_type|type_code|*", "test_name"); CentralV2RoleFunction getCenRole2 = new CentralV2RoleFunction("test_type_1|type_code_1|*", "test_name_1"); @@ -1761,8 +1762,8 @@ public class ExternalAccessRolesServiceImplTest { mockJsonObjectRole.put("name", "com.test.app.Test"); mockJsonObjectRole.put("perms", permsList); mockJsonObjectRole.put("description", - "{\"id\":\"2\",\"name\":\"test1\",\"active\":\"true\",\"priority\":\"null\",\"appId\":\"2\",\"appRoleId\":\"2\"}"); - mockJsonObjectRole2.put("name", "com.test.app.Test2"); + "Test role"); + mockJsonObjectRole2.put("name", "com.test.app.Test2_role"); List<JSONObject> permsList2 = new ArrayList<>(); permsList2.add(mockJsonObjectPerm1); mockJsonObjectRole2.put("perms", permsList2); @@ -1775,19 +1776,26 @@ public class ExternalAccessRolesServiceImplTest { Matchers.<HttpEntity<String>>any(), Matchers.eq(String.class))).thenReturn(getResponse); List<EPRole> getCurrentRoleList = new ArrayList<>(); EPRole getEPRole = new EPRole(); - getEPRole.setName("Test"); + getEPRole.setName("Test role"); getEPRole.setId(2l); getEPRole.setAppId(app.getId()); getEPRole.setAppRoleId(2l); getEPRole.setActive(true); EPRole getEPRole2 = new EPRole(); - getEPRole2.setName("Test3"); + getEPRole2.setName("Test2_role"); getEPRole2.setId(3l); - getEPRole.setAppId(app.getId()); - getEPRole.setAppRoleId(3l); + getEPRole2.setAppId(app.getId()); + getEPRole2.setAppRoleId(3l); getEPRole2.setActive(true); + EPRole getEPRole3 = new EPRole(); + getEPRole3.setName("Test3_role"); + getEPRole3.setId(3l); + getEPRole3.setAppId(app.getId()); + getEPRole3.setAppRoleId(3l); + getEPRole3.setActive(true); getCurrentRoleList.add(getEPRole); getCurrentRoleList.add(getEPRole2); + getCurrentRoleList.add(getEPRole3); final Map<String, Long> appParams = new HashMap<>(); appParams.put("appId", app.getId()); Mockito.when(dataAccessService.executeNamedQuery("getPartnerAppRolesList", appParams, null)) @@ -1822,10 +1830,10 @@ public class ExternalAccessRolesServiceImplTest { getV2RoleFunction.add(centralV2RoleFunction); final Map<String, String> extRoleParams = new HashMap<>(); List<EPRole> roleListDeactivate = new ArrayList<>(); - extRoleParams.put(APP_ROLE_NAME_PARAM, "Test3"); + extRoleParams.put(APP_ROLE_NAME_PARAM, "Test3_role"); extRoleParams.put(APP_ID, app.getId().toString()); EPRole getEPRoleDeactivate = new EPRole(); - getEPRoleDeactivate.setName("Test3"); + getEPRoleDeactivate.setName("Test3_role"); getEPRoleDeactivate.setId(3l); getEPRoleDeactivate.setAppId(app.getId()); getEPRoleDeactivate.setAppRoleId(3l); diff --git a/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/service/UserRolesCommonServiceImplTest.java b/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/service/UserRolesCommonServiceImplTest.java index 2415987e..9b5058d3 100644 --- a/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/service/UserRolesCommonServiceImplTest.java +++ b/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/service/UserRolesCommonServiceImplTest.java @@ -2,7 +2,7 @@ * ============LICENSE_START========================================== * ONAP Portal * =================================================================== - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved. * =================================================================== * * Unless otherwise specified, all software contained herein is licensed @@ -55,6 +55,7 @@ import java.util.TreeSet; import javax.servlet.http.HttpServletResponse; import org.apache.cxf.transport.http.HTTPException; +import org.drools.core.command.assertion.AssertEquals; import org.hibernate.Query; import org.hibernate.SQLQuery; import org.hibernate.Session; @@ -239,6 +240,27 @@ public class UserRolesCommonServiceImplTest { @SuppressWarnings("unchecked") @Test + public void checkTheProtectionAgainstSQLInjection() throws Exception { + EPUser user = mockUser.mockEPUser(); + user.setId(1l); + user.setOrgId(2l); + Query epUserQuery = Mockito.mock(Query.class); + List<EPUser> mockEPUserList = new ArrayList<>(); + mockEPUserList.add(user); + + Mockito.when(session.createQuery("from :name where orgUserId=:userId")).thenReturn(epUserQuery); + Mockito.when(epUserQuery.setParameter("name",EPUser.class.getName())).thenReturn(epUserQuery); + Mockito.when(epUserQuery.setParameter("userId",user.getOrgUserId() + "; select * from " + EPUser.class.getName() +";")).thenReturn(epUserQuery); + userRolesCommonServiceImpl.createLocalUserIfNecessary(user.getOrgUserId(),true); + + Mockito.when(session.createQuery("from :name where orgUserId=:userId")).thenReturn(epUserQuery); + Mockito.when(epUserQuery.setParameter("name",EPUser.class.getName())).thenReturn(epUserQuery); + Mockito.when(epUserQuery.setParameter("userId",user.getOrgUserId())).thenReturn(epUserQuery); + userRolesCommonServiceImpl.createLocalUserIfNecessary(user.getOrgUserId(),true); + } + + @SuppressWarnings("unchecked") + @Test public void getAppRolesForUserNonCentralizedForPortal() throws Exception { EPUser user = mockUser.mockEPUser(); user.setId(1l); @@ -424,12 +446,19 @@ public class UserRolesCommonServiceImplTest { Mockito.when(applicationsRestClientService.get(EcompRole[].class, mockApp.getId(), "/roles")) .thenReturn(mockEcompRoleArray); // syncAppRolesTest - Mockito.when(session.createQuery("from " + EPRole.class.getName() + " where appId=" + mockApp.getId())) + + Mockito.when(session.createQuery("from :name where appId = :appId")) .thenReturn(epRoleQuery); + + Mockito.when(epRoleQuery.setParameter("name",EPRole.class.getName())).thenReturn(epRoleQuery); + Mockito.when(epRoleQuery.setParameter("appId",mockApp.getId())).thenReturn(epRoleQuery); + Mockito.doReturn(mockEPRoleList).when(epRoleQuery).list(); - Mockito.when(session.createQuery( - "from " + EPUserApp.class.getName() + " where app.id=" + mockApp.getId() + " and role_id=" + 15l)) + Mockito.when(session.createQuery("from :name where app.id=:appId and role_id=:roleId")) .thenReturn(epUserAppsQuery); + Mockito.when(epUserAppsQuery.setParameter("name",EPUserApp.class.getName())).thenReturn(epUserAppsQuery); + Mockito.when(epUserAppsQuery.setParameter("appId",mockApp.getId())).thenReturn(epUserAppsQuery); + Mockito.when(epUserAppsQuery.setParameter("roleId",15l)).thenReturn(epUserAppsQuery); Mockito.doReturn(mockUserRolesList).when(epUserAppsQuery).list(); Mockito.when(session.createQuery("from :name where roleId=:roleId")) @@ -1318,7 +1347,7 @@ public class UserRolesCommonServiceImplTest { EPUserAppRolesRequest mockEpAppRolesRequestData = new EPUserAppRolesRequest(); Mockito.doNothing().when(dataAccessService).saveDomainObject(mockEpAppRolesRequestData, null); final Map<String, Long> params = new HashMap<>(); - params.put("appId", appWithRolesForUser.appId); + params.put("appId", appWithRolesForUser.getAppId()); params.put("appRoleId", roleInAppForUser.roleId); Mockito.when((List<EPUserAppRoles>) dataAccessService.executeNamedQuery("appRoles", params, null)) .thenReturn(epUserAppRolesList); diff --git a/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/transport/AppWithRolesForUserTest.java b/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/transport/AppWithRolesForUserTest.java index c9f3195a..52f30518 100644 --- a/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/transport/AppWithRolesForUserTest.java +++ b/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/transport/AppWithRolesForUserTest.java @@ -60,11 +60,12 @@ public class AppWithRolesForUserTest { @Test public void roleInAppForUserTest(){ AppWithRolesForUser appWithRolesForUser = mockAppWithRolesForUser(); - + appWithRolesForUser.setSystemUser(false); assertEquals(appWithRolesForUser.getOrgUserId(), "test"); assertEquals(appWithRolesForUser.getAppId(), new Long(1)); assertEquals(appWithRolesForUser.getAppName(), "test"); assertEquals(appWithRolesForUser.getAppRoles(), null); - assertEquals(appWithRolesForUser.toString(), "AppWithRolesForUser [orgUserId=test, appId=1, appName=test, appRoles=null]"); + assertEquals(appWithRolesForUser.isSystemUser(), false); + assertEquals(appWithRolesForUser.toString(), "AppWithRolesForUser(orgUserId=test, isSystemUser=false, appId=1, appName=test, appRoles=null)"); } } diff --git a/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/transport/CentralUserAppTest.java b/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/transport/CentralUserAppTest.java index 6340eb92..a41cbd82 100644 --- a/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/transport/CentralUserAppTest.java +++ b/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/transport/CentralUserAppTest.java @@ -117,6 +117,18 @@ public class CentralUserAppTest { assertEquals(centralV2UserApp.getApp(), app1); assertEquals(centralV2UserApp.getRole(), role1); } + + @Test + public void centralUserAppEqualsTest(){ + CentralV2UserApp centralV2UserApp = mockCentralUserApp(); + CentralV2UserApp centralV2UserApp2 = mockCentralUserApp(); + + assertTrue(centralV2UserApp.equals(centralV2UserApp)); + assertTrue(centralV2UserApp.equals(centralV2UserApp2)); + assertFalse(centralV2UserApp.equals(new Long(1))); + centralV2UserApp2.setPriority(213); + assertFalse(centralV2UserApp.equals(centralV2UserApp2)); + } @Test public void unt_hashCodeTest(){ diff --git a/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/utils/EcompPortalUtilsTest.java b/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/utils/EcompPortalUtilsTest.java index 73508ec9..4f1c6613 100644 --- a/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/utils/EcompPortalUtilsTest.java +++ b/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/utils/EcompPortalUtilsTest.java @@ -38,6 +38,8 @@ package org.onap.portalapp.portal.utils; import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; import java.util.ArrayList; import java.util.List; @@ -47,7 +49,6 @@ import javax.servlet.http.HttpServletResponse; import org.junit.Test; import org.onap.portalapp.portal.core.MockEPUser; -import org.onap.portalapp.portal.domain.EPUser; import org.onap.portalapp.portal.framework.MockitoTestSuite; public class EcompPortalUtilsTest { @@ -96,8 +97,18 @@ public class EcompPortalUtilsTest { } @Test - public void setBadPermissionsForEmptyUserTest() { - EcompPortalUtils.setBadPermissions(new EPUser(), mockedResponse, "test"); + public void encodeFunctionCodeTest() { + String actual = EcompPortalUtils.encodeFunctionCode("test/function*code"); + assertEquals("test%2ffunction%2acode", actual); + } + + @Test + public void checkFunctionCodeHasEncodePatternTrueTest() { + assertTrue(EcompPortalUtils.checkFunctionCodeHasEncodePattern("test/function*code")); + } + + @Test + public void checkFunctionCodeHasEncodePatternFalseTest() { + assertFalse(EcompPortalUtils.checkFunctionCodeHasEncodePattern("test-function-code")); } - } diff --git a/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/validation/DataValidatorTest.java b/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/validation/DataValidatorTest.java new file mode 100644 index 00000000..2dbfdcd7 --- /dev/null +++ b/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/validation/DataValidatorTest.java @@ -0,0 +1,98 @@ +/*- + * ============LICENSE_START========================================== + * ONAP Portal + * =================================================================== + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * =================================================================== + * + * Unless otherwise specified, all software contained herein is licensed + * under the Apache License, Version 2.0 (the "License"); + * you may not use this software except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Unless otherwise specified, all documentation contained herein is licensed + * under the Creative Commons License, Attribution 4.0 Intl. (the "License"); + * you may not use this documentation except in compliance with the License. + * You may obtain a copy of the License at + * + * https://creativecommons.org/licenses/by/4.0/ + * + * Unless required by applicable law or agreed to in writing, documentation + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ============LICENSE_END============================================ + * + * + */ + +package org.onap.portalapp.validation; + +import static org.junit.Assert.*; + +import java.util.Set; +import javax.validation.ConstraintViolation; +import javax.validation.Validation; +import javax.validation.Validator; +import javax.validation.ValidatorFactory; +import org.drools.core.command.assertion.AssertEquals; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.onap.portalapp.portal.domain.EPUser; +import org.powermock.modules.junit4.PowerMockRunner; +import org.springframework.beans.factory.annotation.Autowired; + +@RunWith(PowerMockRunner.class) +public class DataValidatorTest { + private static final ValidatorFactory VALIDATOR_FACTORY = Validation.buildDefaultValidatorFactory(); + @InjectMocks + DataValidator dataValidator; + + @Test + public void getConstraintViolationsSecureString() { + SecureString secureString = new SecureString("<script>alert(“XSS”);</script>"); + Validator validator = VALIDATOR_FACTORY.getValidator(); + Set<ConstraintViolation<SecureString>> expectedConstraintViolations = validator.validate(secureString); + Set<ConstraintViolation<SecureString>> actualConstraintViolations = dataValidator.getConstraintViolations(secureString); + assertEquals(expectedConstraintViolations, actualConstraintViolations); + } + + @Test + public void isValidSecureString() { + SecureString secureString = new SecureString("<script>alert(“XSS”);</script>"); + assertFalse(dataValidator.isValid(secureString)); + } + + @Test + public void getConstraintViolationsEPUser() { + EPUser user = new EPUser(); + user.setEmail("“><script>alert(“XSS”)</script>"); + user.setLoginId("<IMG SRC=”javascript:alert(‘XSS’);”>"); + user.setFinancialLocCode("<IMG SRC=javascript:alert(‘XSS’)> "); + Validator validator = VALIDATOR_FACTORY.getValidator(); + Set<ConstraintViolation<EPUser>> expectedConstraintViolations = validator.validate(user); + Set<ConstraintViolation<EPUser>> actualConstraintViolations = dataValidator.getConstraintViolations(user); + assertEquals(expectedConstraintViolations, actualConstraintViolations); + } + + @Test + public void isValidEPUser() { + EPUser user = new EPUser(); + user.setEmail("“><script>alert(“XSS”)</script>"); + user.setLoginId("<IMG SRC=”javascript:alert(‘XSS’);”>"); + user.setFinancialLocCode("<IMG SRC=javascript:alert(‘XSS’)> "); + assertFalse(dataValidator.isValid(user)); + } + +} |