diff --git a/core/src/main/java/io/aiven/klaw/service/AclControllerService.java b/core/src/main/java/io/aiven/klaw/service/AclControllerService.java index 1ca39ad63..9c2e264ae 100644 --- a/core/src/main/java/io/aiven/klaw/service/AclControllerService.java +++ b/core/src/main/java/io/aiven/klaw/service/AclControllerService.java @@ -60,7 +60,6 @@ import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.beans.factory.annotation.Value; import org.springframework.http.ResponseEntity; -import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.stereotype.Service; @Service @@ -100,7 +99,7 @@ public ApiResponse createAcl(AclRequestsModel aclRequestsModel) throws KlawExcep aclRequestsModel.setRequestingteam(commonUtilsService.getTeamId(currentUserName)); if (commonUtilsService.isNotAuthorizedUser( - getPrincipal(), PermissionType.REQUEST_CREATE_SUBSCRIPTIONS)) { + commonUtilsService.getPrincipal(), PermissionType.REQUEST_CREATE_SUBSCRIPTIONS)) { return ApiResponse.NOT_AUTHORIZED; } @@ -454,7 +453,7 @@ public List getAclRequestsForApprover( // get requests relevant to your teams or all teams if (commonUtilsService.isNotAuthorizedUser( - getPrincipal(), PermissionType.APPROVE_ALL_REQUESTS_TEAMS)) { + commonUtilsService.getPrincipal(), PermissionType.APPROVE_ALL_REQUESTS_TEAMS)) { createdAclReqs = manageDatabase .getHandleDbRequests() @@ -521,7 +520,7 @@ private List updateCreatAclReqsList( public ApiResponse deleteAclRequests(String req_no) throws KlawException { try { if (commonUtilsService.isNotAuthorizedUser( - getPrincipal(), PermissionType.REQUEST_CREATE_SUBSCRIPTIONS)) { + commonUtilsService.getPrincipal(), PermissionType.REQUEST_CREATE_SUBSCRIPTIONS)) { return ApiResponse.NOT_AUTHORIZED; } String userName = getCurrentUserName(); @@ -544,7 +543,7 @@ public ApiResponse claimAcl(int aclId) throws KlawException { log.info("claimAcl {}", aclId); if (commonUtilsService.isNotAuthorizedUser( - getPrincipal(), PermissionType.REQUEST_CREATE_SUBSCRIPTIONS)) { + commonUtilsService.getPrincipal(), PermissionType.REQUEST_CREATE_SUBSCRIPTIONS)) { return ApiResponse.NOT_AUTHORIZED; } @@ -619,7 +618,7 @@ public ApiResponse createDeleteAclSubscriptionRequest(String req_no) throws Klaw log.info("createDeleteAclSubscriptionRequest {}", req_no); final String userName = getCurrentUserName(); if (commonUtilsService.isNotAuthorizedUser( - getPrincipal(), PermissionType.REQUEST_DELETE_SUBSCRIPTIONS)) { + commonUtilsService.getPrincipal(), PermissionType.REQUEST_DELETE_SUBSCRIPTIONS)) { return ApiResponse.NOT_AUTHORIZED; } @@ -677,7 +676,7 @@ public ApiResponse approveAclRequests(String req_no) final String userDetails = getCurrentUserName(); int tenantId = commonUtilsService.getTenantId(userDetails); if (commonUtilsService.isNotAuthorizedUser( - getPrincipal(), PermissionType.APPROVE_SUBSCRIPTIONS)) { + commonUtilsService.getPrincipal(), PermissionType.APPROVE_SUBSCRIPTIONS)) { return ApiResponse.NOT_AUTHORIZED; } @@ -1033,7 +1032,7 @@ public ApiResponse declineAclRequests(String req_no, String reasonToDecline) String userDetails = getCurrentUserName(); if (commonUtilsService.isNotAuthorizedUser( - getPrincipal(), PermissionType.APPROVE_SUBSCRIPTIONS)) { + commonUtilsService.getPrincipal(), PermissionType.APPROVE_SUBSCRIPTIONS)) { return ApiResponse.NOT_AUTHORIZED; } @@ -1111,10 +1110,6 @@ public List getConsumerOffsets( return consumerOffsetInfoList; } - private Object getPrincipal() { - return SecurityContextHolder.getContext().getAuthentication().getPrincipal(); - } - public ServiceAccountDetails getAivenServiceAccountDetails( String envId, String topicName, String serviceAccount, String aclReqNo) { String loggedInUser = getCurrentUserName(); diff --git a/core/src/main/java/io/aiven/klaw/service/AclSyncControllerService.java b/core/src/main/java/io/aiven/klaw/service/AclSyncControllerService.java index b1a0b1953..1304e4803 100644 --- a/core/src/main/java/io/aiven/klaw/service/AclSyncControllerService.java +++ b/core/src/main/java/io/aiven/klaw/service/AclSyncControllerService.java @@ -43,7 +43,6 @@ import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.ResponseEntity; -import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.stereotype.Service; @Service @@ -82,7 +81,8 @@ public ApiResponse updateSyncAcls(List syncAclUpdates) throws Kl String userName = getUserName(); int tenantId = commonUtilsService.getTenantId(userName); - if (commonUtilsService.isNotAuthorizedUser(getPrincipal(), PermissionType.SYNC_SUBSCRIPTIONS)) { + if (commonUtilsService.isNotAuthorizedUser( + commonUtilsService.getPrincipal(), PermissionType.SYNC_SUBSCRIPTIONS)) { return ApiResponse.NOT_AUTHORIZED; } @@ -179,7 +179,7 @@ public ApiResponse updateSyncBackAcls(SyncBackAcls syncBackAcls) throws KlawExce logArray.add("Type of Sync " + syncBackAcls.getTypeOfSync()); if (commonUtilsService.isNotAuthorizedUser( - getPrincipal(), PermissionType.SYNC_BACK_SUBSCRIPTIONS)) { + commonUtilsService.getPrincipal(), PermissionType.SYNC_BACK_SUBSCRIPTIONS)) { return ApiResponse.NOT_AUTHORIZED; } @@ -395,7 +395,8 @@ public List getSyncAcls( topicNameSearch = topicNameSearch.trim(); } - if (commonUtilsService.isNotAuthorizedUser(getPrincipal(), PermissionType.SYNC_SUBSCRIPTIONS)) { + if (commonUtilsService.isNotAuthorizedUser( + commonUtilsService.getPrincipal(), PermissionType.SYNC_SUBSCRIPTIONS)) { return null; } @@ -440,7 +441,7 @@ public List getSyncBackAcls( int tenantId = commonUtilsService.getTenantId(userName); if (commonUtilsService.isNotAuthorizedUser( - getPrincipal(), PermissionType.SYNC_BACK_SUBSCRIPTIONS)) { + commonUtilsService.getPrincipal(), PermissionType.SYNC_BACK_SUBSCRIPTIONS)) { return null; } @@ -698,7 +699,7 @@ private boolean verifyIfTopicExists( private List tenantFiltering(List teamList) { if (!commonUtilsService.isNotAuthorizedUser( - getPrincipal(), + commonUtilsService.getPrincipal(), Set.of( PermissionType.SYNC_BACK_SUBSCRIPTIONS, PermissionType.SYNC_TOPICS, @@ -726,7 +727,7 @@ private int counterIncrement() { } private String getUserName() { - return mailService.getUserName(getPrincipal()); + return mailService.getUserName(commonUtilsService.getPrincipal()); } public Env getEnvDetails(String envId, int tenantId) { @@ -737,8 +738,4 @@ public Env getEnvDetails(String envId, int tenantId) { .findFirst(); return envFound.orElse(null); } - - private Object getPrincipal() { - return SecurityContextHolder.getContext().getAuthentication().getPrincipal(); - } } diff --git a/core/src/main/java/io/aiven/klaw/service/AnalyticsControllerService.java b/core/src/main/java/io/aiven/klaw/service/AnalyticsControllerService.java index 8015eed25..82870fe1c 100644 --- a/core/src/main/java/io/aiven/klaw/service/AnalyticsControllerService.java +++ b/core/src/main/java/io/aiven/klaw/service/AnalyticsControllerService.java @@ -36,7 +36,6 @@ import org.apache.poi.xssf.usermodel.XSSFSheet; import org.apache.poi.xssf.usermodel.XSSFWorkbook; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.stereotype.Service; @Service @@ -343,7 +342,8 @@ public List getTeamsOverview(String forTeam, int numberOfDays) { final String currentUserName = getCurrentUserName(); Integer userTeamId = commonUtilsService.getTeamId(currentUserName); - if (commonUtilsService.isNotAuthorizedUser(getPrincipal(), PermissionType.ALL_TEAMS_REPORTS)) { + if (commonUtilsService.isNotAuthorizedUser( + commonUtilsService.getPrincipal(), PermissionType.ALL_TEAMS_REPORTS)) { int tenantId = commonUtilsService.getTenantId(currentUserName); teamOverview.setProducerAclsPerTeamsOverview( @@ -593,7 +593,8 @@ private Map> getTopicNames(int tenantId) { final Set allowedEnvIdSet = commonUtilsService.getEnvsFromUserId(getCurrentUserName()); Map> topicsPerEnv = new HashMap<>(); - if (commonUtilsService.isNotAuthorizedUser(getPrincipal(), PermissionType.ALL_TEAMS_REPORTS)) { + if (commonUtilsService.isNotAuthorizedUser( + commonUtilsService.getPrincipal(), PermissionType.ALL_TEAMS_REPORTS)) { // normal user Integer userTeamId = commonUtilsService.getTeamId(getCurrentUserName()); List topics = @@ -630,7 +631,8 @@ private Map> getConsumerGroups(int tenantId) { final Set allowedEnvIdSet = commonUtilsService.getEnvsFromUserId(getCurrentUserName()); Map> aclsPerEnv = new HashMap<>(); - if (commonUtilsService.isNotAuthorizedUser(getPrincipal(), PermissionType.ALL_TEAMS_REPORTS)) { + if (commonUtilsService.isNotAuthorizedUser( + commonUtilsService.getPrincipal(), PermissionType.ALL_TEAMS_REPORTS)) { // normal user Integer userTeamId = commonUtilsService.getTeamId(getCurrentUserName()); List acls = @@ -665,8 +667,4 @@ private Map> getConsumerGroups(int tenantId) { return aclsPerEnv; } - - private Object getPrincipal() { - return SecurityContextHolder.getContext().getAuthentication().getPrincipal(); - } } diff --git a/core/src/main/java/io/aiven/klaw/service/BaseOverviewService.java b/core/src/main/java/io/aiven/klaw/service/BaseOverviewService.java index 2ef97ff05..f2367ce4b 100644 --- a/core/src/main/java/io/aiven/klaw/service/BaseOverviewService.java +++ b/core/src/main/java/io/aiven/klaw/service/BaseOverviewService.java @@ -31,7 +31,6 @@ import java.util.stream.Collectors; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.stereotype.Service; @Slf4j @@ -333,11 +332,7 @@ protected void generatePromotionDetails( } protected String getUserName() { - return mailService.getUserName(getPrincipal()); - } - - protected Object getPrincipal() { - return SecurityContextHolder.getContext().getAuthentication().getPrincipal(); + return mailService.getUserName(commonUtilsService.getPrincipal()); } protected Env getEnvDetails(String envId, int tenantId) { diff --git a/core/src/main/java/io/aiven/klaw/service/EnvsClustersTenantsControllerService.java b/core/src/main/java/io/aiven/klaw/service/EnvsClustersTenantsControllerService.java index 0f3e94673..ccf07e74d 100644 --- a/core/src/main/java/io/aiven/klaw/service/EnvsClustersTenantsControllerService.java +++ b/core/src/main/java/io/aiven/klaw/service/EnvsClustersTenantsControllerService.java @@ -107,7 +107,7 @@ public void setServices(ClusterApiService clusterApiService, MailUtils mailServi } private boolean isAuthorizedFor(PermissionType type) { - return !commonUtilsService.isNotAuthorizedUser(getPrincipal(), type); + return !commonUtilsService.isNotAuthorizedUser(commonUtilsService.getPrincipal(), type); } public synchronized EnvModelResponse getEnvDetails(String envSelected, String clusterType) { @@ -392,7 +392,8 @@ public List getKafkaConnectEnvs() { int tenantId = getUserDetails(userName).getTenantId(); List listEnvs = manageDatabase.getKafkaConnectEnvList(tenantId); - if (commonUtilsService.isNotAuthorizedUser(getPrincipal(), ADD_EDIT_DELETE_ENVS)) { + if (commonUtilsService.isNotAuthorizedUser( + commonUtilsService.getPrincipal(), ADD_EDIT_DELETE_ENVS)) { final Set allowedEnvIdSet = commonUtilsService.getEnvsFromUserId(userName); listEnvs = listEnvs.stream().filter(env -> allowedEnvIdSet.contains(env.getId())).collect(toList()); @@ -730,7 +731,7 @@ private void associateWithKafkaEnv(EnvTag envTag, String envId, String envName, } private String getUserName() { - return mailService.getUserName(getPrincipal()); + return mailService.getUserName(commonUtilsService.getPrincipal()); } private Boolean isUserSuperAdmin() { @@ -858,10 +859,6 @@ public KwTenantModel getMyTenantInfo() { return kwTenantModel; } - private Object getPrincipal() { - return SecurityContextHolder.getContext().getAuthentication().getPrincipal(); - } - public ApiResponse deleteTenant() throws KlawException { if (!isAuthorizedFor(UPDATE_DELETE_MY_TENANT)) { return ApiResponse.NOT_AUTHORIZED; @@ -907,7 +904,7 @@ public ApiResponse deleteTenant() throws KlawException { public ApiResponse updateTenant(KwTenantModel kwTenantModel) throws KlawException { if (commonUtilsService.isNotAuthorizedUser( - getPrincipal(), PermissionType.UPDATE_DELETE_MY_TENANT)) { + commonUtilsService.getPrincipal(), PermissionType.UPDATE_DELETE_MY_TENANT)) { return ApiResponse.NOT_AUTHORIZED; } diff --git a/core/src/main/java/io/aiven/klaw/service/KafkaConnectControllerService.java b/core/src/main/java/io/aiven/klaw/service/KafkaConnectControllerService.java index 69a5e3efc..a2441568d 100644 --- a/core/src/main/java/io/aiven/klaw/service/KafkaConnectControllerService.java +++ b/core/src/main/java/io/aiven/klaw/service/KafkaConnectControllerService.java @@ -72,7 +72,6 @@ import org.jasypt.util.text.BasicTextEncryptor; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; -import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.stereotype.Service; import org.springframework.web.client.HttpClientErrorException; import org.springframework.web.client.HttpServerErrorException; @@ -111,7 +110,7 @@ public ApiResponse createConnectorRequest(KafkaConnectorRequestModel connectorRe String userName = getUserName(); if (commonUtilsService.isNotAuthorizedUser( - getPrincipal(), PermissionType.REQUEST_CREATE_CONNECTORS)) { + commonUtilsService.getPrincipal(), PermissionType.REQUEST_CREATE_CONNECTORS)) { return ApiResponse.NOT_AUTHORIZED; } @@ -504,7 +503,7 @@ public ApiResponse restartConnector(KafkaConnectorRestartModel kafkaConnectorRes int tenantId = commonUtilsService.getTenantId(getUserName()); try { if (commonUtilsService.isNotAuthorizedUser( - getPrincipal(), PermissionType.MANAGE_CONNECTORS)) { + commonUtilsService.getPrincipal(), PermissionType.MANAGE_CONNECTORS)) { return ApiResponse.NOT_AUTHORIZED; } return clusterApiService.restartConnector(kafkaConnectorRestartModel, tenantId); @@ -528,7 +527,7 @@ public List getCreatedConnectorRequests( // get requests relevant to your teams or all teams if (commonUtilsService.isNotAuthorizedUser( - getPrincipal(), PermissionType.APPROVE_ALL_REQUESTS_TEAMS)) + commonUtilsService.getPrincipal(), PermissionType.APPROVE_ALL_REQUESTS_TEAMS)) createdTopicReqList = manageDatabase .getHandleDbRequests() @@ -637,7 +636,8 @@ public ApiResponse approveConnectorRequests(String connectorId) String userDetails = getUserName(); int tenantId = commonUtilsService.getTenantId(getUserName()); - if (commonUtilsService.isNotAuthorizedUser(getPrincipal(), PermissionType.APPROVE_CONNECTORS)) { + if (commonUtilsService.isNotAuthorizedUser( + commonUtilsService.getPrincipal(), PermissionType.APPROVE_CONNECTORS)) { return ApiResponse.NOT_AUTHORIZED; } @@ -788,7 +788,8 @@ public ApiResponse declineConnectorRequests(String connectorId, String reasonFor throws KlawException { log.info("declineConnectorRequests {} {}", connectorId, reasonForDecline); String userDetails = getUserName(); - if (commonUtilsService.isNotAuthorizedUser(getPrincipal(), PermissionType.APPROVE_CONNECTORS)) { + if (commonUtilsService.isNotAuthorizedUser( + commonUtilsService.getPrincipal(), PermissionType.APPROVE_CONNECTORS)) { return ApiResponse.NOT_AUTHORIZED; } @@ -837,7 +838,7 @@ public ApiResponse createConnectorDeleteRequest(String connectorName, String env String userDetails = getUserName(); if (commonUtilsService.isNotAuthorizedUser( - getPrincipal(), PermissionType.REQUEST_DELETE_CONNECTORS)) { + commonUtilsService.getPrincipal(), PermissionType.REQUEST_DELETE_CONNECTORS)) { return ApiResponse.NOT_AUTHORIZED; } @@ -1553,11 +1554,7 @@ private List getFilteredConnectorsForTenant( } private String getUserName() { - return mailService.getUserName(getPrincipal()); - } - - private Object getPrincipal() { - return SecurityContextHolder.getContext().getAuthentication().getPrincipal(); + return mailService.getUserName(commonUtilsService.getPrincipal()); } public Env getKafkaConnectEnvDetails(String envId) { diff --git a/core/src/main/java/io/aiven/klaw/service/KafkaConnectSyncControllerService.java b/core/src/main/java/io/aiven/klaw/service/KafkaConnectSyncControllerService.java index f10013d26..b49edc159 100644 --- a/core/src/main/java/io/aiven/klaw/service/KafkaConnectSyncControllerService.java +++ b/core/src/main/java/io/aiven/klaw/service/KafkaConnectSyncControllerService.java @@ -34,7 +34,6 @@ import java.util.stream.Collectors; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.stereotype.Service; @Service @@ -81,7 +80,8 @@ public ApiResponse updateSyncConnectors(List updatedSyncTo log.info("updateSyncConnectors {}", updatedSyncTopics); String userName = getUserName(); - if (commonUtilsService.isNotAuthorizedUser(getPrincipal(), PermissionType.SYNC_CONNECTORS)) { + if (commonUtilsService.isNotAuthorizedUser( + commonUtilsService.getPrincipal(), PermissionType.SYNC_CONNECTORS)) { return ApiResponse.NOT_AUTHORIZED; } @@ -477,7 +477,8 @@ private List getSyncConnectorsList( } private List tenantFilterTeams(List teamList) { - if (!commonUtilsService.isNotAuthorizedUser(getPrincipal(), PermissionType.SYNC_CONNECTORS)) { + if (!commonUtilsService.isNotAuthorizedUser( + commonUtilsService.getPrincipal(), PermissionType.SYNC_CONNECTORS)) { // tenant filtering int tenantId = commonUtilsService.getTenantId(getUserName()); List teams = manageDatabase.getHandleDbRequests().getAllTeams(tenantId); @@ -492,11 +493,7 @@ private List tenantFilterTeams(List teamList) { } private String getUserName() { - return mailService.getUserName(getPrincipal()); - } - - private Object getPrincipal() { - return SecurityContextHolder.getContext().getAuthentication().getPrincipal(); + return mailService.getUserName(commonUtilsService.getPrincipal()); } public Env getKafkaConnectorEnvDetails(String envId) { diff --git a/core/src/main/java/io/aiven/klaw/service/MetricsControllerService.java b/core/src/main/java/io/aiven/klaw/service/MetricsControllerService.java index 04da96233..af6f6950c 100644 --- a/core/src/main/java/io/aiven/klaw/service/MetricsControllerService.java +++ b/core/src/main/java/io/aiven/klaw/service/MetricsControllerService.java @@ -11,7 +11,6 @@ import org.springframework.beans.factory.annotation.Value; import org.springframework.scheduling.annotation.EnableScheduling; import org.springframework.scheduling.annotation.Scheduled; -import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.stereotype.Service; @Service @@ -31,7 +30,7 @@ public class MetricsControllerService { @Autowired private CommonUtilsService commonUtilsService; private String getUserName() { - return mailService.getUserName(getPrincipal()); + return mailService.getUserName(commonUtilsService.getPrincipal()); } // default 1 min @@ -109,8 +108,4 @@ private ChartsJsOverview getBrokerTopMetricsOverview() { "Messages", commonUtilsService.getTenantId(getUserName())); } - - private Object getPrincipal() { - return SecurityContextHolder.getContext().getAuthentication().getPrincipal(); - } } diff --git a/core/src/main/java/io/aiven/klaw/service/OperationalRequestsService.java b/core/src/main/java/io/aiven/klaw/service/OperationalRequestsService.java index e29e203bb..0efe08c58 100644 --- a/core/src/main/java/io/aiven/klaw/service/OperationalRequestsService.java +++ b/core/src/main/java/io/aiven/klaw/service/OperationalRequestsService.java @@ -42,7 +42,6 @@ import java.util.stream.Collectors; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.math.NumberUtils; -import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.stereotype.Service; @Service @@ -264,7 +263,7 @@ public List getOperationalRequestsForApprover( int tenantId = commonUtilsService.getTenantId(userName); // get requests relevant to your teams or all teams if (commonUtilsService.isNotAuthorizedUser( - getPrincipal(), PermissionType.APPROVE_ALL_REQUESTS_TEAMS)) { + commonUtilsService.getPrincipal(), PermissionType.APPROVE_ALL_REQUESTS_TEAMS)) { operationalRequestList = manageDatabase .getHandleDbRequests() @@ -400,7 +399,7 @@ public ApiResponse approveOperationalRequests(String reqId) { final String userName = getUserName(); int tenantId = commonUtilsService.getTenantId(userName); if (commonUtilsService.isNotAuthorizedUser( - getPrincipal(), PermissionType.APPROVE_OPERATIONAL_CHANGES)) { + commonUtilsService.getPrincipal(), PermissionType.APPROVE_OPERATIONAL_CHANGES)) { return ApiResponse.NOT_AUTHORIZED; } @@ -477,7 +476,7 @@ public ApiResponse approveOperationalRequests(String reqId) { } private void checkIsAuthorized(PermissionType permission) throws KlawNotAuthorizedException { - if (commonUtilsService.isNotAuthorizedUser(getPrincipal(), permission)) { + if (commonUtilsService.isNotAuthorizedUser(commonUtilsService.getPrincipal(), permission)) { throw new KlawNotAuthorizedException(TOPICS_ERR_101); } } @@ -486,10 +485,6 @@ private String getUserName() { return mailService.getCurrentUserName(); } - private Object getPrincipal() { - return SecurityContextHolder.getContext().getAuthentication().getPrincipal(); - } - public EnvIdInfo validateOffsetRequestDetails( String envId, String topicName, String consumerGroup) { log.debug("validateOffsetRequestDetails {} {} {}", envId, topicName, consumerGroup); @@ -520,7 +515,7 @@ public ApiResponse deleteOperationalRequest(String operationalRequestId) throws log.info("deleteOperationalRequest {}", operationalRequestId); if (commonUtilsService.isNotAuthorizedUser( - getPrincipal(), PermissionType.REQUEST_CREATE_OPERATIONAL_CHANGES)) { + commonUtilsService.getPrincipal(), PermissionType.REQUEST_CREATE_OPERATIONAL_CHANGES)) { return ApiResponse.NOT_AUTHORIZED; } String userName = getUserName(); @@ -546,7 +541,7 @@ public ApiResponse declineOperationalRequest(String reqId, String reasonForDecli throws KlawException { log.debug("declineOperationalRequest {} {}", reqId, reasonForDecline); if (commonUtilsService.isNotAuthorizedUser( - getPrincipal(), PermissionType.APPROVE_OPERATIONAL_CHANGES)) { + commonUtilsService.getPrincipal(), PermissionType.APPROVE_OPERATIONAL_CHANGES)) { return ApiResponse.NOT_AUTHORIZED; } diff --git a/core/src/main/java/io/aiven/klaw/service/RequestStatisticsService.java b/core/src/main/java/io/aiven/klaw/service/RequestStatisticsService.java index 791992308..097a04f4e 100644 --- a/core/src/main/java/io/aiven/klaw/service/RequestStatisticsService.java +++ b/core/src/main/java/io/aiven/klaw/service/RequestStatisticsService.java @@ -14,7 +14,6 @@ import java.util.Set; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.stereotype.Service; @Service @@ -118,10 +117,6 @@ private void updateRequestsCountOverview( } private String getUserName() { - return mailService.getUserName(getPrincipal()); - } - - private Object getPrincipal() { - return SecurityContextHolder.getContext().getAuthentication().getPrincipal(); + return mailService.getUserName(commonUtilsService.getPrincipal()); } } diff --git a/core/src/main/java/io/aiven/klaw/service/RolesPermissionsControllerService.java b/core/src/main/java/io/aiven/klaw/service/RolesPermissionsControllerService.java index d0e550a86..e7b660ff6 100644 --- a/core/src/main/java/io/aiven/klaw/service/RolesPermissionsControllerService.java +++ b/core/src/main/java/io/aiven/klaw/service/RolesPermissionsControllerService.java @@ -13,7 +13,6 @@ import java.util.*; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Value; -import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.stereotype.Service; @Slf4j @@ -37,14 +36,14 @@ public RolesPermissionsControllerService( } private String getUserName() { - return mailService.getUserName(getPrincipal()); + return mailService.getUserName(commonUtilsService.getPrincipal()); } public List getRoles() { int tenantId = commonUtilsService.getTenantId(getUserName()); try { if (commonUtilsService.isNotAuthorizedUser( - getPrincipal(), PermissionType.FULL_ACCESS_USERS_TEAMS_ROLES)) + commonUtilsService.getPrincipal(), PermissionType.FULL_ACCESS_USERS_TEAMS_ROLES)) return Arrays.asList( manageDatabase.getKwPropertyValue("klaw.adduser.roles", tenantId).split(",")); else { @@ -68,7 +67,7 @@ public Map>> getPermissions(boolean isExternal if (isExternalCall && commonUtilsService.isNotAuthorizedUser( - getPrincipal(), PermissionType.UPDATE_PERMISSIONS)) { + commonUtilsService.getPrincipal(), PermissionType.UPDATE_PERMISSIONS)) { return null; } @@ -110,7 +109,8 @@ public Map getPermissionDescriptions() { public ApiResponse updatePermissions(KwRolesPermissionsModel[] permissionsSet) throws KlawException { - if (commonUtilsService.isNotAuthorizedUser(getPrincipal(), PermissionType.UPDATE_PERMISSIONS)) { + if (commonUtilsService.isNotAuthorizedUser( + commonUtilsService.getPrincipal(), PermissionType.UPDATE_PERMISSIONS)) { return ApiResponse.NOT_AUTHORIZED; } @@ -166,7 +166,7 @@ public ApiResponse updatePermissions(KwRolesPermissionsModel[] permissionsSet) public ApiResponse deleteRole(String roleId) throws KlawException { if (commonUtilsService.isNotAuthorizedUser( - getPrincipal(), PermissionType.ADD_EDIT_DELETE_ROLES)) { + commonUtilsService.getPrincipal(), PermissionType.ADD_EDIT_DELETE_ROLES)) { return ApiResponse.NOT_AUTHORIZED; } @@ -191,7 +191,7 @@ public ApiResponse deleteRole(String roleId) throws KlawException { public ApiResponse addRoleId(String roleId) throws KlawException { if (commonUtilsService.isNotAuthorizedUser( - getPrincipal(), PermissionType.ADD_EDIT_DELETE_ROLES)) { + commonUtilsService.getPrincipal(), PermissionType.ADD_EDIT_DELETE_ROLES)) { return ApiResponse.NOT_AUTHORIZED; } @@ -216,10 +216,6 @@ public ApiResponse addRoleId(String roleId) throws KlawException { } } - private Object getPrincipal() { - return SecurityContextHolder.getContext().getAuthentication().getPrincipal(); - } - protected Set getApproverRoles(String requestType, int tenantId) { Map>> existingPermissions = getPermissions(false); Set approverRoles = new HashSet<>(); diff --git a/core/src/main/java/io/aiven/klaw/service/SchemaRegistryControllerService.java b/core/src/main/java/io/aiven/klaw/service/SchemaRegistryControllerService.java index 1577e69cd..779cf3c63 100644 --- a/core/src/main/java/io/aiven/klaw/service/SchemaRegistryControllerService.java +++ b/core/src/main/java/io/aiven/klaw/service/SchemaRegistryControllerService.java @@ -45,7 +45,6 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.http.ResponseEntity; -import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.stereotype.Service; @Service @@ -102,7 +101,8 @@ public List getSchemaRequests( search, isApproval && !commonUtilsService.isNotAuthorizedUser( - getPrincipal(), PermissionType.APPROVE_ALL_REQUESTS_TEAMS), + commonUtilsService.getPrincipal(), + PermissionType.APPROVE_ALL_REQUESTS_TEAMS), isMyRequest); // tenant filtering @@ -205,7 +205,7 @@ public ApiResponse deleteSchemaRequests(String avroSchemaId) throws KlawExceptio log.info("deleteSchemaRequests {}", avroSchemaId); if (commonUtilsService.isNotAuthorizedUser( - getPrincipal(), PermissionType.REQUEST_DELETE_SCHEMAS)) { + commonUtilsService.getPrincipal(), PermissionType.REQUEST_DELETE_SCHEMAS)) { return ApiResponse.NOT_AUTHORIZED; } String userName = getUserName(); @@ -231,7 +231,8 @@ public ApiResponse execSchemaRequests(String avroSchemaId) throws KlawException log.info("execSchemaRequests {}", avroSchemaId); String userDetails = getUserName(); int tenantId = commonUtilsService.getTenantId(getUserName()); - if (commonUtilsService.isNotAuthorizedUser(getPrincipal(), PermissionType.APPROVE_SCHEMAS)) { + if (commonUtilsService.isNotAuthorizedUser( + commonUtilsService.getPrincipal(), PermissionType.APPROVE_SCHEMAS)) { return ApiResponse.NOT_AUTHORIZED; } @@ -415,7 +416,8 @@ public ApiResponse execSchemaRequestsDecline(String avroSchemaId, String reasonF throws KlawException { log.info("execSchemaRequestsDecline {}", avroSchemaId); String userDetails = getUserName(); - if (commonUtilsService.isNotAuthorizedUser(getPrincipal(), PermissionType.APPROVE_SCHEMAS)) { + if (commonUtilsService.isNotAuthorizedUser( + commonUtilsService.getPrincipal(), PermissionType.APPROVE_SCHEMAS)) { return ApiResponse.NOT_AUTHORIZED; } int tenantId = commonUtilsService.getTenantId(getUserName()); @@ -452,7 +454,7 @@ public ApiResponse promoteSchema(SchemaPromotion schemaPromotion) throws Excepti String userDetails = getUserName(); if (commonUtilsService.isNotAuthorizedUser( - getPrincipal(), PermissionType.REQUEST_CREATE_SCHEMAS)) { + commonUtilsService.getPrincipal(), PermissionType.REQUEST_CREATE_SCHEMAS)) { return ApiResponse.NOT_AUTHORIZED; } @@ -542,7 +544,7 @@ public ApiResponse uploadSchema( String userName = getUserName(); if (commonUtilsService.isNotAuthorizedUser( - getPrincipal(), PermissionType.REQUEST_CREATE_SCHEMAS)) { + commonUtilsService.getPrincipal(), PermissionType.REQUEST_CREATE_SCHEMAS)) { return ApiResponse.NOT_AUTHORIZED; } schemaRequest.setRequestor(userName); @@ -732,10 +734,6 @@ private String prettyPrintUglyJsonString(String json) { } private String getUserName() { - return mailService.getUserName(getPrincipal()); - } - - private Object getPrincipal() { - return SecurityContextHolder.getContext().getAuthentication().getPrincipal(); + return mailService.getUserName(commonUtilsService.getPrincipal()); } } diff --git a/core/src/main/java/io/aiven/klaw/service/SchemaRegistrySyncControllerService.java b/core/src/main/java/io/aiven/klaw/service/SchemaRegistrySyncControllerService.java index 5175dc18c..6b96944cb 100644 --- a/core/src/main/java/io/aiven/klaw/service/SchemaRegistrySyncControllerService.java +++ b/core/src/main/java/io/aiven/klaw/service/SchemaRegistrySyncControllerService.java @@ -42,7 +42,6 @@ import org.apache.commons.lang3.StringUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.ResponseEntity; -import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.stereotype.Service; @Service @@ -106,7 +105,8 @@ public SyncSchemasList getSchemasOfEnvironmentFromMetadataDb( Integer teamId) { SyncSchemasList syncSchemasList = new SyncSchemasList(); List schemaInfoList; - if (commonUtilsService.isNotAuthorizedUser(getPrincipal(), PermissionType.SYNC_BACK_SCHEMAS)) { + if (commonUtilsService.isNotAuthorizedUser( + commonUtilsService.getPrincipal(), PermissionType.SYNC_BACK_SCHEMAS)) { return syncSchemasList; } @@ -229,7 +229,8 @@ private SyncSchemasList getSchemaOfEnvironmentFromCluster( boolean showAllTopics) throws KlawException { SyncSchemasList syncSchemasList = new SyncSchemasList(); - if (commonUtilsService.isNotAuthorizedUser(getPrincipal(), PermissionType.SYNC_SCHEMAS)) { + if (commonUtilsService.isNotAuthorizedUser( + commonUtilsService.getPrincipal(), PermissionType.SYNC_SCHEMAS)) { return syncSchemasList; } @@ -440,7 +441,8 @@ public ApiResponse updateSyncSchemas(SyncSchemaUpdates syncSchemaUpdates) throws private ApiResponse updateSyncSchemasToCluster(SyncSchemaUpdates syncSchemaUpdates) throws KlawException { - if (commonUtilsService.isNotAuthorizedUser(getPrincipal(), PermissionType.SYNC_BACK_SCHEMAS)) { + if (commonUtilsService.isNotAuthorizedUser( + commonUtilsService.getPrincipal(), PermissionType.SYNC_BACK_SCHEMAS)) { return ApiResponse.NOT_AUTHORIZED; } List logArray = new ArrayList<>(); @@ -546,7 +548,8 @@ private ApiResponse updateSyncSchemasToCluster(SyncSchemaUpdates syncSchemaUpdat private ApiResponse updateSyncSchemasToMetadata(SyncSchemaUpdates syncSchemaUpdates) throws Exception { - if (commonUtilsService.isNotAuthorizedUser(getPrincipal(), PermissionType.SYNC_SCHEMAS)) { + if (commonUtilsService.isNotAuthorizedUser( + commonUtilsService.getPrincipal(), PermissionType.SYNC_SCHEMAS)) { return ApiResponse.NOT_AUTHORIZED; } String userDetails = getUserName(); @@ -705,11 +708,7 @@ private Integer getTeamIdFromDb(int tenantId, SchemaSubjectInfoResponse mp) { } private String getUserName() { - return mailService.getUserName(getPrincipal()); - } - - private Object getPrincipal() { - return SecurityContextHolder.getContext().getAuthentication().getPrincipal(); + return mailService.getUserName(commonUtilsService.getPrincipal()); } public ApiResponse resetCacheClusterApi(SchemaResetCache schemaResetCache) throws KlawException { diff --git a/core/src/main/java/io/aiven/klaw/service/ServerConfigService.java b/core/src/main/java/io/aiven/klaw/service/ServerConfigService.java index 3da6ac2af..f594c5ecd 100644 --- a/core/src/main/java/io/aiven/klaw/service/ServerConfigService.java +++ b/core/src/main/java/io/aiven/klaw/service/ServerConfigService.java @@ -50,7 +50,6 @@ import org.springframework.core.env.EnumerablePropertySource; import org.springframework.core.env.Environment; import org.springframework.core.env.PropertySource; -import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.stereotype.Service; @Service @@ -125,7 +124,7 @@ public void getAllProperties() { public Collection getAllProps() { if (commonUtilsService.isNotAuthorizedUser( - getPrincipal(), PermissionType.UPDATE_SERVERCONFIG)) { + commonUtilsService.getPrincipal(), PermissionType.UPDATE_SERVERCONFIG)) { return new ArrayList<>(); } return key2Props.values(); @@ -136,7 +135,7 @@ public List getAllEditableProps() { KwPropertiesResponse propertiesResponse = new KwPropertiesResponse(); if (commonUtilsService.isNotAuthorizedUser( - getPrincipal(), PermissionType.UPDATE_SERVERCONFIG)) { + commonUtilsService.getPrincipal(), PermissionType.UPDATE_SERVERCONFIG)) { propertiesResponse.setResult(ApiResultStatus.NOT_AUTHORIZED.value); listMap.add(propertiesResponse); return listMap; @@ -194,7 +193,7 @@ public ApiResponse updateKwCustomProperty(KwPropertiesModel kwPropertiesModel) String kwVal = kwPropertiesModel.getKwValue().trim(); if (commonUtilsService.isNotAuthorizedUser( - getPrincipal(), PermissionType.UPDATE_SERVERCONFIG)) { + commonUtilsService.getPrincipal(), PermissionType.UPDATE_SERVERCONFIG)) { return ApiResponse.NOT_AUTHORIZED; } @@ -552,10 +551,6 @@ public ConnectivityStatus testClusterApiConnection(String clusterApiUrl) throws return connectivityStatus; } - private Object getPrincipal() { - return SecurityContextHolder.getContext().getAuthentication().getPrincipal(); - } - private Integer getTenantIdFromName(String tenantName) { return manageDatabase.getTenantMap().entrySet().stream() .filter(obj -> Objects.equals(obj.getValue(), tenantName)) @@ -565,6 +560,6 @@ private Integer getTenantIdFromName(String tenantName) { } private String getUserName() { - return mailService.getUserName(getPrincipal()); + return mailService.getUserName(commonUtilsService.getPrincipal()); } } diff --git a/core/src/main/java/io/aiven/klaw/service/TopicControllerService.java b/core/src/main/java/io/aiven/klaw/service/TopicControllerService.java index eaaa01550..caabfffdc 100644 --- a/core/src/main/java/io/aiven/klaw/service/TopicControllerService.java +++ b/core/src/main/java/io/aiven/klaw/service/TopicControllerService.java @@ -82,7 +82,6 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.dao.DataIntegrityViolationException; import org.springframework.http.ResponseEntity; -import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.stereotype.Service; @Service @@ -525,7 +524,7 @@ public List getTopicRequestsForApprover( int tenantId = commonUtilsService.getTenantId(userName); // get requests relevant to your teams or all teams if (commonUtilsService.isNotAuthorizedUser( - getPrincipal(), PermissionType.APPROVE_ALL_REQUESTS_TEAMS)) { + commonUtilsService.getPrincipal(), PermissionType.APPROVE_ALL_REQUESTS_TEAMS)) { createdTopicReqList = manageDatabase .getHandleDbRequests() @@ -717,10 +716,10 @@ public ApiResponse approveTopicRequests(String topicId) throws KlawException { if (topicRequest.getRequestOperationType().equals(RequestOperationType.CREATE.value) && Boolean.parseBoolean(isOptionalExtraPermissionForPromote) && commonUtilsService.isNotAuthorizedUser( - getPrincipal(), PermissionType.APPROVE_TOPICS_CREATE)) { + commonUtilsService.getPrincipal(), PermissionType.APPROVE_TOPICS_CREATE)) { return ApiResponse.notOk(ApiResultStatus.NOT_AUTHORIZED.value + ". " + TOPICS_ERR_116); } else if (commonUtilsService.isNotAuthorizedUser( - getPrincipal(), PermissionType.APPROVE_TOPICS)) { + commonUtilsService.getPrincipal(), PermissionType.APPROVE_TOPICS)) { return ApiResponse.NOT_AUTHORIZED; } @@ -882,7 +881,8 @@ private ApiResponse validateTopicRequest(TopicRequest topicRequest, String userN public ApiResponse declineTopicRequests(String topicId, String reasonForDecline) throws KlawException { log.info("declineTopicRequests {} {}", topicId, reasonForDecline); - if (commonUtilsService.isNotAuthorizedUser(getPrincipal(), PermissionType.APPROVE_TOPICS)) { + if (commonUtilsService.isNotAuthorizedUser( + commonUtilsService.getPrincipal(), PermissionType.APPROVE_TOPICS)) { return ApiResponse.NOT_AUTHORIZED; } @@ -1301,11 +1301,7 @@ private int counterIncrement() { } public String getUserName() { - return mailService.getUserName(getPrincipal()); - } - - public Object getPrincipal() { - return SecurityContextHolder.getContext().getAuthentication().getPrincipal(); + return mailService.getUserName(commonUtilsService.getPrincipal()); } public Env getEnvDetails(String envId) { diff --git a/core/src/main/java/io/aiven/klaw/service/TopicSyncControllerService.java b/core/src/main/java/io/aiven/klaw/service/TopicSyncControllerService.java index 1a75b2a66..1a88dc7e4 100644 --- a/core/src/main/java/io/aiven/klaw/service/TopicSyncControllerService.java +++ b/core/src/main/java/io/aiven/klaw/service/TopicSyncControllerService.java @@ -68,7 +68,6 @@ import org.springframework.http.ResponseEntity; import org.springframework.scheduling.annotation.EnableScheduling; import org.springframework.scheduling.annotation.Scheduled; -import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.stereotype.Service; @EnableScheduling @@ -287,7 +286,8 @@ public SyncTopicsList getSyncTopics( log.info("getSyncTopics {} {} {}", env, pageNo, topicNameSearch); if (!"-1".equals(pageNo)) { // ignore check for scheduler - if (commonUtilsService.isNotAuthorizedUser(getPrincipal(), PermissionType.SYNC_TOPICS)) { + if (commonUtilsService.isNotAuthorizedUser( + commonUtilsService.getPrincipal(), PermissionType.SYNC_TOPICS)) { return null; } } @@ -586,7 +586,7 @@ private void updateClusterDeletedTopicsList( private List tenantFilterTeams(Integer tenantId, boolean scheduledThread) { if (!scheduledThread && (!commonUtilsService.isNotAuthorizedUser( - getPrincipal(), + commonUtilsService.getPrincipal(), Set.of( PermissionType.SYNC_BACK_SUBSCRIPTIONS, PermissionType.SYNC_TOPICS, @@ -619,7 +619,8 @@ public ApiResponse updateSyncBackTopics(SyncBackTopics syncBackTopics) { "Target Environment " + getEnvDetails(syncBackTopics.getTargetEnv(), tenantId).getName()); logArray.add("Type of Sync " + syncBackTopics.getTypeOfSync()); - if (commonUtilsService.isNotAuthorizedUser(getPrincipal(), PermissionType.SYNC_BACK_TOPICS)) { + if (commonUtilsService.isNotAuthorizedUser( + commonUtilsService.getPrincipal(), PermissionType.SYNC_BACK_TOPICS)) { return ApiResponse.NOT_AUTHORIZED; } @@ -914,7 +915,8 @@ public ApiResponse updateSyncTopicsBulk(SyncTopicsBulk syncTopicsBulk) throws Kl logArray.add("Assigned to Team " + syncTopicsBulk.getSelectedTeam()); logArray.add("Type of Sync " + syncTopicsBulk.getTypeOfSync()); - if (commonUtilsService.isNotAuthorizedUser(getPrincipal(), PermissionType.SYNC_TOPICS)) { + if (commonUtilsService.isNotAuthorizedUser( + commonUtilsService.getPrincipal(), PermissionType.SYNC_TOPICS)) { return ApiResponse.NOT_AUTHORIZED; } @@ -1055,7 +1057,8 @@ public ApiResponse updateSyncTopics(List updatedSyncTopics) log.info("updateSyncTopics {}", updatedSyncTopics); String userDetails = getUserName(); - if (commonUtilsService.isNotAuthorizedUser(getPrincipal(), PermissionType.SYNC_TOPICS)) { + if (commonUtilsService.isNotAuthorizedUser( + commonUtilsService.getPrincipal(), PermissionType.SYNC_TOPICS)) { return ApiResponse.NOT_AUTHORIZED; } @@ -1244,11 +1247,7 @@ private List handleTopicDeletes( } private String getUserName() { - return mailService.getUserName(getPrincipal()); - } - - private Object getPrincipal() { - return SecurityContextHolder.getContext().getAuthentication().getPrincipal(); + return mailService.getUserName(commonUtilsService.getPrincipal()); } public Env getEnvDetails(String envId, Integer tenantId) { diff --git a/core/src/main/java/io/aiven/klaw/service/UiConfigControllerService.java b/core/src/main/java/io/aiven/klaw/service/UiConfigControllerService.java index a3c559e26..3e8bb7224 100644 --- a/core/src/main/java/io/aiven/klaw/service/UiConfigControllerService.java +++ b/core/src/main/java/io/aiven/klaw/service/UiConfigControllerService.java @@ -18,7 +18,6 @@ import org.apache.commons.lang3.StringUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; -import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.stereotype.Service; @Service @@ -45,7 +44,7 @@ public DbAuthInfo getDbAuth() { } private String getUserName() { - return mailService.getUserName(getPrincipal()); + return mailService.getUserName(commonUtilsService.getPrincipal()); } public List showActivityLog( @@ -55,7 +54,8 @@ public List showActivityLog( List origActivityList; int tenantId = commonUtilsService.getTenantId(getUserName()); - if (commonUtilsService.isNotAuthorizedUser(getPrincipal(), PermissionType.ALL_TEAMS_REPORTS)) { + if (commonUtilsService.isNotAuthorizedUser( + commonUtilsService.getPrincipal(), PermissionType.ALL_TEAMS_REPORTS)) { origActivityList = manageDatabase .getHandleDbRequests() @@ -124,8 +124,4 @@ public ApiResponse sendMessageToAdmin(String contactFormSubject, String contactF public List getRequestTypeStatuses() { return manageDatabase.getRequestStatusList(); } - - private Object getPrincipal() { - return SecurityContextHolder.getContext().getAuthentication().getPrincipal(); - } } diff --git a/core/src/main/java/io/aiven/klaw/service/UsersTeamsControllerService.java b/core/src/main/java/io/aiven/klaw/service/UsersTeamsControllerService.java index 4abc46e62..19ee7f225 100644 --- a/core/src/main/java/io/aiven/klaw/service/UsersTeamsControllerService.java +++ b/core/src/main/java/io/aiven/klaw/service/UsersTeamsControllerService.java @@ -57,7 +57,6 @@ import org.jasypt.util.text.BasicTextEncryptor; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; -import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.core.userdetails.User; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.crypto.factory.PasswordEncoderFactories; @@ -425,7 +424,7 @@ public ApiResponse deleteTeam(Integer teamId) throws KlawException { String userName = getUserName(); if (commonUtilsService.isNotAuthorizedUser( - getPrincipal(), PermissionType.ADD_EDIT_DELETE_TEAMS)) { + commonUtilsService.getPrincipal(), PermissionType.ADD_EDIT_DELETE_TEAMS)) { return ApiResponse.NOT_AUTHORIZED; } @@ -469,7 +468,7 @@ public ApiResponse deleteUser(String userIdToDelete, boolean isExternal) throws int tenantId = commonUtilsService.getTenantId(getUserName()); if (commonUtilsService.isNotAuthorizedUser( - getPrincipal(), PermissionType.ADD_EDIT_DELETE_USERS)) { + commonUtilsService.getPrincipal(), PermissionType.ADD_EDIT_DELETE_USERS)) { return ApiResponse.NOT_AUTHORIZED; } @@ -484,7 +483,7 @@ public ApiResponse deleteUser(String userIdToDelete, boolean isExternal) throws // user to be deleted has superuser permissions. // check if you (logged in user who is deleting) have superuser permissions to delete user if (commonUtilsService.isNotAuthorizedUser( - getPrincipal(), PermissionType.FULL_ACCESS_USERS_TEAMS_ROLES)) { + commonUtilsService.getPrincipal(), PermissionType.FULL_ACCESS_USERS_TEAMS_ROLES)) { return ApiResponse.notOk(TEAMS_ERR_106); } } @@ -574,7 +573,7 @@ public ApiResponse addNewUser(UserInfoModel newUser, boolean isExternal) throws if (isExternal && commonUtilsService.isNotAuthorizedUser( - getPrincipal(), PermissionType.ADD_EDIT_DELETE_USERS)) { + commonUtilsService.getPrincipal(), PermissionType.ADD_EDIT_DELETE_USERS)) { return ApiResponse.NOT_AUTHORIZED; } @@ -662,7 +661,7 @@ public ApiResponse addNewTeam(TeamModel newTeam, boolean isExternal) throws Klaw if (isExternal && commonUtilsService.isNotAuthorizedUser( - getPrincipal(), PermissionType.ADD_EDIT_DELETE_TEAMS)) { + commonUtilsService.getPrincipal(), PermissionType.ADD_EDIT_DELETE_TEAMS)) { return ApiResponse.NOT_AUTHORIZED; } @@ -707,7 +706,7 @@ public ApiResponse updateTeam(TeamModel updatedTeam) throws KlawException { log.info("updateTeam {}", updatedTeam); if (commonUtilsService.isNotAuthorizedUser( - getPrincipal(), PermissionType.ADD_EDIT_DELETE_TEAMS)) { + commonUtilsService.getPrincipal(), PermissionType.ADD_EDIT_DELETE_TEAMS)) { return ApiResponse.NOT_AUTHORIZED; } @@ -836,7 +835,7 @@ public UserInfoModelResponse getMyProfileInfo() { } private String getUserName() { - return mailService.getUserName(getPrincipal()); + return mailService.getUserName(commonUtilsService.getPrincipal()); } Map addTwoDefaultTeams( @@ -977,7 +976,7 @@ public ApiResponse registerUser(RegisterUserInfoModel newUser, boolean isExterna public List getNewUserRequests() throws KlawNotAuthorizedException { if (commonUtilsService.isNotAuthorizedUser( - getPrincipal(), PermissionType.ADD_EDIT_DELETE_USERS)) { + commonUtilsService.getPrincipal(), PermissionType.ADD_EDIT_DELETE_USERS)) { throw new KlawNotAuthorizedException("You are not authorized to view this information."); } int tenantId = commonUtilsService.getTenantId(getUserName()); @@ -1008,7 +1007,7 @@ public ApiResponse approveNewUserRequests( if (isExternal && commonUtilsService.isNotAuthorizedUser( - getPrincipal(), PermissionType.ADD_EDIT_DELETE_USERS)) { + commonUtilsService.getPrincipal(), PermissionType.ADD_EDIT_DELETE_USERS)) { return ApiResponse.NOT_AUTHORIZED; } @@ -1050,7 +1049,7 @@ public ApiResponse declineNewUserRequests(String username) throws KlawException String userDetails = getUserName(); if (commonUtilsService.isNotAuthorizedUser( - getPrincipal(), PermissionType.ADD_EDIT_DELETE_USERS)) { + commonUtilsService.getPrincipal(), PermissionType.ADD_EDIT_DELETE_USERS)) { return ApiResponse.NOT_AUTHORIZED; } @@ -1086,10 +1085,6 @@ public Env getEnvDetailsFromId(String envId) { return envFound.orElse(null); } - private Object getPrincipal() { - return SecurityContextHolder.getContext().getAuthentication().getPrincipal(); - } - private boolean userNamePatternValidation(String userName) { Matcher m1 = emailUsernamePattern.matcher(userName); Matcher m2 = defaultPattern.matcher(userName); diff --git a/core/src/main/java/io/aiven/klaw/service/UtilControllerService.java b/core/src/main/java/io/aiven/klaw/service/UtilControllerService.java index f6754bfab..95286255b 100644 --- a/core/src/main/java/io/aiven/klaw/service/UtilControllerService.java +++ b/core/src/main/java/io/aiven/klaw/service/UtilControllerService.java @@ -47,7 +47,6 @@ import org.springframework.context.ConfigurableApplicationContext; import org.springframework.core.io.ClassPathResource; import org.springframework.security.core.Authentication; -import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.web.authentication.logout.SecurityContextLogoutHandler; import org.springframework.stereotype.Service; @@ -112,7 +111,7 @@ public DashboardStats getDashboardStats() { } private String getUserName() { - return mailService.getUserName(getPrincipal()); + return mailService.getUserName(commonUtilsService.getPrincipal()); } public String getTenantNameFromUser(String userId, UserInfo userInfo) { @@ -135,11 +134,11 @@ public Map getAllRequestsToBeApproved(String requestor, int tena Map countList = new HashMap<>(); String roleToSet = ""; if (!commonUtilsService.isNotAuthorizedUser( - getPrincipal(), PermissionType.APPROVE_SUBSCRIPTIONS)) { + commonUtilsService.getPrincipal(), PermissionType.APPROVE_SUBSCRIPTIONS)) { roleToSet = APPROVER_SUBSCRIPTIONS; } if (!commonUtilsService.isNotAuthorizedUser( - getPrincipal(), PermissionType.REQUEST_CREATE_SUBSCRIPTIONS)) { + commonUtilsService.getPrincipal(), PermissionType.REQUEST_CREATE_SUBSCRIPTIONS)) { roleToSet = REQUESTOR_SUBSCRIPTIONS; } List allSchemaReqs = @@ -153,7 +152,7 @@ public Map getAllRequestsToBeApproved(String requestor, int tena null, null, !commonUtilsService.isNotAuthorizedUser( - getPrincipal(), PermissionType.APPROVE_ALL_REQUESTS_TEAMS), + commonUtilsService.getPrincipal(), PermissionType.APPROVE_ALL_REQUESTS_TEAMS), false); List allAclReqs; @@ -161,7 +160,7 @@ public Map getAllRequestsToBeApproved(String requestor, int tena List allConnectorReqs; if (commonUtilsService.isNotAuthorizedUser( - getPrincipal(), PermissionType.APPROVE_ALL_REQUESTS_TEAMS)) { + commonUtilsService.getPrincipal(), PermissionType.APPROVE_ALL_REQUESTS_TEAMS)) { allAclReqs = reqsHandle.getAllAclRequests( true, @@ -244,7 +243,7 @@ public Map getAllRequestsToBeApproved(String requestor, int tena countList.put("connectors", allConnectorReqs.size() + ""); if (commonUtilsService.isNotAuthorizedUser( - getPrincipal(), PermissionType.ADD_EDIT_DELETE_USERS)) { + commonUtilsService.getPrincipal(), PermissionType.ADD_EDIT_DELETE_USERS)) { countList.put("users", "0"); } else { countList.put("users", reqsHandle.getCountRegisterUsersInfoForTenant(tenantId) + ""); @@ -260,7 +259,7 @@ public AuthenticationInfo getAuth() { if (userName != null) { String teamName = manageDatabase.getTeamNameFromTeamId(tenantId, commonUtilsService.getTeamId(userName)); - String authority = commonUtilsService.getAuthority(getPrincipal()); + String authority = commonUtilsService.getAuthority(commonUtilsService.getPrincipal()); Map outstanding = getAllRequestsToBeApproved(userName, tenantId); String outstandingTopicReqs = outstanding.get("topics"); @@ -318,7 +317,8 @@ public AuthenticationInfo getAuth() { authenticationInfo.setKafkaconnect_clusters_count( "" + manageDatabase.getKafkaConnectEnvList(tenantId).size()); - final Set permissions = commonUtilsService.getPermissions(getPrincipal()); + final Set permissions = + commonUtilsService.getPermissions(commonUtilsService.getPrincipal()); final String canUpdatePermissions = getPermission(permissions, PermissionType.UPDATE_PERMISSIONS); final String addEditRoles = getPermission(permissions, PermissionType.ADD_EDIT_DELETE_ROLES); @@ -464,7 +464,7 @@ public AuthenticationInfo getAuth() { isOptionalExtraPermissionForTopicCreateEnabled); if (commonUtilsService.isNotAuthorizedUser( - getPrincipal(), PermissionType.APPROVE_TOPICS_CREATE)) { + commonUtilsService.getPrincipal(), PermissionType.APPROVE_TOPICS_CREATE)) { authenticationInfo.setKlawOptionalPermissionNewTopicCreation("false"); } else { authenticationInfo.setKlawOptionalPermissionNewTopicCreation("true"); @@ -550,16 +550,13 @@ public void shutdownContext() { return; } - if (!commonUtilsService.isNotAuthorizedUser(getPrincipal(), PermissionType.SHUTDOWN_KLAW)) { + if (!commonUtilsService.isNotAuthorizedUser( + commonUtilsService.getPrincipal(), PermissionType.SHUTDOWN_KLAW)) { log.info("Klaw Shutdown requested by {}", getUserName()); context.close(); } } - private Object getPrincipal() { - return SecurityContextHolder.getContext().getAuthentication().getPrincipal(); - } - public Map getBasicInfo() { Map resultBasicInfo = new HashMap<>(); resultBasicInfo.put("contextPath", kwContextPath); @@ -613,7 +610,7 @@ public ApiResponse resetCache(ResetEntityCache resetEntityCache) { // resources } else if (entityType.equals(EntityType.USERS.name()) && commonUtilsService.isNotAuthorizedUser( - getPrincipal(), PermissionType.ADD_EDIT_DELETE_USERS)) { + commonUtilsService.getPrincipal(), PermissionType.ADD_EDIT_DELETE_USERS)) { return ApiResponse.NOT_AUTHORIZED; } log.debug("Reset cache triggered on the instance {}", resetEntityCache); diff --git a/core/src/test/java/io/aiven/klaw/service/AclControllerServiceTest.java b/core/src/test/java/io/aiven/klaw/service/AclControllerServiceTest.java index 2f669da1c..f2dfc193e 100644 --- a/core/src/test/java/io/aiven/klaw/service/AclControllerServiceTest.java +++ b/core/src/test/java/io/aiven/klaw/service/AclControllerServiceTest.java @@ -68,12 +68,8 @@ import org.mockito.ArgumentCaptor; import org.mockito.Captor; import org.mockito.Mock; -import org.mockito.Mockito; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; -import org.springframework.security.core.Authentication; -import org.springframework.security.core.context.SecurityContext; -import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.test.context.junit.jupiter.SpringExtension; import org.springframework.test.util.ReflectionTestUtils; @@ -119,7 +115,8 @@ public void setUp() throws Exception { rolesPermissionsControllerService); when(manageDatabase.getHandleDbRequests()).thenReturn(handleDbRequests); when(commonUtilsService.getEnvDetails(anyString(), anyInt())).thenReturn(env); - loginMock(); + when(commonUtilsService.getPrincipal()).thenReturn(userDetails); + when(commonUtilsService.isNotAuthorizedUser(any(), any(PermissionType.class))).thenReturn(true); } private void mockKafkaFlavor() { @@ -146,14 +143,6 @@ private void mockKafkaFlavorAiven() { when(manageDatabase.getKafkaEnvList(anyInt())).thenReturn(utilMethods.getEnvLists()); } - private void loginMock() { - Authentication authentication = Mockito.mock(Authentication.class); - SecurityContext securityContext = Mockito.mock(SecurityContext.class); - when(securityContext.getAuthentication()).thenReturn(authentication); - when(authentication.getPrincipal()).thenReturn(userDetails); - SecurityContextHolder.setContext(securityContext); - } - @Test @Order(1) public void createAclProducer() throws KlawException { @@ -168,6 +157,9 @@ public void createAclProducer() throws KlawException { Env env = new Env(); env.setClusterId(1); when(commonUtilsService.getEnvDetails(anyString(), anyInt())).thenReturn(env); + when(commonUtilsService.isNotAuthorizedUser( + userDetails, PermissionType.REQUEST_CREATE_SUBSCRIPTIONS)) + .thenReturn(false); stubUserInfo(); mockKafkaFlavor(); @@ -186,6 +178,9 @@ public void createAclConsumer() throws KlawException { hashMap.put("result", ApiResultStatus.SUCCESS.value); when(commonUtilsService.getTopicsForTopicName(anyString(), anyInt())).thenReturn(topicList); when(handleDbRequests.requestForAcl(any())).thenReturn(hashMap); + when(commonUtilsService.isNotAuthorizedUser( + userDetails, PermissionType.REQUEST_CREATE_SUBSCRIPTIONS)) + .thenReturn(false); mockKafkaFlavor(); stubUserInfo(); @@ -206,6 +201,9 @@ public void createAclConsumerThrowError() { .thenThrow(new RuntimeException("Failure in creating request")); stubUserInfo(); mockKafkaFlavor(); + when(commonUtilsService.isNotAuthorizedUser( + userDetails, PermissionType.REQUEST_CREATE_SUBSCRIPTIONS)) + .thenReturn(false); KlawException thrown = Assertions.assertThrows( @@ -219,7 +217,9 @@ public void createAclNotAuthorized() throws KlawException { AclRequests aclRequestsDao = new AclRequests(); AclRequestsModel aclRequests = getAclRequestProducer(); copyProperties(aclRequests, aclRequestsDao); - when(commonUtilsService.isNotAuthorizedUser(any(), any(PermissionType.class))).thenReturn(true); + when(commonUtilsService.isNotAuthorizedUser( + userDetails, PermissionType.REQUEST_CREATE_SUBSCRIPTIONS)) + .thenReturn(true); stubUserInfo(); ApiResponse resultResp = aclControllerService.createAcl(aclRequests); @@ -233,6 +233,9 @@ public void createAclTopicNotFound() throws KlawException { AclRequestsModel aclRequests = getAclRequestProducer(); copyProperties(aclRequests, aclRequestsDao); when(handleDbRequests.getTopics(anyString(), anyInt())).thenReturn(Collections.emptyList()); + when(commonUtilsService.isNotAuthorizedUser( + userDetails, PermissionType.REQUEST_CREATE_SUBSCRIPTIONS)) + .thenReturn(false); stubUserInfo(); ApiResponse resultResp = aclControllerService.createAcl(aclRequests); @@ -249,6 +252,9 @@ public void createAclInvalidPattern() throws KlawException { List topicList = utilMethods.getTopics(); copyProperties(aclRequestsModel, aclRequestsDao); when(handleDbRequests.getTopics(anyString(), anyInt())).thenReturn(topicList); + when(commonUtilsService.isNotAuthorizedUser( + userDetails, PermissionType.REQUEST_CREATE_SUBSCRIPTIONS)) + .thenReturn(false); stubUserInfo(); mockKafkaFlavor(); @@ -270,6 +276,9 @@ public void createAclConsumerFailure() throws KlawException { when(commonUtilsService.getTopicsForTopicName(anyString(), anyInt())).thenReturn(topicList); when(handleDbRequests.validateIfConsumerGroupUsedByAnotherTeam(anyInt(), anyInt(), anyString())) .thenReturn(true); + when(commonUtilsService.isNotAuthorizedUser( + userDetails, PermissionType.REQUEST_CREATE_SUBSCRIPTIONS)) + .thenReturn(false); stubUserInfo(); mockKafkaFlavor(); @@ -293,6 +302,9 @@ public void createAclProducerEmptyTxnId() throws KlawException { hashMap.put("result", ApiResultStatus.SUCCESS.value); when(commonUtilsService.getTopicsForTopicName(anyString(), anyInt())).thenReturn(topicList); when(handleDbRequests.requestForAcl(any())).thenReturn(hashMap); + when(commonUtilsService.isNotAuthorizedUser( + userDetails, PermissionType.REQUEST_CREATE_SUBSCRIPTIONS)) + .thenReturn(false); stubUserInfo(); mockKafkaFlavor(); @@ -438,7 +450,9 @@ public void getCreatedAclRequestsNotAuthorizedForAllTeams() { any(), anyInt())) .thenReturn(getAclRequests("testtopic", 16)); - when(commonUtilsService.isNotAuthorizedUser(any(), any(PermissionType.class))).thenReturn(true); + when(commonUtilsService.isNotAuthorizedUser( + userDetails, PermissionType.APPROVE_ALL_REQUESTS_TEAMS)) + .thenReturn(true); when(commonUtilsService.getEnvsFromUserId(anyString())) .thenReturn(new HashSet<>(Collections.singletonList("1"))); when(manageDatabase.getTeamNameFromTeamId(anyInt(), anyInt())).thenReturn(teamName); @@ -465,6 +479,9 @@ public void deleteAclRequests() throws KlawException { when(commonUtilsService.getTenantId(userDetails.getUsername())).thenReturn(1); when(handleDbRequests.deleteAclRequest(anyInt(), anyString(), anyInt())) .thenReturn(ApiResultStatus.SUCCESS.value); + when(commonUtilsService.isNotAuthorizedUser( + userDetails, PermissionType.REQUEST_CREATE_SUBSCRIPTIONS)) + .thenReturn(false); ApiResponse result = aclControllerService.deleteAclRequests(req_no); assertThat(result.getMessage()).isEqualTo(ApiResultStatus.SUCCESS.value); } @@ -473,16 +490,6 @@ public void deleteAclRequests() throws KlawException { @Order(14) public void deleteAclRequestsNotAuthorized() throws KlawException { String req_no = "1001"; - when(commonUtilsService.isNotAuthorizedUser(any(), any(PermissionType.class))).thenReturn(true); - ApiResponse result = aclControllerService.deleteAclRequests(req_no); - assertThat(result.getMessage()).isEqualTo(ApiResultStatus.NOT_AUTHORIZED.value); - } - - @Test - @Order(14) - public void deleteAclRequestsNotRequestOwner() throws KlawException { - String req_no = "1001"; - when(commonUtilsService.isNotAuthorizedUser(any(), any(PermissionType.class))).thenReturn(true); ApiResponse result = aclControllerService.deleteAclRequests(req_no); assertThat(result.getMessage()).isEqualTo(ApiResultStatus.NOT_AUTHORIZED.value); } @@ -494,6 +501,9 @@ public void deleteAclRequestsFailure() { when(mailService.getCurrentUserName()).thenReturn("testuser"); when(handleDbRequests.deleteAclRequest(anyInt(), anyString(), anyInt())) .thenThrow(new RuntimeException("failure in deleting request")); + when(commonUtilsService.isNotAuthorizedUser( + userDetails, PermissionType.REQUEST_CREATE_SUBSCRIPTIONS)) + .thenReturn(false); KlawException thrown = Assertions.assertThrows( KlawException.class, () -> aclControllerService.deleteAclRequests(req_no)); @@ -515,6 +525,8 @@ public void approveAclRequests() throws KlawException, KlawBadRequestException { .thenReturn(ApiResultStatus.SUCCESS.value); when(commonUtilsService.getEnvsFromUserId(anyString())) .thenReturn(new HashSet<>(Collections.singletonList("1"))); + when(commonUtilsService.isNotAuthorizedUser(userDetails, PermissionType.APPROVE_SUBSCRIPTIONS)) + .thenReturn(false); Topic t1 = new Topic(); t1.setTopicname("testtopic"); t1.setEnvironment("1"); @@ -548,6 +560,8 @@ public void approveAclRequestsWithAivenAcl() throws KlawException, KlawBadReques .thenReturn(ApiResultStatus.SUCCESS.value); when(commonUtilsService.getEnvsFromUserId(anyString())) .thenReturn(new HashSet<>(Collections.singletonList("1"))); + when(commonUtilsService.isNotAuthorizedUser(userDetails, PermissionType.APPROVE_SUBSCRIPTIONS)) + .thenReturn(false); Topic t1 = new Topic(); t1.setTopicname("testtopic"); t1.setEnvironment("1"); @@ -561,7 +575,6 @@ public void approveAclRequestsWithAivenAcl() throws KlawException, KlawBadReques @Order(18) public void approveAclRequestsNotAuthorized() throws KlawException, KlawBadRequestException { stubUserInfo(); - when(commonUtilsService.isNotAuthorizedUser(any(), any(PermissionType.class))).thenReturn(true); ApiResponse apiResp = aclControllerService.approveAclRequests("112"); assertThat(apiResp.getMessage()).isEqualTo(ApiResultStatus.NOT_AUTHORIZED.value); } @@ -573,6 +586,8 @@ public void approveAclRequestsOwnRequest() throws KlawException, KlawBadRequestE AclRequests aclReq = getAclRequestDao(); aclReq.setRequestor("kwusera"); when(handleDbRequests.getAclRequest(anyInt(), anyInt())).thenReturn(aclReq); + when(commonUtilsService.isNotAuthorizedUser(userDetails, PermissionType.APPROVE_SUBSCRIPTIONS)) + .thenReturn(false); ApiResponse apiResp = aclControllerService.approveAclRequests("112"); assertThat(apiResp.getMessage()) .isEqualTo("You are not allowed to approve your own subscription requests."); @@ -591,6 +606,8 @@ public void approveAclRequestsFailure1() throws KlawException, KlawBadRequestExc t1.setTopicname("testtopic"); t1.setEnvironment("1"); when(manageDatabase.getTopicsForTenant(anyInt())).thenReturn(List.of(t1)); + when(commonUtilsService.isNotAuthorizedUser(userDetails, PermissionType.APPROVE_SUBSCRIPTIONS)) + .thenReturn(false); ApiResponse apiResponse = ApiResponse.notOk("failure"); when(clusterApiService.approveAclRequests(any(), anyInt())) @@ -621,6 +638,8 @@ public void approveAclRequestsFailure2() throws KlawException, KlawBadRequestExc .thenReturn(new ResponseEntity<>(apiResponse, HttpStatus.OK)); when(handleDbRequests.updateAclRequest(any(), any(), anyMap(), anyBoolean())) .thenThrow(new RuntimeException("Error")); + when(commonUtilsService.isNotAuthorizedUser(userDetails, PermissionType.APPROVE_SUBSCRIPTIONS)) + .thenReturn(false); ApiResponse apiResp = aclControllerService.approveAclRequests(req_no); assertThat(apiResp.getMessage()).isEqualTo("failure"); @@ -637,6 +656,8 @@ public void approveAclRequestsFailure3() throws KlawException, KlawBadRequestExc when(handleDbRequests.getAclRequest(anyInt(), anyInt())).thenReturn(aclReq); when(manageDatabase.getTeamsAndAllowedEnvs(anyInt(), anyInt())) .thenReturn(Collections.singletonList("1")); + when(commonUtilsService.isNotAuthorizedUser(userDetails, PermissionType.APPROVE_SUBSCRIPTIONS)) + .thenReturn(false); ApiResponse apiResp = aclControllerService.approveAclRequests(req_no); assertThat(apiResp.getMessage()).isEqualTo("This request does not exist anymore."); @@ -654,6 +675,8 @@ public void declineAclRequests() throws KlawException { .thenReturn(new HashSet<>(Collections.singletonList("1"))); when(handleDbRequests.declineAclRequest(any(), any())) .thenReturn(ApiResultStatus.SUCCESS.value); + when(commonUtilsService.isNotAuthorizedUser(userDetails, PermissionType.APPROVE_SUBSCRIPTIONS)) + .thenReturn(false); ApiResponse resultResp = aclControllerService.declineAclRequests(req_no, ""); assertThat(resultResp.getMessage()).isEqualTo(ApiResultStatus.SUCCESS.value); @@ -669,6 +692,8 @@ public void declineAclRequestsFailure() { when(handleDbRequests.getAclRequest(anyInt(), anyInt())).thenReturn(aclReq); when(commonUtilsService.getEnvsFromUserId(anyString())) .thenReturn(new HashSet<>(Collections.singletonList("1"))); + when(commonUtilsService.isNotAuthorizedUser(userDetails, PermissionType.APPROVE_SUBSCRIPTIONS)) + .thenReturn(false); when(handleDbRequests.declineAclRequest(any(), anyString())) .thenThrow(new RuntimeException("failure in declining request")); @@ -693,6 +718,9 @@ public void createDeleteAclSubscriptionRequest() throws KlawException { Map hashMap = new HashMap<>(); hashMap.put("result", ApiResultStatus.SUCCESS.value); when(handleDbRequests.requestForAcl(any())).thenReturn(hashMap); + when(commonUtilsService.isNotAuthorizedUser( + userDetails, PermissionType.REQUEST_DELETE_SUBSCRIPTIONS)) + .thenReturn(false); ApiResponse resultResp = aclControllerService.createDeleteAclSubscriptionRequest(reqNo); assertThat(resultResp.getMessage()).isEqualTo(ApiResultStatus.SUCCESS.value); @@ -1006,6 +1034,9 @@ public void getAclRequestsForApprover_RequestOperationType(RequestOperationType when(commonUtilsService.getEnvsFromUserId(anyString())) .thenReturn(new HashSet<>(Collections.singletonList("1"))); when(manageDatabase.getTeamNameFromTeamId(anyInt(), anyInt())).thenReturn(teamName); + when(commonUtilsService.isNotAuthorizedUser( + userDetails, PermissionType.APPROVE_ALL_REQUESTS_TEAMS)) + .thenReturn(false); List listReqs = aclControllerService.getAclRequestsForApprover( @@ -1047,6 +1078,9 @@ public void createDeleteAclSubscriptionRequestFailure() throws KlawException { Map hashMap = new HashMap<>(); hashMap.put("result", ApiResultStatus.SUCCESS.value); when(handleDbRequests.requestForAcl(any())).thenReturn(hashMap); + when(commonUtilsService.isNotAuthorizedUser( + userDetails, PermissionType.REQUEST_DELETE_SUBSCRIPTIONS)) + .thenReturn(false); when(handleDbRequests.getAllAclRequests( anyBoolean(), @@ -1083,6 +1117,8 @@ public void approveAclRequestsFailure4() throws KlawException, KlawBadRequestExc t1.setTopicname("testtopic1"); // non-existing topic t1.setEnvironment("1"); when(manageDatabase.getTopicsForTenant(anyInt())).thenReturn(List.of(t1)); + when(commonUtilsService.isNotAuthorizedUser(userDetails, PermissionType.APPROVE_SUBSCRIPTIONS)) + .thenReturn(false); ApiResponse apiResp = aclControllerService.approveAclRequests(req_no); assertThat(apiResp.getMessage()).isEqualTo(ACL_ERR_101); @@ -1095,10 +1131,6 @@ public void claimAcl_NotAuthorized() throws KlawException, KlawBadRequestExcepti int aclId = 224; stubUserInfo(); - - when(commonUtilsService.isNotAuthorizedUser( - any(), eq(PermissionType.REQUEST_CREATE_SUBSCRIPTIONS))) - .thenReturn(true); ApiResponse apiResp = aclControllerService.claimAcl(aclId); assertThat(apiResp.getMessage()).isEqualTo(ApiResultStatus.NOT_AUTHORIZED.value); @@ -1110,11 +1142,11 @@ public void claimAcl_NotAuthorized() throws KlawException, KlawBadRequestExcepti public void claimAcl_AclDoesNotExist() throws KlawException { int aclId = 224; stubUserInfo(); - when(commonUtilsService.isNotAuthorizedUser( - any(), eq(PermissionType.REQUEST_CREATE_SUBSCRIPTIONS))) - .thenReturn(false); when(commonUtilsService.getTenantId(any())).thenReturn(TENANT_ID); when(handleDbRequests.getAcl(eq(aclId), anyInt())).thenReturn(Optional.empty()); + when(commonUtilsService.isNotAuthorizedUser( + userDetails, PermissionType.REQUEST_CREATE_SUBSCRIPTIONS)) + .thenReturn(false); ApiResponse apiResp = aclControllerService.claimAcl(aclId); assertThat(apiResp.getMessage()).isEqualTo("Acl does not exist."); @@ -1127,13 +1159,13 @@ public void claimAcl_TopicDoesNotExistOnACL() throws KlawException { int aclId = 224; stubUserInfo(); Acl acl = createAcl(); - when(commonUtilsService.isNotAuthorizedUser( - any(), eq(PermissionType.REQUEST_CREATE_SUBSCRIPTIONS))) - .thenReturn(false); when(commonUtilsService.getTenantId(any())).thenReturn(TENANT_ID); when(handleDbRequests.getAcl(eq(aclId), anyInt())).thenReturn(Optional.of(acl)); when(handleDbRequests.getTopics(eq(acl.getTopicname()), eq(TENANT_ID))) .thenReturn(new ArrayList<>()); + when(commonUtilsService.isNotAuthorizedUser( + userDetails, PermissionType.REQUEST_CREATE_SUBSCRIPTIONS)) + .thenReturn(false); ApiResponse apiResp = aclControllerService.claimAcl(aclId); assertThat(apiResp.getMessage()).isEqualTo("Unable to find the topic related to this ACL."); @@ -1146,9 +1178,6 @@ public void claimAcl_claimAlreadyExists() throws KlawException { int aclId = 224; stubUserInfo(); Acl acl = createAcl(); - when(commonUtilsService.isNotAuthorizedUser( - any(), eq(PermissionType.REQUEST_CREATE_SUBSCRIPTIONS))) - .thenReturn(false); when(commonUtilsService.getTenantId(any())).thenReturn(TENANT_ID); when(handleDbRequests.getAcl(eq(aclId), anyInt())).thenReturn(Optional.of(acl)); ArrayList topics = new ArrayList<>(); @@ -1163,6 +1192,9 @@ public void claimAcl_claimAlreadyExists() throws KlawException { eq(TENANT_ID), eq(aclId))) .thenReturn(true); + when(commonUtilsService.isNotAuthorizedUser( + userDetails, PermissionType.REQUEST_CREATE_SUBSCRIPTIONS)) + .thenReturn(false); ApiResponse apiResp = aclControllerService.claimAcl(aclId); assertThat(apiResp.getMessage()).isEqualTo(ACL_ERR_108); @@ -1175,9 +1207,6 @@ public void claimAcl_createClaimRequest() throws KlawException { int aclId = 224; stubUserInfo(); Acl acl = createAcl(); - when(commonUtilsService.isNotAuthorizedUser( - any(), eq(PermissionType.REQUEST_CREATE_SUBSCRIPTIONS))) - .thenReturn(false); when(commonUtilsService.getTenantId(any())).thenReturn(TENANT_ID); when(handleDbRequests.getAcl(eq(aclId), anyInt())).thenReturn(Optional.of(acl)); ArrayList topics = new ArrayList<>(); @@ -1207,6 +1236,9 @@ public void claimAcl_createClaimRequest() throws KlawException { put("result", ApiResultStatus.SUCCESS.value); } }); + when(commonUtilsService.isNotAuthorizedUser( + userDetails, PermissionType.REQUEST_CREATE_SUBSCRIPTIONS)) + .thenReturn(false); ApiResponse apiResp = aclControllerService.claimAcl(aclId); verify(approvalService, times(1)) .sendEmailToApprovers( @@ -1227,8 +1259,6 @@ public void claimAcl_createClaimRequest() throws KlawException { public void claimAcl_approveClaim_NotAuthorized() throws KlawException, KlawBadRequestException { String reqNum = "224"; stubUserInfo(); - when(commonUtilsService.isNotAuthorizedUser(any(), eq(PermissionType.APPROVE_SUBSCRIPTIONS))) - .thenReturn(true); ApiResponse apiResp = aclControllerService.approveAclRequests(reqNum); assertThat(apiResp.isSuccess()).isFalse(); @@ -1242,8 +1272,6 @@ public void claimAcl_approveClaim_transferOwnership() int reqNum = 224; stubUserInfo(); Acl acl = createAcl(); - when(commonUtilsService.isNotAuthorizedUser(any(), eq(PermissionType.APPROVE_SUBSCRIPTIONS))) - .thenReturn(false); when(commonUtilsService.getTenantId(any())).thenReturn(TENANT_ID); AclRequests aclReq = getAclClaimRequestDao(reqNum); when(handleDbRequests.getAclRequest(eq(reqNum), eq(TENANT_ID))) @@ -1261,6 +1289,8 @@ public void claimAcl_approveClaim_transferOwnership() .thenReturn(false); when(manageDatabase.getTeamObjForTenant(eq(TENANT_ID))) .thenReturn(getTeamsListWithServiceAccounts(aclReq)); + when(commonUtilsService.isNotAuthorizedUser(userDetails, PermissionType.APPROVE_SUBSCRIPTIONS)) + .thenReturn(false); ApiResponse apiResp = aclControllerService.approveAclRequests(String.valueOf(reqNum)); @@ -1299,8 +1329,6 @@ public void claimAcl_approveClaim_transferOwnership() int reqNum = 224; stubUserInfo(); Acl acl = createAcl(); - when(commonUtilsService.isNotAuthorizedUser(any(), eq(PermissionType.APPROVE_SUBSCRIPTIONS))) - .thenReturn(false); when(commonUtilsService.getTenantId(any())).thenReturn(TENANT_ID); AclRequests aclReq = getAclClaimRequestDao(reqNum); when(handleDbRequests.getAclRequest(eq(reqNum), eq(TENANT_ID))) @@ -1318,6 +1346,8 @@ public void claimAcl_approveClaim_transferOwnership() .thenReturn(true); when(manageDatabase.getTeamObjForTenant(eq(TENANT_ID))) .thenReturn(getTeamsListWithServiceAccounts(aclReq)); + when(commonUtilsService.isNotAuthorizedUser(userDetails, PermissionType.APPROVE_SUBSCRIPTIONS)) + .thenReturn(false); ApiResponse apiResp = aclControllerService.approveAclRequests(String.valueOf(reqNum)); @@ -1342,8 +1372,6 @@ public void claimAcl_approveClaim_Not_fullyApproved_doNot_transferOwnership() int reqNum = 224; stubUserInfo(); Acl acl = createAcl(); - when(commonUtilsService.isNotAuthorizedUser(any(), eq(PermissionType.APPROVE_SUBSCRIPTIONS))) - .thenReturn(false); when(commonUtilsService.getTenantId(any())).thenReturn(TENANT_ID); AclRequests aclReq = getAclClaimRequestDao(reqNum); when(handleDbRequests.getAclRequest(eq(reqNum), eq(TENANT_ID))) @@ -1354,6 +1382,8 @@ public void claimAcl_approveClaim_Not_fullyApproved_doNot_transferOwnership() topics.add(createTopic()); when(manageDatabase.getTopicsForTenant(TENANT_ID)).thenReturn(topics); when(approvalService.isRequestFullyApproved(any())).thenReturn(false); + when(commonUtilsService.isNotAuthorizedUser(userDetails, PermissionType.APPROVE_SUBSCRIPTIONS)) + .thenReturn(false); ApiResponse apiResp = aclControllerService.approveAclRequests(String.valueOf(reqNum)); @@ -1380,8 +1410,6 @@ public void claimAcl_approveClaim_Not_fullyApproved_doNot_transferOwnership() int reqNum = 224; stubUserInfo(); Acl acl = createAcl(); - when(commonUtilsService.isNotAuthorizedUser(any(), eq(PermissionType.APPROVE_SUBSCRIPTIONS))) - .thenReturn(false); when(commonUtilsService.getTenantId(any())).thenReturn(TENANT_ID); AclRequests aclReq = getAclClaimRequestDao(reqNum); when(handleDbRequests.getAclRequest(eq(reqNum), eq(TENANT_ID))) @@ -1404,6 +1432,8 @@ public void claimAcl_approveClaim_Not_fullyApproved_doNot_transferOwnership() .existsAclSslInTeam(aclReq.getTeamId(), aclReq.getTenantId(), aclReq.getAcl_ssl())) .thenReturn(false); when(manageDatabase.getTeamObjForTenant(eq(TENANT_ID))).thenReturn(existingTeams); + when(commonUtilsService.isNotAuthorizedUser(userDetails, PermissionType.APPROVE_SUBSCRIPTIONS)) + .thenReturn(false); ApiResponse apiResp = aclControllerService.approveAclRequests(String.valueOf(reqNum)); @@ -1443,8 +1473,6 @@ public void claimAcl_approveClaim_Not_fullyApproved_doNot_transferOwnership() int reqNum = 224; stubUserInfo(); Acl acl = createAcl(); - when(commonUtilsService.isNotAuthorizedUser(any(), eq(PermissionType.APPROVE_SUBSCRIPTIONS))) - .thenReturn(false); when(commonUtilsService.getTenantId(any())).thenReturn(TENANT_ID); AclRequests aclReq = getAclClaimRequestDao(reqNum); when(handleDbRequests.getAclRequest(eq(reqNum), eq(TENANT_ID))) @@ -1466,6 +1494,8 @@ public void claimAcl_approveClaim_Not_fullyApproved_doNot_transferOwnership() .existsAclSslInTeam(aclReq.getTeamId(), aclReq.getTenantId(), aclReq.getAcl_ssl())) .thenReturn(false); when(manageDatabase.getTeamObjForTenant(eq(TENANT_ID))).thenReturn(existingTeams); + when(commonUtilsService.isNotAuthorizedUser(userDetails, PermissionType.APPROVE_SUBSCRIPTIONS)) + .thenReturn(false); ApiResponse apiResp = aclControllerService.approveAclRequests(String.valueOf(reqNum)); @@ -1516,6 +1546,9 @@ public void createAclProducer_alreadyExists() throws KlawException { .thenReturn(true); stubUserInfo(); mockKafkaFlavor(); + when(commonUtilsService.isNotAuthorizedUser( + userDetails, PermissionType.REQUEST_CREATE_SUBSCRIPTIONS)) + .thenReturn(false); ApiResponse resultResp = aclControllerService.createAcl(aclRequests); assertThat(resultResp.getMessage()).isEqualTo("Subscription already exists."); @@ -1542,6 +1575,10 @@ public void createAclConsumer_alreadyExists() throws KlawException { mockKafkaFlavor(); stubUserInfo(); + when(commonUtilsService.isNotAuthorizedUser( + userDetails, PermissionType.REQUEST_CREATE_SUBSCRIPTIONS)) + .thenReturn(false); + ApiResponse resultResp = aclControllerService.createAcl(aclRequests); assertThat(resultResp.getMessage()).isEqualTo("Subscription already exists."); } diff --git a/core/src/test/java/io/aiven/klaw/service/AclSyncControllerServiceTest.java b/core/src/test/java/io/aiven/klaw/service/AclSyncControllerServiceTest.java index 87bb8f90e..50306bbba 100644 --- a/core/src/test/java/io/aiven/klaw/service/AclSyncControllerServiceTest.java +++ b/core/src/test/java/io/aiven/klaw/service/AclSyncControllerServiceTest.java @@ -42,12 +42,8 @@ import org.junit.jupiter.api.TestMethodOrder; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; -import org.mockito.Mockito; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; -import org.springframework.security.core.Authentication; -import org.springframework.security.core.context.SecurityContext; -import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.test.context.junit.jupiter.SpringExtension; import org.springframework.test.util.ReflectionTestUtils; @@ -80,15 +76,8 @@ public void setUp() throws Exception { ReflectionTestUtils.setField( aclSyncControllerService, "commonUtilsService", commonUtilsService); when(manageDatabase.getHandleDbRequests()).thenReturn(handleDbRequests); - loginMock(); - } - - private void loginMock() { - Authentication authentication = Mockito.mock(Authentication.class); - SecurityContext securityContext = Mockito.mock(SecurityContext.class); - when(securityContext.getAuthentication()).thenReturn(authentication); - when(authentication.getPrincipal()).thenReturn(userDetails); - SecurityContextHolder.setContext(securityContext); + when(commonUtilsService.getPrincipal()).thenReturn(userDetails); + when(commonUtilsService.isNotAuthorizedUser(any(), any(PermissionType.class))).thenReturn(true); } @Test @@ -96,7 +85,7 @@ private void loginMock() { public void updateSyncAcls() throws KlawException { stubUserInfo(); when(handleDbRequests.addToSyncacls(anyList())).thenReturn(ApiResultStatus.SUCCESS.value); - when(commonUtilsService.isNotAuthorizedUser(any(), any(PermissionType.class))) + when(commonUtilsService.isNotAuthorizedUser(userDetails, PermissionType.SYNC_SUBSCRIPTIONS)) .thenReturn(false); when(commonUtilsService.getEnvsFromUserId(anyString())) .thenReturn(new HashSet<>(Collections.singletonList("1"))); @@ -110,7 +99,7 @@ public void updateSyncAcls() throws KlawException { @Order(2) public void updateSyncAclsFailure1() throws KlawException { stubUserInfo(); - when(commonUtilsService.isNotAuthorizedUser(any(), any(PermissionType.class))) + when(commonUtilsService.isNotAuthorizedUser(userDetails, PermissionType.SYNC_SUBSCRIPTIONS)) .thenReturn(false); ApiResponse resultResp = @@ -122,7 +111,7 @@ public void updateSyncAclsFailure1() throws KlawException { @Order(3) public void updateSyncAclsFailure2() { stubUserInfo(); - when(commonUtilsService.isNotAuthorizedUser(any(), any(PermissionType.class))) + when(commonUtilsService.isNotAuthorizedUser(userDetails, PermissionType.SYNC_SUBSCRIPTIONS)) .thenReturn(false); when(handleDbRequests.addToSyncacls(anyList())).thenThrow(new RuntimeException("Error")); when(manageDatabase.getTeamsAndAllowedEnvs(anyInt(), anyInt())) @@ -140,7 +129,7 @@ public void updateSyncAclsFailure2() { public void updateSyncAclsFailure3() throws KlawException { List updates = new ArrayList<>(); stubUserInfo(); - when(commonUtilsService.isNotAuthorizedUser(any(), any(PermissionType.class))) + when(commonUtilsService.isNotAuthorizedUser(userDetails, PermissionType.SYNC_SUBSCRIPTIONS)) .thenReturn(false); when(manageDatabase.getTeamsAndAllowedEnvs(anyInt(), anyInt())) .thenReturn(Collections.singletonList("1")); @@ -153,7 +142,7 @@ public void updateSyncAclsFailure3() throws KlawException { public void updateSyncAclsFailure4() { when(handleDbRequests.addToSyncacls(anyList())).thenThrow(new RuntimeException("Error")); stubUserInfo(); - when(commonUtilsService.isNotAuthorizedUser(any(), any(PermissionType.class))) + when(commonUtilsService.isNotAuthorizedUser(userDetails, PermissionType.SYNC_SUBSCRIPTIONS)) .thenReturn(false); when(manageDatabase.getTeamsAndAllowedEnvs(anyInt(), anyInt())) .thenReturn(Collections.singletonList("1")); @@ -187,6 +176,8 @@ public void getAclsSyncTrue1() throws KlawException { .thenReturn(clustersHashMap); when(clustersHashMap.get(any())).thenReturn(kwClusters); when(kwClusters.getBootstrapServers()).thenReturn("clusters"); + when(commonUtilsService.isNotAuthorizedUser(userDetails, PermissionType.SYNC_SUBSCRIPTIONS)) + .thenReturn(false); List aclList = aclSyncControllerService.getSyncAcls(envSelected, pageNo, "1", topicNameSearch, ""); @@ -217,6 +208,8 @@ public void getAclsSyncTrueNonApacheKafka() throws KlawException { .thenReturn(clustersHashMap); when(clustersHashMap.get(any())).thenReturn(kwClusters); when(kwClusters.getBootstrapServers()).thenReturn("clusters"); + when(commonUtilsService.isNotAuthorizedUser(userDetails, PermissionType.SYNC_SUBSCRIPTIONS)) + .thenReturn(false); List aclList = aclSyncControllerService.getSyncAcls(envSelected, pageNo, "1", topicNameSearch, ""); @@ -263,6 +256,8 @@ public void getAclsSyncTrueGetDeletedOnClusterNonApacheKafka() throws KlawExcept .thenReturn(clustersHashMap); when(clustersHashMap.get(any())).thenReturn(kwClusters); when(kwClusters.getBootstrapServers()).thenReturn("clusters"); + when(commonUtilsService.isNotAuthorizedUser(userDetails, PermissionType.SYNC_SUBSCRIPTIONS)) + .thenReturn(false); List aclList = aclSyncControllerService.getSyncAcls(envSelected, pageNo, "1", topicNameSearch, ""); @@ -291,6 +286,8 @@ public void getAclsSyncTrue2() throws KlawException { .thenReturn(clustersHashMap); when(clustersHashMap.get(any())).thenReturn(kwClusters); when(kwClusters.getBootstrapServers()).thenReturn("clusters"); + when(commonUtilsService.isNotAuthorizedUser(userDetails, PermissionType.SYNC_SUBSCRIPTIONS)) + .thenReturn(false); List aclList = aclSyncControllerService.getSyncAcls(envSelected, pageNo, "", topicNameSearch, ""); @@ -324,7 +321,8 @@ public void updateSyncBackAcls() throws KlawException { .thenReturn(clustersHashMap); when(clustersHashMap.get(any())).thenReturn(kwClusters); when(kwClusters.getKafkaFlavor()).thenReturn(KafkaFlavors.AIVEN_FOR_APACHE_KAFKA.value); - when(commonUtilsService.isNotAuthorizedUser(any(), any(PermissionType.class))) + when(commonUtilsService.isNotAuthorizedUser( + userDetails, PermissionType.SYNC_BACK_SUBSCRIPTIONS)) .thenReturn(false); when(handleDbRequests.getSyncAclsFromReqNo(anyInt(), anyInt())) .thenReturn(getAclsSOT0().get(0)); @@ -407,6 +405,6 @@ private List getAclsSOT0NonApacheKafka() { private void stubUserInfo() { when(handleDbRequests.getUsersInfo(anyString())).thenReturn(userInfo); when(userInfo.getTeamId()).thenReturn(101); - when(mailService.getUserName(any())).thenReturn("kwusera"); + when(mailService.getUserName(userDetails)).thenReturn("kwusera"); } } diff --git a/core/src/test/java/io/aiven/klaw/service/AnalyticsControllerServiceTest.java b/core/src/test/java/io/aiven/klaw/service/AnalyticsControllerServiceTest.java index 8996e7081..65c23223a 100644 --- a/core/src/test/java/io/aiven/klaw/service/AnalyticsControllerServiceTest.java +++ b/core/src/test/java/io/aiven/klaw/service/AnalyticsControllerServiceTest.java @@ -7,7 +7,6 @@ import static org.mockito.ArgumentMatchers.anyList; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.ArgumentMatchers.eq; -import static org.mockito.Mockito.when; import io.aiven.klaw.UtilMethods; import io.aiven.klaw.config.ManageDatabase; @@ -30,19 +29,17 @@ import java.util.Map; import java.util.Set; import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.Spy; -import org.mockito.junit.jupiter.MockitoExtension; -import org.springframework.security.core.Authentication; -import org.springframework.security.core.context.SecurityContext; -import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.core.userdetails.UserDetails; +import org.springframework.test.context.junit.jupiter.SpringExtension; -@ExtendWith(MockitoExtension.class) +@ExtendWith(SpringExtension.class) class AnalyticsControllerServiceTest { public static final int NUMBER_OF_DAYS = 30; @Mock private ManageDatabase manageDatabase; @@ -52,12 +49,11 @@ class AnalyticsControllerServiceTest { @Mock private HandleDbRequestsJdbc handleDbRequestsJdbc; @Mock private UserDetails userDetails; - private void loginMock() { - Authentication authentication = Mockito.mock(Authentication.class); - SecurityContext securityContext = Mockito.mock(SecurityContext.class); - when(securityContext.getAuthentication()).thenReturn(authentication); - when(authentication.getPrincipal()).thenReturn(userDetails); - SecurityContextHolder.setContext(securityContext); + @BeforeEach + public void setUp() { + Mockito.when(commonUtilsService.getPrincipal()).thenReturn(userDetails); + Mockito.when(commonUtilsService.isNotAuthorizedUser(any(), any(PermissionType.class))) + .thenReturn(true); } @Test @@ -460,13 +456,9 @@ public void getTeamsOverview_UnauthorizedUser() { teamOverview.setTopicsPerTeamsOverview(chartsJsOverview); List expected = List.of(teamOverview); - loginMock(); Mockito.when(commonUtilsService.getCurrentUserName()).thenReturn(TestConstants.USERNAME); Mockito.when(commonUtilsService.getTeamId(TestConstants.USERNAME)) .thenReturn(TestConstants.TEAM_ID); - Mockito.when( - commonUtilsService.isNotAuthorizedUser(any(), eq(PermissionType.ALL_TEAMS_REPORTS))) - .thenReturn(true); Mockito.when(commonUtilsService.getTenantId(TestConstants.USERNAME)) .thenReturn(TestConstants.TENANT_ID); Mockito.doReturn(chartsJsOverview) @@ -509,12 +501,11 @@ public void getTeamsOverview_AuthorizedUser() { teamOverview.setTopicsPerTeamsOverview(chartsJsOverview); List expected = List.of(teamOverview); - loginMock(); Mockito.when(commonUtilsService.getCurrentUserName()).thenReturn(TestConstants.USERNAME); Mockito.when(commonUtilsService.getTeamId(TestConstants.USERNAME)) .thenReturn(TestConstants.TEAM_ID); Mockito.when( - commonUtilsService.isNotAuthorizedUser(any(), eq(PermissionType.ALL_TEAMS_REPORTS))) + commonUtilsService.isNotAuthorizedUser(userDetails, PermissionType.ALL_TEAMS_REPORTS)) .thenReturn(false); Mockito.when(commonUtilsService.getTenantId(TestConstants.USERNAME)) .thenReturn(TestConstants.TENANT_ID); @@ -577,7 +568,6 @@ public void generateReport_UnauthorizedUser() { Topic topic = UtilMethods.getDummyTopic(); Acl acl = UtilMethods.getDummyAcl(); - loginMock(); Mockito.when(commonUtilsService.getCurrentUserName()).thenReturn(TestConstants.USERNAME); Mockito.when(commonUtilsService.getTenantId(TestConstants.USERNAME)) .thenReturn(TestConstants.TENANT_ID); @@ -593,9 +583,6 @@ public void generateReport_UnauthorizedUser() { Mockito.doReturn(TestConstants.ENV_NAME) .when(analyticsControllerService) .getEnvName(TestConstants.ENV_ID); - Mockito.when( - commonUtilsService.isNotAuthorizedUser(any(), eq(PermissionType.ALL_TEAMS_REPORTS))) - .thenReturn(true); Mockito.when(commonUtilsService.getTeamId(TestConstants.USERNAME)) .thenReturn(TestConstants.TEAM_ID); Mockito.when(manageDatabase.getHandleDbRequests()).thenReturn(handleDbRequestsJdbc); @@ -620,7 +607,6 @@ public void generateReport_AuthorizedUser() { Topic topic = UtilMethods.getDummyTopic(); Acl acl = UtilMethods.getDummyAcl(); - loginMock(); Mockito.when(commonUtilsService.getCurrentUserName()).thenReturn(TestConstants.USERNAME); Mockito.when(commonUtilsService.getTenantId(TestConstants.USERNAME)) .thenReturn(TestConstants.TENANT_ID); @@ -637,7 +623,7 @@ public void generateReport_AuthorizedUser() { .when(analyticsControllerService) .getEnvName(TestConstants.ENV_ID); Mockito.when( - commonUtilsService.isNotAuthorizedUser(any(), eq(PermissionType.ALL_TEAMS_REPORTS))) + commonUtilsService.isNotAuthorizedUser(userDetails, PermissionType.ALL_TEAMS_REPORTS)) .thenReturn(false); Mockito.when(manageDatabase.getHandleDbRequests()).thenReturn(handleDbRequestsJdbc); Mockito.when(handleDbRequestsJdbc.getAllTopics(TestConstants.TENANT_ID)) diff --git a/core/src/test/java/io/aiven/klaw/service/EnvsClustersTenantsControllerServiceTest.java b/core/src/test/java/io/aiven/klaw/service/EnvsClustersTenantsControllerServiceTest.java index 161000034..a74016632 100644 --- a/core/src/test/java/io/aiven/klaw/service/EnvsClustersTenantsControllerServiceTest.java +++ b/core/src/test/java/io/aiven/klaw/service/EnvsClustersTenantsControllerServiceTest.java @@ -69,6 +69,7 @@ import org.mockito.ArgumentCaptor; import org.mockito.Captor; import org.mockito.Mock; +import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.test.context.support.WithMockUser; import org.springframework.test.context.junit.jupiter.SpringExtension; import org.springframework.test.util.ReflectionTestUtils; @@ -79,6 +80,7 @@ class EnvsClustersTenantsControllerServiceTest { private EnvsClustersTenantsControllerService service; @Mock private MailUtils mailService; + @Mock private UserDetails userDetails; @Mock private CommonUtilsService commonUtilsService; @@ -102,10 +104,12 @@ public void setup() { ReflectionTestUtils.setField( service, "usersTeamsControllerService", usersTeamsControllerService); ReflectionTestUtils.setField(service, "defaultDataService", defaultDataService); - when(mailService.getUserName(any())).thenReturn("testuser"); + when(mailService.getUserName(userDetails)).thenReturn("testuser"); when(handleDbRequestsJdbc.getUsersInfo(any())).thenReturn(buildUserInfo()); when(manageDatabase.getHandleDbRequests()).thenReturn(handleDbRequestsJdbc); when(commonUtilsService.getTenantId(any())).thenReturn(101); + when(commonUtilsService.getPrincipal()).thenReturn(userDetails); + when(commonUtilsService.isNotAuthorizedUser(any(), any(PermissionType.class))).thenReturn(true); } @Test @@ -117,6 +121,8 @@ void addNewEnv() throws KlawException, KlawValidationException { Env SchemaEnv = generateKafkaEnv("9", "Schema"); when(handleDbRequestsJdbc.addNewEnv(any())).thenReturn(ApiResultStatus.SUCCESS.value); when(handleDbRequestsJdbc.getEnvDetails(anyString(), anyInt())).thenReturn(SchemaEnv); + when(commonUtilsService.isNotAuthorizedUser(userDetails, PermissionType.ADD_EDIT_DELETE_ENVS)) + .thenReturn(false); ApiResponse response = service.addNewEnv(env); assertThat(response.getMessage()).contains("success"); } @@ -134,6 +140,8 @@ void addNewEnvNameAlreadyInUse() throws KlawException, KlawValidationException { buildEnv("5", 101, "TST", KafkaClustersType.SCHEMA_REGISTRY, 5))); when(manageDatabase.getKafkaEnvList(anyInt())) .thenReturn(List.of(buildEnv("4", 101, "DEV", KafkaClustersType.KAFKA, 4))); + when(commonUtilsService.isNotAuthorizedUser(userDetails, PermissionType.ADD_EDIT_DELETE_ENVS)) + .thenReturn(false); ApiResponse response = service.addNewEnv(env); assertThat(response.getMessage()) .contains("Failure. Please choose a different name. This environment name already exists."); @@ -150,6 +158,8 @@ void addNewEnvWithAssociatedEnv() throws KlawException, KlawValidationException when(handleDbRequestsJdbc.getEnvDetails(eq("1"), eq(101))) .thenReturn(kafkaEnv) .thenReturn(null); + when(commonUtilsService.isNotAuthorizedUser(userDetails, PermissionType.ADD_EDIT_DELETE_ENVS)) + .thenReturn(false); ApiResponse response = service.addNewEnv(env); kafkaEnv.setAssociatedEnv(env.getAssociatedEnv()); verify(handleDbRequestsJdbc, times(1)).addNewEnv(eq(kafkaEnv)); @@ -180,6 +190,8 @@ void updateEnvWithDifferentAssociatedEnv() throws KlawException, KlawValidationE .thenReturn(generateKafkaEnv("2", "Kafka")); when(handleDbRequestsJdbc.getNextSeqIdAndUpdate(eq(EntityType.ENVIRONMENT.name()), eq(101))) .thenReturn(1); + when(commonUtilsService.isNotAuthorizedUser(userDetails, PermissionType.ADD_EDIT_DELETE_ENVS)) + .thenReturn(false); ApiResponse response = service.addNewEnv(env); kafkaEnv.setAssociatedEnv(env.getAssociatedEnv()); verify(handleDbRequestsJdbc, times(1)).addNewEnv(eq(kafkaEnv)); @@ -203,6 +215,8 @@ void updateEnvWithKafkaEnvAlreadyAssociatedWithAnotherEnv() { Env kafkaEnv = generateKafkaEnv("1", "Kafka"); kafkaEnv.setAssociatedEnv(new EnvTag("2", "TST_SCH")); when(handleDbRequestsJdbc.getEnvDetails(eq("1"), eq(101))).thenReturn(kafkaEnv); + when(commonUtilsService.isNotAuthorizedUser(userDetails, PermissionType.ADD_EDIT_DELETE_ENVS)) + .thenReturn(false); assertThatExceptionOfType(KlawValidationException.class) .isThrownBy( @@ -222,6 +236,8 @@ void addEnvWithoutAssociatedEnv() throws KlawValidationException, KlawException when(handleDbRequestsJdbc.getEnvDetails(eq("1"), eq(101))).thenReturn(env1).thenReturn(null); when(handleDbRequestsJdbc.addNewEnv(any())).thenReturn(ApiResultStatus.SUCCESS.value); + when(commonUtilsService.isNotAuthorizedUser(userDetails, PermissionType.ADD_EDIT_DELETE_ENVS)) + .thenReturn(false); ApiResponse response = service.addNewEnv(env); assertThat(response.getMessage()).contains("success"); @@ -243,6 +259,8 @@ void addEnvRemoveAssociatedEnv() throws KlawValidationException, KlawException { when(handleDbRequestsJdbc.addNewEnv(any())).thenReturn(ApiResultStatus.SUCCESS.value); when(handleDbRequestsJdbc.getNextSeqIdAndUpdate(eq(EntityType.ENVIRONMENT.name()), eq(101))) .thenReturn(1); + when(commonUtilsService.isNotAuthorizedUser(userDetails, PermissionType.ADD_EDIT_DELETE_ENVS)) + .thenReturn(false); ApiResponse response = service.addNewEnv(env); assertThat(response.getMessage()).contains("success"); @@ -264,6 +282,8 @@ void addEnvRemoveAssociatedEnvIncorrectIdSupplied() when(handleDbRequestsJdbc.addNewEnv(any())).thenReturn(ApiResultStatus.SUCCESS.value); when(handleDbRequestsJdbc.getNextSeqIdAndUpdate(eq(EntityType.ENVIRONMENT.name()), eq(101))) .thenReturn(1); + when(commonUtilsService.isNotAuthorizedUser(userDetails, PermissionType.ADD_EDIT_DELETE_ENVS)) + .thenReturn(false); ApiResponse response = service.addNewEnv(env); assertThat(response.getMessage()).contains("success"); @@ -308,7 +328,7 @@ void getEnvs(KafkaClustersType type, String searchBy, String pageNo, int expecte put(101, ""); } }); - when(commonUtilsService.isNotAuthorizedUser(any(), any(PermissionType.class))) + when(commonUtilsService.isNotAuthorizedUser(userDetails, PermissionType.ADD_EDIT_DELETE_ENVS)) .thenReturn(false); List response = service.getEnvsPaginated(type, "", pageNo, searchBy); @@ -321,7 +341,6 @@ void getEnvs(KafkaClustersType type, String searchBy, String pageNo, int expecte username = "james", authorities = {"ADMIN", "USER"}) void deleteTenantUnauthorizedUser1() throws KlawException { - when(commonUtilsService.isNotAuthorizedUser(any(), any(PermissionType.class))).thenReturn(true); ApiResponse response = service.deleteTenant(); assertThat(response).isEqualTo(ApiResponse.NOT_AUTHORIZED); @@ -332,7 +351,8 @@ void deleteTenantUnauthorizedUser1() throws KlawException { username = "james", authorities = {"ADMIN", "USER"}) void deleteTenantUnauthorizedUser2() throws KlawException { - when(commonUtilsService.isNotAuthorizedUser(any(), any(PermissionType.class))) + when(commonUtilsService.isNotAuthorizedUser( + userDetails, PermissionType.UPDATE_DELETE_MY_TENANT)) .thenReturn(false); ApiResponse response = service.deleteTenant(); @@ -345,7 +365,8 @@ void deleteTenantUnauthorizedUser2() throws KlawException { authorities = {"ADMIN", "USER"}) void deleteTenantFailed() throws KlawException { int tenantId = 102; - when(commonUtilsService.isNotAuthorizedUser(any(), any(PermissionType.class))) + when(commonUtilsService.isNotAuthorizedUser( + userDetails, PermissionType.UPDATE_DELETE_MY_TENANT)) .thenReturn(false); when(commonUtilsService.getTenantId(any())).thenReturn(tenantId); when(manageDatabase.getTenantMap()) @@ -374,7 +395,8 @@ void deleteTenantFailed() throws KlawException { authorities = {"ADMIN", "USER"}) void deleteTenant() throws KlawException { int tenantId = 102; - when(commonUtilsService.isNotAuthorizedUser(any(), any(PermissionType.class))) + when(commonUtilsService.isNotAuthorizedUser( + userDetails, PermissionType.UPDATE_DELETE_MY_TENANT)) .thenReturn(false); when(commonUtilsService.getTenantId(any())).thenReturn(tenantId); when(manageDatabase.getTenantMap()) @@ -425,7 +447,6 @@ void addTenantIdExceedMax() throws KlawException { void addTenantIdUnauthorized() throws KlawException { when(handleDbRequestsJdbc.getTenants()).thenReturn(List.of(new KwTenants(), new KwTenants())); ReflectionTestUtils.setField(service, "maxNumberOfTenantsCanBeCreated", 100); - when(commonUtilsService.isNotAuthorizedUser(any(), any(PermissionType.class))).thenReturn(true); ApiResponse response = service.addTenantId(new KwTenantModel(), true); assertThat(response).isEqualTo(ApiResponse.NOT_AUTHORIZED); @@ -446,7 +467,7 @@ void addTenantIdInternal() throws KlawException { kwTenant2.setTenantId(102); when(handleDbRequestsJdbc.getTenants()).thenReturn(List.of(kwTenant1, kwTenant2)); ReflectionTestUtils.setField(service, "maxNumberOfTenantsCanBeCreated", 100); - when(commonUtilsService.isNotAuthorizedUser(any(), any(PermissionType.class))) + when(commonUtilsService.isNotAuthorizedUser(userDetails, PermissionType.ADD_TENANT)) .thenReturn(false); when(handleDbRequestsJdbc.addNewTenant(any())).thenReturn("add new tenant"); ApiResponse response = service.addTenantId(kwTenantModel, false); @@ -474,7 +495,7 @@ void addTenantIdExternal() throws KlawException { when(handleDbRequestsJdbc.getTenants()).thenReturn(List.of(kwTenant1, kwTenant2)); ReflectionTestUtils.setField(service, "maxNumberOfTenantsCanBeCreated", 100); ReflectionTestUtils.setField(service, "kwInstallationType", "kwInstallationType"); - when(commonUtilsService.isNotAuthorizedUser(any(), any(PermissionType.class))) + when(commonUtilsService.isNotAuthorizedUser(userDetails, PermissionType.ADD_TENANT)) .thenReturn(false); when(handleDbRequestsJdbc.addNewTenant(any())).thenReturn("add new tenant"); List kwProperties = List.of(new KwProperties()); @@ -552,7 +573,6 @@ void getUpdateEnvStatus() throws KlawBadRequestException { username = "james", authorities = {"ADMIN", "USER"}) void deleteEnvironmentUnauthorized() throws KlawException { - when(commonUtilsService.isNotAuthorizedUser(any(), any(PermissionType.class))).thenReturn(true); ApiResponse response = service.deleteEnvironment("envId", "envType"); assertThat(response).isEqualTo(ApiResponse.NOT_AUTHORIZED); @@ -565,7 +585,7 @@ void deleteEnvironmentUnauthorized() throws KlawException { void deleteEnvironmentExistKafkaComponents() throws KlawException { int tenantId = 101; String envId = "20"; - when(commonUtilsService.isNotAuthorizedUser(any(), any(PermissionType.class))) + when(commonUtilsService.isNotAuthorizedUser(userDetails, PermissionType.ADD_EDIT_DELETE_ENVS)) .thenReturn(false); when(handleDbRequestsJdbc.existsKafkaComponentsForEnv(envId, tenantId)).thenReturn(true); @@ -581,7 +601,7 @@ void deleteEnvironmentExistKafkaComponents() throws KlawException { void deleteEnvironmentExistKafkaConnectComponents() throws KlawException { int tenantId = 101; String envId = "20"; - when(commonUtilsService.isNotAuthorizedUser(any(), any(PermissionType.class))) + when(commonUtilsService.isNotAuthorizedUser(userDetails, PermissionType.ADD_EDIT_DELETE_ENVS)) .thenReturn(false); when(handleDbRequestsJdbc.existsConnectorComponentsForEnv(envId, tenantId)).thenReturn(true); @@ -597,7 +617,7 @@ void deleteEnvironmentExistKafkaConnectComponents() throws KlawException { void deleteEnvironmentExistSchemaRegistryComponents() throws KlawException { int tenantId = 101; String envId = "20"; - when(commonUtilsService.isNotAuthorizedUser(any(), any(PermissionType.class))) + when(commonUtilsService.isNotAuthorizedUser(userDetails, PermissionType.ADD_EDIT_DELETE_ENVS)) .thenReturn(false); when(handleDbRequestsJdbc.existsSchemaComponentsForEnv(envId, tenantId)).thenReturn(true); @@ -614,7 +634,7 @@ void deleteEnvironmentExistSchemaRegistryComponents() throws KlawException { void deleteEnvironmentWithAssociatedEnv() throws KlawException { int tenantId = 101; String envId = "20"; - when(commonUtilsService.isNotAuthorizedUser(any(), any(PermissionType.class))) + when(commonUtilsService.isNotAuthorizedUser(userDetails, PermissionType.ADD_EDIT_DELETE_ENVS)) .thenReturn(false); when(handleDbRequestsJdbc.existsKafkaComponentsForEnv(envId, tenantId)).thenReturn(false); @@ -643,7 +663,7 @@ void deleteEnvironmentWithAssociatedEnv() throws KlawException { void deleteEnvironmentFailed() throws KlawException { int tenantId = 101; String envId = "20"; - when(commonUtilsService.isNotAuthorizedUser(any(), any(PermissionType.class))) + when(commonUtilsService.isNotAuthorizedUser(userDetails, PermissionType.ADD_EDIT_DELETE_ENVS)) .thenReturn(false); when(handleDbRequestsJdbc.existsKafkaComponentsForEnv(envId, tenantId)).thenReturn(false); @@ -662,7 +682,6 @@ void deleteEnvironmentFailed() throws KlawException { username = "james", authorities = {"ADMIN", "USER"}) void addNewClusterUnauthorized() { - when(commonUtilsService.isNotAuthorizedUser(any(), any(PermissionType.class))).thenReturn(true); ApiResponse response = service.addNewCluster(new KwClustersModel()); assertThat(response).isEqualTo(ApiResponse.NOT_AUTHORIZED); @@ -674,7 +693,8 @@ void addNewClusterUnauthorized() { authorities = {"ADMIN", "USER"}) void addNewCluster() { int tenantId = 101; - when(commonUtilsService.isNotAuthorizedUser(any(), any(PermissionType.class))) + when(commonUtilsService.isNotAuthorizedUser( + userDetails, PermissionType.ADD_EDIT_DELETE_CLUSTERS)) .thenReturn(false); when(handleDbRequestsJdbc.addNewCluster(any(KwClusters.class))) @@ -698,7 +718,8 @@ void addNewCluster() { authorities = {"ADMIN", "USER"}) void addNewClusterFailed() { int tenantId = 101; - when(commonUtilsService.isNotAuthorizedUser(any(), any(PermissionType.class))) + when(commonUtilsService.isNotAuthorizedUser( + userDetails, PermissionType.ADD_EDIT_DELETE_CLUSTERS)) .thenReturn(false); when(handleDbRequestsJdbc.addNewCluster(any(KwClusters.class))) @@ -720,7 +741,8 @@ void addNewClusterFailed() { authorities = {"ADMIN", "USER"}) void addNewClusterNameExists() { int tenantId = 101; - when(commonUtilsService.isNotAuthorizedUser(any(), any(PermissionType.class))) + when(commonUtilsService.isNotAuthorizedUser( + userDetails, PermissionType.ADD_EDIT_DELETE_CLUSTERS)) .thenReturn(false); when(manageDatabase.getClusters(KafkaClustersType.ALL, tenantId)) @@ -805,7 +827,6 @@ void getSyncEnvs() { username = "james", authorities = {"ADMIN", "USER"}) void getEnvDetailsUnauthorized() { - when(commonUtilsService.isNotAuthorizedUser(any(), any(PermissionType.class))).thenReturn(true); when(commonUtilsService.getEnvsFromUserId(anyString())).thenReturn(new HashSet<>()); EnvModelResponse result = service.getEnvDetails("env id", "cluster type"); assertThat(result).isNull(); @@ -818,7 +839,7 @@ void getEnvDetailsUnauthorized() { void getEnvDetails() { int tenantId = 101; String envId = "1"; - when(commonUtilsService.isNotAuthorizedUser(any(), any(PermissionType.class))) + when(commonUtilsService.isNotAuthorizedUser(userDetails, PermissionType.ADD_EDIT_DELETE_ENVS)) .thenReturn(false); when(handleDbRequestsJdbc.getEnvDetails(envId, tenantId)) @@ -857,7 +878,8 @@ void getClusters() { List.of( buildEnv("1", tenantId, "env1", KafkaClustersType.KAFKA, 1), buildEnv("2", tenantId, "env2", KafkaClustersType.KAFKA, 2))); - when(commonUtilsService.isNotAuthorizedUser(any(), any(PermissionType.class))) + when(commonUtilsService.isNotAuthorizedUser( + userDetails, PermissionType.ADD_EDIT_DELETE_CLUSTERS)) .thenReturn(false); List result = service.getClusters(KafkaClustersType.KAFKA.value); @@ -879,7 +901,6 @@ void getMyTenantInfo() { KwTenants tenant = buildTenants(tenantId); when(handleDbRequestsJdbc.getMyTenants(tenantId)).thenReturn(Optional.of(tenant)); - when(commonUtilsService.isNotAuthorizedUser(any(), any(PermissionType.class))).thenReturn(true); KwTenantModel result = service.getMyTenantInfo(); assertThat(result.getTenantName()).isEqualTo(tenant.getTenantName()); assertThat(result.getContactPerson()).isEqualTo(tenant.getContactPerson()); @@ -980,7 +1001,6 @@ void getClusterDetails() { username = "james", authorities = {"ADMIN", "USER"}) void updateTenantUnauthorized() throws KlawException { - when(commonUtilsService.isNotAuthorizedUser(any(), any(PermissionType.class))).thenReturn(true); ApiResponse result = service.updateTenant(new KwTenantModel()); assertThat(result).isEqualTo(ApiResponse.NOT_AUTHORIZED); } @@ -992,7 +1012,8 @@ void updateTenantUnauthorized() throws KlawException { void updateTenantFailed() throws KlawException { int tenantId = 101; when(commonUtilsService.getTenantId(any())).thenReturn(tenantId); - when(commonUtilsService.isNotAuthorizedUser(any(), any(PermissionType.class))) + when(commonUtilsService.isNotAuthorizedUser( + userDetails, PermissionType.UPDATE_DELETE_MY_TENANT)) .thenReturn(false); when(handleDbRequestsJdbc.addNewTenant(any(KwTenants.class))) .thenReturn("failed to add new tenant"); @@ -1008,7 +1029,8 @@ void updateTenantFailed() throws KlawException { void updateTenant() throws KlawException { int tenantId = 101; when(commonUtilsService.getTenantId(any())).thenReturn(tenantId); - when(commonUtilsService.isNotAuthorizedUser(any(), any(PermissionType.class))) + when(commonUtilsService.isNotAuthorizedUser( + userDetails, PermissionType.UPDATE_DELETE_MY_TENANT)) .thenReturn(false); when(handleDbRequestsJdbc.addNewTenant(any(KwTenants.class))) .thenReturn(ApiResultStatus.SUCCESS.value); @@ -1026,7 +1048,6 @@ void updateTenant() throws KlawException { void getClusterInfoFromEnvUnauthorized() { int tenantId = 101; when(commonUtilsService.getTenantId(any())).thenReturn(tenantId); - when(commonUtilsService.isNotAuthorizedUser(any(), any(PermissionType.class))).thenReturn(true); when(commonUtilsService.getEnvsFromUserId(anyString())).thenReturn(new HashSet<>()); ClusterInfo result = service.getClusterInfoFromEnv("1", KafkaClustersType.KAFKA.value); assertThat(result).isNull(); @@ -1040,7 +1061,7 @@ void getClusterInfoFromEnv() { int tenantId = 101; String envId = "1"; when(commonUtilsService.getTenantId(any())).thenReturn(tenantId); - when(commonUtilsService.isNotAuthorizedUser(any(), any(PermissionType.class))) + when(commonUtilsService.isNotAuthorizedUser(userDetails, PermissionType.ADD_EDIT_DELETE_ENVS)) .thenReturn(false); when(handleDbRequestsJdbc.getEnvDetails(envId, tenantId)) .thenReturn(buildEnv(envId, tenantId, "env1", KafkaClustersType.KAFKA, 1)); @@ -1055,7 +1076,6 @@ void getClusterInfoFromEnv() { username = "james", authorities = {"ADMIN", "USER"}) void deleteClusterUnauthorized() throws KlawException { - when(commonUtilsService.isNotAuthorizedUser(any(), any(PermissionType.class))).thenReturn(true); ApiResponse result = service.deleteCluster("cluster id"); assertThat(result).isEqualTo(ApiResponse.NOT_AUTHORIZED); } @@ -1068,7 +1088,8 @@ void deleteClusterNotAllowed() throws KlawException { int tenantId = 101; String clusterId = "1"; when(commonUtilsService.getTenantId(any())).thenReturn(tenantId); - when(commonUtilsService.isNotAuthorizedUser(any(), any(PermissionType.class))) + when(commonUtilsService.isNotAuthorizedUser( + userDetails, PermissionType.ADD_EDIT_DELETE_CLUSTERS)) .thenReturn(false); when(manageDatabase.getAllEnvList(tenantId)) .thenReturn(List.of(buildEnv("1", tenantId, "env1", KafkaClustersType.KAFKA, 1))); @@ -1085,7 +1106,8 @@ void deleteClusterFailed() throws KlawException { int tenantId = 101; String clusterId = "2"; when(commonUtilsService.getTenantId(any())).thenReturn(tenantId); - when(commonUtilsService.isNotAuthorizedUser(any(), any(PermissionType.class))) + when(commonUtilsService.isNotAuthorizedUser( + userDetails, PermissionType.ADD_EDIT_DELETE_CLUSTERS)) .thenReturn(false); when(manageDatabase.getAllEnvList(tenantId)) .thenReturn(List.of(buildEnv("1", tenantId, "env1", KafkaClustersType.KAFKA, 1))); @@ -1103,7 +1125,8 @@ void deleteCluster() throws KlawException { int tenantId = 101; String clusterId = "2"; when(commonUtilsService.getTenantId(any())).thenReturn(tenantId); - when(commonUtilsService.isNotAuthorizedUser(any(), any(PermissionType.class))) + when(commonUtilsService.isNotAuthorizedUser( + userDetails, PermissionType.ADD_EDIT_DELETE_CLUSTERS)) .thenReturn(false); when(manageDatabase.getAllEnvList(tenantId)) .thenReturn(List.of(buildEnv("1", tenantId, "env1", KafkaClustersType.KAFKA, 1))); diff --git a/core/src/test/java/io/aiven/klaw/service/KafkaConnectControllerServiceTest.java b/core/src/test/java/io/aiven/klaw/service/KafkaConnectControllerServiceTest.java index 8f5bfaaf2..7b834ed0f 100644 --- a/core/src/test/java/io/aiven/klaw/service/KafkaConnectControllerServiceTest.java +++ b/core/src/test/java/io/aiven/klaw/service/KafkaConnectControllerServiceTest.java @@ -51,10 +51,6 @@ import org.mockito.ArgumentCaptor; import org.mockito.Captor; import org.mockito.Mock; -import org.mockito.Mockito; -import org.springframework.security.core.Authentication; -import org.springframework.security.core.context.SecurityContext; -import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.test.context.junit.jupiter.SpringExtension; import org.springframework.test.util.ReflectionTestUtils; @@ -109,15 +105,8 @@ public void setUp() throws Exception { rolesPermissionsControllerService); when(manageDatabase.getHandleDbRequests()).thenReturn(handleDbRequests); - loginMock(); - } - - private void loginMock() { - Authentication authentication = Mockito.mock(Authentication.class); - SecurityContext securityContext = Mockito.mock(SecurityContext.class); - when(securityContext.getAuthentication()).thenReturn(authentication); - when(authentication.getPrincipal()).thenReturn(userDetails); - SecurityContextHolder.setContext(securityContext); + when(commonUtilsService.isNotAuthorizedUser(any(), any(PermissionType.class))).thenReturn(true); + when(commonUtilsService.getPrincipal()).thenReturn(userDetails); } @Test @@ -127,7 +116,8 @@ public void createConnectorRequest() throws KlawException { resultMap.put("result", ApiResultStatus.SUCCESS.value); stubUserInfo(); - when(commonUtilsService.isNotAuthorizedUser(any(), any(PermissionType.class))) + when(commonUtilsService.isNotAuthorizedUser( + userDetails, PermissionType.REQUEST_CREATE_CONNECTORS)) .thenReturn(false); when(commonUtilsService.getTenantId(anyString())).thenReturn(TENANT_ID); when(tenantConfig.get(anyInt())).thenReturn(tenantConfigModel); @@ -155,7 +145,8 @@ public void createConnectorRequestInvalidJsonConfig() { KafkaConnectorRequestModel kafkaConnectorRequestModel = getConnectRequestModel(); kafkaConnectorRequestModel.setConnectorConfig("plain string"); // Invalid json stubUserInfo(); - when(commonUtilsService.isNotAuthorizedUser(any(), any(PermissionType.class))) + when(commonUtilsService.isNotAuthorizedUser( + userDetails, PermissionType.REQUEST_CREATE_CONNECTORS)) .thenReturn(false); when(handleDbRequests.requestForConnector(any())) .thenThrow(new RuntimeException("Unrecognized token")); @@ -173,7 +164,8 @@ public void createConnectorRequestParameterTopicsDoesntExist() throws KlawExcept KafkaConnectorRequestModel kafkaConnectorRequestModel = getConnectRequestModel(); kafkaConnectorRequestModel.setConnectorConfig(getInvalidValidConnConfig()); stubUserInfo(); - when(commonUtilsService.isNotAuthorizedUser(any(), any(PermissionType.class))) + when(commonUtilsService.isNotAuthorizedUser( + userDetails, PermissionType.REQUEST_CREATE_CONNECTORS)) .thenReturn(false); ApiResponse apiResponse = @@ -189,7 +181,8 @@ public void createConnectorRequestParameterTopicsTopicRegexExist() throws KlawEx KafkaConnectorRequestModel kafkaConnectorRequestModel = getConnectRequestModel(); kafkaConnectorRequestModel.setConnectorConfig(getInvalidValidConnConfigTopicsTopicsRegex()); stubUserInfo(); - when(commonUtilsService.isNotAuthorizedUser(any(), any(PermissionType.class))) + when(commonUtilsService.isNotAuthorizedUser( + userDetails, PermissionType.REQUEST_CREATE_CONNECTORS)) .thenReturn(false); ApiResponse apiResponse = @@ -204,8 +197,6 @@ public void createClaimConnectorRequest() throws KlawException { Set envListIds = new HashSet<>(); envListIds.add("1"); stubUserInfo(); - when(commonUtilsService.isNotAuthorizedUser(any(), any(PermissionType.class))) - .thenReturn(false); when(commonUtilsService.getTenantId(any())).thenReturn(TENANT_ID); when(handleDbRequests.getConnectorsFromName(eq("ConnectorOne"), eq(TENANT_ID))) .thenReturn(List.of(getKwKafkaConnector())); @@ -227,8 +218,6 @@ public void createClaimConnectorRequestAlreadyExists() throws KlawException { Set envListIds = new HashSet<>(); envListIds.add("DEV"); stubUserInfo(); - when(commonUtilsService.isNotAuthorizedUser(any(), any(PermissionType.class))) - .thenReturn(false); when(commonUtilsService.getTenantId(any())).thenReturn(TENANT_ID); when(handleDbRequests.existsConnectorRequest( "ConnectorOne", "1", RequestStatus.CREATED.value, TENANT_ID)) @@ -247,8 +236,6 @@ public void getRequests_OrderBy_NEWEST_FIRST() throws KlawException { envListIds.add("DEV"); stubUserInfo(); when(commonUtilsService.getTenantId(any())).thenReturn(TENANT_ID); - when(commonUtilsService.isNotAuthorizedUser(any(), any(PermissionType.class))) - .thenReturn(false); when(handleDbRequests.getAllConnectorRequests( anyString(), @@ -291,8 +278,6 @@ public void getRequests_OrderBy_OLDEST_FIRST() throws KlawException { envListIds.add("DEV"); stubUserInfo(); when(commonUtilsService.getTenantId(any())).thenReturn(TENANT_ID); - when(commonUtilsService.isNotAuthorizedUser(any(), any(PermissionType.class))) - .thenReturn(false); when(handleDbRequests.getAllConnectorRequests( anyString(), @@ -335,8 +320,6 @@ public void getRequests_IsOnlyMyRequests() throws KlawException { envListIds.add("DEV"); stubUserInfo(); when(commonUtilsService.getTenantId(any())).thenReturn(TENANT_ID); - when(commonUtilsService.isNotAuthorizedUser(any(), any(PermissionType.class))) - .thenReturn(false); when(handleDbRequests.getAllConnectorRequests( anyString(), @@ -380,8 +363,6 @@ public void getRequests_() throws KlawException { envListIds.add("DEV"); stubUserInfo(); when(commonUtilsService.getTenantId(any())).thenReturn(TENANT_ID); - when(commonUtilsService.isNotAuthorizedUser(any(), any(PermissionType.class))) - .thenReturn(false); when(handleDbRequests.getAllConnectorRequests( anyString(), @@ -425,8 +406,6 @@ public void getClaimRequests_WhereConnectorIsDeleted() throws KlawException { envListIds.add("DEV"); stubUserInfo(); when(commonUtilsService.getTenantId(any())).thenReturn(TENANT_ID); - when(commonUtilsService.isNotAuthorizedUser(any(), any(PermissionType.class))) - .thenReturn(false); List connectorRequests = generateKafkaConnectorRequests(9); connectorRequests.addAll(generateKafkaConnectorRequests(1, 7, RequestOperationType.CLAIM)); when(handleDbRequests.getAllConnectorRequests( @@ -473,8 +452,6 @@ public void getClaimRequests_WhereConnectorIsNotDeleted() throws KlawException { envListIds.add("DEV"); stubUserInfo(); when(commonUtilsService.getTenantId(any())).thenReturn(TENANT_ID); - when(commonUtilsService.isNotAuthorizedUser(any(), any(PermissionType.class))) - .thenReturn(false); List connectorRequests = generateKafkaConnectorRequests(9); connectorRequests.addAll(generateKafkaConnectorRequests(1, 7, RequestOperationType.CLAIM)); when(handleDbRequests.getAllConnectorRequests( @@ -524,8 +501,6 @@ public void getConnectorOverview_WithNoParams_returnsNull() throws KlawException envListIds.add("DEV"); stubUserInfo(); when(commonUtilsService.getTenantId(any())).thenReturn(TENANT_ID); - when(commonUtilsService.isNotAuthorizedUser(any(), any(PermissionType.class))) - .thenReturn(false); when(commonUtilsService.getTeamId(eq(USERNAME))).thenReturn(8); when(handleDbRequests.getConnectors(eq(CONNECTOR_NAME), eq(TENANT_ID))) .thenReturn(generateKafkaConnectors(3)); @@ -542,8 +517,6 @@ public void getConnectorOverview_WithAllEnvs_noPromotionOrderSet() throws KlawEx envListIds.add("DEV"); stubUserInfo(); when(commonUtilsService.getTenantId(any())).thenReturn(TENANT_ID); - when(commonUtilsService.isNotAuthorizedUser(any(), any(PermissionType.class))) - .thenReturn(false); when(commonUtilsService.getTeamId(eq(USERNAME))).thenReturn(8); when(handleDbRequests.getConnectors(eq(CONNECTOR_NAME), eq(TENANT_ID))) .thenReturn(generateKafkaConnectors(3)); @@ -588,8 +561,6 @@ public void getConnectorOverview_WithAllEnvs() throws KlawException { envListIds.add("DEV"); stubUserInfo(); when(commonUtilsService.getTenantId(any())).thenReturn(TENANT_ID); - when(commonUtilsService.isNotAuthorizedUser(any(), any(PermissionType.class))) - .thenReturn(false); when(commonUtilsService.getTeamId(eq(USERNAME))).thenReturn(8); when(handleDbRequests.getConnectors(eq(CONNECTOR_NAME), eq(TENANT_ID))) .thenReturn(generateKafkaConnectors(3)); @@ -621,8 +592,6 @@ public void getConnectorOverview_WithOneEnv() throws KlawException { envListIds.add("DEV"); stubUserInfo(); when(commonUtilsService.getTenantId(any())).thenReturn(TENANT_ID); - when(commonUtilsService.isNotAuthorizedUser(any(), any(PermissionType.class))) - .thenReturn(false); when(commonUtilsService.getTeamId(eq(USERNAME))).thenReturn(8); when(handleDbRequests.getConnectors(eq(CONNECTOR_NAME), eq(TENANT_ID))) .thenReturn(generateKafkaConnectors(3)); @@ -655,8 +624,6 @@ public void getConnectorOverview_WithOneEnvAndPromotion() throws KlawException { envListIds.add("DEV"); stubUserInfo(); when(commonUtilsService.getTenantId(any())).thenReturn(TENANT_ID); - when(commonUtilsService.isNotAuthorizedUser(any(), any(PermissionType.class))) - .thenReturn(false); when(commonUtilsService.getTeamId(eq(USERNAME))).thenReturn(8); when(handleDbRequests.getConnectors(eq(CONNECTOR_NAME), eq(TENANT_ID))) .thenReturn(generateKafkaConnectors(2)); @@ -690,8 +657,6 @@ public void getConnectorOverview_WithOneEnvAndNoPromotionForBaseEnv() throws Kla envListIds.add("DEV"); stubUserInfo(); when(commonUtilsService.getTenantId(any())).thenReturn(TENANT_ID); - when(commonUtilsService.isNotAuthorizedUser(any(), any(PermissionType.class))) - .thenReturn(false); when(commonUtilsService.getTeamId(eq(USERNAME))).thenReturn(8); when(handleDbRequests.getConnectors(eq(CONNECTOR_NAME), eq(TENANT_ID))) .thenReturn(generateKafkaConnectors(2)); @@ -775,8 +740,6 @@ public void getConnectorOverview_WithHighestEnvAndConnectorOwnerSet() throws Kla envListIds.add("DEV"); stubUserInfo(); when(commonUtilsService.getTenantId(any())).thenReturn(TENANT_ID); - when(commonUtilsService.isNotAuthorizedUser(any(), any(PermissionType.class))) - .thenReturn(false); when(commonUtilsService.getTeamId(eq(USERNAME))).thenReturn(8); when(handleDbRequests.getConnectors(eq(CONNECTOR_NAME), eq(TENANT_ID))) .thenReturn(generateKafkaConnectors(2)); @@ -810,8 +773,6 @@ public void getConnectorOverview_WithRequestsOpen() throws KlawException { envListIds.add("DEV"); stubUserInfo(); when(commonUtilsService.getTenantId(any())).thenReturn(TENANT_ID); - when(commonUtilsService.isNotAuthorizedUser(any(), any(PermissionType.class))) - .thenReturn(false); when(commonUtilsService.getTeamId(eq(USERNAME))).thenReturn(8); when(handleDbRequests.getConnectors(eq(CONNECTOR_NAME), eq(TENANT_ID))) .thenReturn(generateKafkaConnectors(2)); @@ -855,8 +816,6 @@ public void getConnectorOverview_WithNoRequestsOpen() throws KlawException { envListIds.add("DEV"); stubUserInfo(); when(commonUtilsService.getTenantId(any())).thenReturn(TENANT_ID); - when(commonUtilsService.isNotAuthorizedUser(any(), any(PermissionType.class))) - .thenReturn(false); when(commonUtilsService.getTeamId(eq(USERNAME))).thenReturn(8); when(handleDbRequests.getConnectors(eq(CONNECTOR_NAME), eq(TENANT_ID))) .thenReturn(generateKafkaConnectors(2)); @@ -897,8 +856,6 @@ public void getConnectorOverviewPerEnv_ConnectorDoesNotExist() { envListIds.add("DEV"); stubUserInfo(); when(commonUtilsService.getTenantId(any())).thenReturn(TENANT_ID); - when(commonUtilsService.isNotAuthorizedUser(any(), any(PermissionType.class))) - .thenReturn(false); when(commonUtilsService.getTeamId(eq(USERNAME))).thenReturn(8); when(handleDbRequests.getConnectors(eq(CONNECTOR_NAME), eq(TENANT_ID))) .thenReturn(generateKafkaConnectors(2)); @@ -923,8 +880,6 @@ public void getConnectorOverviewPerEnv_ConnectorOwnedByDifferentTeam() { envListIds.add("DEV"); stubUserInfo(); when(commonUtilsService.getTenantId(any())).thenReturn(TENANT_ID); - when(commonUtilsService.isNotAuthorizedUser(any(), any(PermissionType.class))) - .thenReturn(false); when(commonUtilsService.getTeamId(eq(USERNAME))).thenReturn(8); when(handleDbRequests.getConnectors(eq(CONNECTOR_NAME), eq(TENANT_ID))) .thenReturn(generateKafkaConnectors(2)); @@ -954,8 +909,6 @@ public void getConnectorOverview_WithClaimRequestsOpenAndNoOtherRequestOpen() envListIds.add("DEV"); stubUserInfo(); when(commonUtilsService.getTenantId(any())).thenReturn(TENANT_ID); - when(commonUtilsService.isNotAuthorizedUser(any(), any(PermissionType.class))) - .thenReturn(false); when(commonUtilsService.getTeamId(eq(USERNAME))).thenReturn(8); when(handleDbRequests.getConnectors(eq(CONNECTOR_NAME), eq(TENANT_ID))) .thenReturn(generateKafkaConnectors(2)); @@ -1005,8 +958,6 @@ public void getConnectorOverview_WithPromotionRequestsOpen() throws KlawExceptio envListIds.add("DEV"); stubUserInfo(); when(commonUtilsService.getTenantId(any())).thenReturn(TENANT_ID); - when(commonUtilsService.isNotAuthorizedUser(any(), any(PermissionType.class))) - .thenReturn(false); when(commonUtilsService.getTeamId(eq(USERNAME))).thenReturn(8); when(handleDbRequests.getConnectors(eq(CONNECTOR_NAME), eq(TENANT_ID))) .thenReturn(generateKafkaConnectors(2)); @@ -1158,7 +1109,7 @@ private String getInvalidValidConnConfigTopicsTopicsRegex() { private void stubUserInfo() { when(handleDbRequests.getUsersInfo(anyString())).thenReturn(userInfo); when(userInfo.getTeamId()).thenReturn(TENANT_ID); - when(mailService.getUserName(any())).thenReturn(USERNAME); + when(mailService.getUserName(userDetails)).thenReturn(USERNAME); Env e = new Env(); e.setId("1"); e.setName("DEV"); diff --git a/core/src/test/java/io/aiven/klaw/service/KafkaConnectSyncControllerServiceTest.java b/core/src/test/java/io/aiven/klaw/service/KafkaConnectSyncControllerServiceTest.java index efa5da0e2..a2ab46fe0 100644 --- a/core/src/test/java/io/aiven/klaw/service/KafkaConnectSyncControllerServiceTest.java +++ b/core/src/test/java/io/aiven/klaw/service/KafkaConnectSyncControllerServiceTest.java @@ -38,10 +38,6 @@ import org.junit.jupiter.api.TestMethodOrder; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; -import org.mockito.Mockito; -import org.springframework.security.core.Authentication; -import org.springframework.security.core.context.SecurityContext; -import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.test.context.junit.jupiter.SpringExtension; import org.springframework.test.util.ReflectionTestUtils; @@ -98,7 +94,8 @@ public void setUp() throws Exception { kafkaConnectSyncControllerService, "clusterApiService", clusterApiService); when(manageDatabase.getHandleDbRequests()).thenReturn(handleDbRequests); - loginMock(); + when(commonUtilsService.getPrincipal()).thenReturn(userDetails); + when(commonUtilsService.isNotAuthorizedUser(any(), any(PermissionType.class))).thenReturn(true); } private void environmentSetUp() { @@ -112,18 +109,10 @@ private void environmentSetUp() { when(manageDatabase.getKafkaEnvList(anyInt())).thenReturn(List.of(env, test)); } - private void loginMock() { - Authentication authentication = Mockito.mock(Authentication.class); - SecurityContext securityContext = Mockito.mock(SecurityContext.class); - when(securityContext.getAuthentication()).thenReturn(authentication); - when(authentication.getPrincipal()).thenReturn(userDetails); - SecurityContextHolder.setContext(securityContext); - } - private void stubUserInfo() { when(handleDbRequests.getUsersInfo(anyString())).thenReturn(userInfo); when(userInfo.getTeamId()).thenReturn(101); - when(mailService.getUserName(any())).thenReturn(USERNAME); + when(mailService.getUserName(userDetails)).thenReturn(USERNAME); when(commonUtilsService.getTenantId(eq(USERNAME))).thenReturn(TENANT_ID); } @@ -134,7 +123,7 @@ public void updateSyncConnectorsSuccess() throws KlawException { when(manageDatabase.getTenantConfig()).thenReturn(tenantConfig); when(tenantConfig.get(anyInt())).thenReturn(tenantConfigModel); when(tenantConfigModel.getBaseSyncEnvironment()).thenReturn("1"); - when(commonUtilsService.isNotAuthorizedUser(any(), any(PermissionType.class))) + when(commonUtilsService.isNotAuthorizedUser(userDetails, PermissionType.SYNC_CONNECTORS)) .thenReturn(false); when(commonUtilsService.getEnvsFromUserId(anyString())) .thenReturn(new HashSet<>(Collections.singletonList("1"))); diff --git a/core/src/test/java/io/aiven/klaw/service/OperationalRequestsServiceTest.java b/core/src/test/java/io/aiven/klaw/service/OperationalRequestsServiceTest.java index 3c1abba10..85fda15b1 100644 --- a/core/src/test/java/io/aiven/klaw/service/OperationalRequestsServiceTest.java +++ b/core/src/test/java/io/aiven/klaw/service/OperationalRequestsServiceTest.java @@ -41,10 +41,6 @@ import org.mockito.ArgumentCaptor; import org.mockito.Captor; import org.mockito.Mock; -import org.mockito.Mockito; -import org.springframework.security.core.Authentication; -import org.springframework.security.core.context.SecurityContext; -import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.test.context.junit.jupiter.SpringExtension; @@ -94,15 +90,8 @@ public void setUp() throws Exception { env.setName("DEV"); when(manageDatabase.getHandleDbRequests()).thenReturn(handleDbRequests); - loginMock(); - } - - private void loginMock() { - Authentication authentication = Mockito.mock(Authentication.class); - SecurityContext securityContext = Mockito.mock(SecurityContext.class); - when(securityContext.getAuthentication()).thenReturn(authentication); - when(authentication.getPrincipal()).thenReturn(userDetails); - SecurityContextHolder.setContext(securityContext); + when(commonUtilsService.getPrincipal()).thenReturn(userDetails); + when(commonUtilsService.isNotAuthorizedUser(any(), any(PermissionType.class))).thenReturn(true); } @Test @@ -110,7 +99,8 @@ private void loginMock() { public void createConsumerOffsetsResetRequestDoesNotOwnGroup() throws KlawNotAuthorizedException { ConsumerOffsetResetRequestModel consumerOffsetResetRequestModel = utilMethods.getConsumerOffsetResetRequest(1001); - when(commonUtilsService.isNotAuthorizedUser(any(), any(PermissionType.class))) + when(commonUtilsService.isNotAuthorizedUser( + userDetails, PermissionType.REQUEST_CREATE_SUBSCRIPTIONS)) .thenReturn(false); ApiResponse apiResponse = @@ -125,7 +115,8 @@ public void createRequestEmptyResetTimeForDateTimeResetType() throws KlawNotAuth ConsumerOffsetResetRequestModel consumerOffsetResetRequestModel = utilMethods.getConsumerOffsetResetRequest(1001); consumerOffsetResetRequestModel.setOffsetResetType(OffsetResetType.TO_DATE_TIME); - when(commonUtilsService.isNotAuthorizedUser(any(), any(PermissionType.class))) + when(commonUtilsService.isNotAuthorizedUser( + userDetails, PermissionType.REQUEST_CREATE_SUBSCRIPTIONS)) .thenReturn(false); when(handleDbRequests.getSyncAcls(anyString(), anyString(), anyInt(), anyString(), anyInt())) .thenReturn(utilMethods.getAcls()); @@ -141,7 +132,8 @@ public void createRequestEmptyResetTimeForDateTimeResetType() throws KlawNotAuth public void createRequestWhichAlreadyExists() throws KlawNotAuthorizedException { ConsumerOffsetResetRequestModel consumerOffsetResetRequestModel = utilMethods.getConsumerOffsetResetRequest(1001); - when(commonUtilsService.isNotAuthorizedUser(any(), any(PermissionType.class))) + when(commonUtilsService.isNotAuthorizedUser( + userDetails, PermissionType.REQUEST_CREATE_SUBSCRIPTIONS)) .thenReturn(false); when(handleDbRequests.getSyncAcls(anyString(), anyString(), anyInt(), anyString(), anyInt())) .thenReturn(utilMethods.getAcls()); @@ -169,7 +161,8 @@ public void createRequestWhichAlreadyExists() throws KlawNotAuthorizedException public void createRequestSuccess() throws KlawNotAuthorizedException { ConsumerOffsetResetRequestModel consumerOffsetResetRequestModel = utilMethods.getConsumerOffsetResetRequest(1001); - when(commonUtilsService.isNotAuthorizedUser(any(), any(PermissionType.class))) + when(commonUtilsService.isNotAuthorizedUser( + userDetails, PermissionType.REQUEST_CREATE_SUBSCRIPTIONS)) .thenReturn(false); when(handleDbRequests.getSyncAcls(anyString(), anyString(), anyInt(), anyString(), anyInt())) .thenReturn(utilMethods.getAcls()); @@ -203,7 +196,8 @@ public void approveOperationalRequestsSuccess() throws KlawException { UtilMethods.getOffsetsTimingMapMap(); ApiResponse apiResponse = ApiResponse.builder().success(true).data(offsetPositionsBeforeAndAfter).build(); - when(commonUtilsService.isNotAuthorizedUser(any(), any(PermissionType.class))) + when(commonUtilsService.isNotAuthorizedUser( + userDetails, PermissionType.APPROVE_OPERATIONAL_CHANGES)) .thenReturn(false); when(commonUtilsService.getTenantId(anyString())).thenReturn(101); when(mailService.getCurrentUserName()).thenReturn("testuser"); @@ -220,7 +214,8 @@ public void approveOperationalRequestsSuccess() throws KlawException { @Order(6) public void approveOperationalRequestsFailure() throws KlawException { ApiResponse apiResponse = ApiResponse.builder().success(false).build(); - when(commonUtilsService.isNotAuthorizedUser(any(), any(PermissionType.class))) + when(commonUtilsService.isNotAuthorizedUser( + userDetails, PermissionType.APPROVE_OPERATIONAL_CHANGES)) .thenReturn(false); when(commonUtilsService.getTenantId(anyString())).thenReturn(101); when(mailService.getCurrentUserName()).thenReturn("testuser"); diff --git a/core/src/test/java/io/aiven/klaw/service/RequestStatisticsServiceTest.java b/core/src/test/java/io/aiven/klaw/service/RequestStatisticsServiceTest.java index fcf371d3e..9f9555364 100644 --- a/core/src/test/java/io/aiven/klaw/service/RequestStatisticsServiceTest.java +++ b/core/src/test/java/io/aiven/klaw/service/RequestStatisticsServiceTest.java @@ -1,7 +1,6 @@ package io.aiven.klaw.service; import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyInt; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.ArgumentMatchers.eq; @@ -24,10 +23,6 @@ import org.junit.jupiter.api.TestMethodOrder; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; -import org.mockito.Mockito; -import org.springframework.security.core.Authentication; -import org.springframework.security.core.context.SecurityContext; -import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.test.context.junit.jupiter.SpringExtension; import org.springframework.test.util.ReflectionTestUtils; @@ -56,7 +51,7 @@ void setUp() { requestStatisticsService, "commonUtilsService", commonUtilsService); ReflectionTestUtils.setField(requestStatisticsService, "mailService", mailService); when(manageDatabase.getHandleDbRequests()).thenReturn(handleDbRequests); - loginMock(); + when(commonUtilsService.getPrincipal()).thenReturn(userDetails); } @Test @@ -124,18 +119,10 @@ public void getRequestsCountOverview() { .hasSize(2); } - private void loginMock() { - Authentication authentication = Mockito.mock(Authentication.class); - SecurityContext securityContext = Mockito.mock(SecurityContext.class); - when(securityContext.getAuthentication()).thenReturn(authentication); - when(authentication.getPrincipal()).thenReturn(userDetails); - SecurityContextHolder.setContext(securityContext); - } - private void stubUserInfo() { when(handleDbRequests.getUsersInfo(anyString())).thenReturn(userInfo); when(userInfo.getTeamId()).thenReturn(101); - when(mailService.getUserName(any())).thenReturn("kwusera"); + when(mailService.getUserName(userDetails)).thenReturn("kwusera"); when(mailService.getCurrentUserName()).thenReturn("kwusera"); } } diff --git a/core/src/test/java/io/aiven/klaw/service/SchemaRegistryControllerServiceTest.java b/core/src/test/java/io/aiven/klaw/service/SchemaRegistryControllerServiceTest.java index 13dc0e2fb..ddeb97005 100644 --- a/core/src/test/java/io/aiven/klaw/service/SchemaRegistryControllerServiceTest.java +++ b/core/src/test/java/io/aiven/klaw/service/SchemaRegistryControllerServiceTest.java @@ -45,12 +45,8 @@ import org.mockito.ArgumentCaptor; import org.mockito.Captor; import org.mockito.Mock; -import org.mockito.Mockito; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; -import org.springframework.security.core.Authentication; -import org.springframework.security.core.context.SecurityContext; -import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.test.context.support.WithMockUser; import org.springframework.test.context.junit.jupiter.SpringExtension; @@ -108,19 +104,12 @@ public void setUp() throws Exception { rolesPermissionsControllerService); when(manageDatabase.getHandleDbRequests()).thenReturn(handleDbRequests); - loginMock(); Boolean validateOnSave = true; ReflectionTestUtils.setField( schemaRegistryControllerService, "validateCompatiblityOnSave", validateOnSave); utilMethods = new UtilMethods(); - } - - private void loginMock() { - Authentication authentication = Mockito.mock(Authentication.class); - SecurityContext securityContext = Mockito.mock(SecurityContext.class); - when(securityContext.getAuthentication()).thenReturn(authentication); - when(authentication.getPrincipal()).thenReturn(userDetails); - SecurityContextHolder.setContext(securityContext); + when(commonUtilsService.getPrincipal()).thenReturn(userDetails); + when(commonUtilsService.isNotAuthorizedUser(any(), any(PermissionType.class))).thenReturn(true); } @Test @@ -147,6 +136,9 @@ public void getSchemaRequests() { when(handleDbRequests.getAllUsersInfoForTeam(anyInt(), anyInt())).thenReturn(List.of(userInfo)); when(handleDbRequests.getEnvDetails(anyString(), anyInt())).thenReturn(this.env); when(manageDatabase.getTeamNameFromTeamId(anyInt(), anyInt())).thenReturn("teamname"); + when(commonUtilsService.isNotAuthorizedUser( + userDetails, PermissionType.APPROVE_ALL_REQUESTS_TEAMS)) + .thenReturn(false); List listReqs = schemaRegistryControllerService.getSchemaRequests( @@ -171,6 +163,8 @@ public void deleteSchemaRequestsSuccess() throws KlawException { stubUserInfo(); when(handleDbRequests.deleteSchemaRequest(anyInt(), anyString(), anyInt())) .thenReturn(ApiResultStatus.SUCCESS.value); + when(commonUtilsService.isNotAuthorizedUser(userDetails, PermissionType.REQUEST_DELETE_SCHEMAS)) + .thenReturn(false); ApiResponse resultResp = schemaRegistryControllerService.deleteSchemaRequests("" + schemaReqId); assertThat(resultResp.getMessage()).isEqualTo(ApiResultStatus.SUCCESS.value); } @@ -183,11 +177,14 @@ public void deleteSchemaRequestsFailure() { stubUserInfo(); when(handleDbRequests.deleteSchemaRequest(anyInt(), anyString(), anyInt())) .thenThrow(new RuntimeException("Error from Schema upload")); - try { - schemaRegistryControllerService.deleteSchemaRequests("" + schemaReqId); - } catch (KlawException e) { - assertThat(e.getMessage()).contains("Error from Schema upload"); - } + when(commonUtilsService.isNotAuthorizedUser(userDetails, PermissionType.REQUEST_DELETE_SCHEMAS)) + .thenReturn(false); + + KlawException ex = + assertThrows( + KlawException.class, + () -> schemaRegistryControllerService.deleteSchemaRequests("" + schemaReqId)); + assertThat(ex.getMessage()).contains("Error from Schema upload"); } @Test @@ -223,7 +220,7 @@ public void execSchemaRequestsSuccess() throws KlawException { when(commonUtilsService.getEnvsFromUserId(anyString())) .thenReturn(new HashSet<>(Collections.singletonList("1"))); when(commonUtilsService.getTenantId(anyString())).thenReturn(101); - when(commonUtilsService.isNotAuthorizedUser(any(), any(PermissionType.class))) + when(commonUtilsService.isNotAuthorizedUser(userDetails, PermissionType.APPROVE_SCHEMAS)) .thenReturn(false); ApiResponse resultResp = schemaRegistryControllerService.execSchemaRequests("" + schemaReqId); @@ -252,7 +249,7 @@ public void execSchemaRequestsFailure1() throws KlawException { when(commonUtilsService.getEnvsFromUserId(anyString())) .thenReturn(new HashSet<>(Collections.singletonList("1"))); when(commonUtilsService.getTenantId(anyString())).thenReturn(101); - when(commonUtilsService.isNotAuthorizedUser(any(), any(PermissionType.class))) + when(commonUtilsService.isNotAuthorizedUser(userDetails, PermissionType.APPROVE_SCHEMAS)) .thenReturn(false); ApiResponse resultResp = schemaRegistryControllerService.execSchemaRequests("" + schemaReqId); @@ -286,7 +283,7 @@ public void execSchemaRequestsFailure2() { when(manageDatabase.getTeamsAndAllowedEnvs(anyInt(), anyInt())) .thenReturn(Collections.singletonList("1")); when(commonUtilsService.getTenantId(anyString())).thenReturn(101); - when(commonUtilsService.isNotAuthorizedUser(any(), any(PermissionType.class))) + when(commonUtilsService.isNotAuthorizedUser(userDetails, PermissionType.APPROVE_SCHEMAS)) .thenReturn(false); try { @@ -310,7 +307,7 @@ public void uploadSchemaSuccess() throws KlawException { when(commonUtilsService.getTenantId(anyString())).thenReturn(101); mockGetEnvironment(); when(manageDatabase.getEnv(eq(101), eq(1))).thenReturn(Optional.of(createEnv(1))); - when(commonUtilsService.isNotAuthorizedUser(any(), any(PermissionType.class))) + when(commonUtilsService.isNotAuthorizedUser(userDetails, PermissionType.REQUEST_CREATE_SCHEMAS)) .thenReturn(false); when(handleDbRequests.requestForSchema(any())).thenReturn(ApiResultStatus.SUCCESS.value); when(commonUtilsService.getTopicsForTopicName(anyString(), anyInt())) @@ -331,7 +328,7 @@ public void uploadSchemaFailure() throws KlawException { when(commonUtilsService.getEnvsFromUserId(anyString())) .thenReturn(new HashSet<>(Collections.singletonList("1"))); when(commonUtilsService.getTenantId(anyString())).thenReturn(101); - when(commonUtilsService.isNotAuthorizedUser(any(), any(PermissionType.class))) + when(commonUtilsService.isNotAuthorizedUser(userDetails, PermissionType.REQUEST_CREATE_SCHEMAS)) .thenReturn(false); when(handleDbRequests.requestForSchema(any())) .thenThrow(new RuntimeException("Error from schema upload")); @@ -351,7 +348,7 @@ public void uploadSchemaFailure() throws KlawException { @Order(9) public void promoteSchemaNotAuthorized() throws Exception { // Make user unauthorized - when(commonUtilsService.isNotAuthorizedUser(any(), eq(PermissionType.REQUEST_CREATE_SCHEMAS))) + when(commonUtilsService.isNotAuthorizedUser(userDetails, PermissionType.REQUEST_CREATE_SCHEMAS)) .thenReturn(true); ApiResponse returnedValue = schemaRegistryControllerService.promoteSchema(buildPromoteSchemaRequest(false, "1")); @@ -368,6 +365,8 @@ public void promoteSchemaCanNotFindSourceEnvironmentSchema() throws Exception { when(commonUtilsService.getTopicsForTopicName(anyString(), anyInt())) .thenReturn(List.of(createTopic())); when(commonUtilsService.getTeamId(any())).thenReturn(101); + when(commonUtilsService.isNotAuthorizedUser(userDetails, PermissionType.REQUEST_CREATE_SCHEMAS)) + .thenReturn(false); ApiResponse returnedValue = schemaRegistryControllerService.promoteSchema(buildPromoteSchemaRequest(false, "1")); assertThat(returnedValue.getMessage()) @@ -384,6 +383,8 @@ public void promoteSchemaSuccess() throws Exception { .thenReturn(buildValidationResponse(true)); mockSchemaCreation(); when(manageDatabase.getEnv(eq(101), eq(8))).thenReturn(Optional.of(createEnv(8))); + when(commonUtilsService.isNotAuthorizedUser(userDetails, PermissionType.REQUEST_CREATE_SCHEMAS)) + .thenReturn(false); ApiResponse returnedValue = schemaRegistryControllerService.promoteSchema(buildPromoteSchemaRequest(false, "1")); @@ -403,6 +404,8 @@ public void promoteSchemaEnsureCorrectSchemaSelectedV1Success() throws Exception mockSchemaCreation(); when(manageDatabase.getEnv(eq(101), eq(8))).thenReturn(Optional.of(createEnv(8))); + when(commonUtilsService.isNotAuthorizedUser(userDetails, PermissionType.REQUEST_CREATE_SCHEMAS)) + .thenReturn(false); ApiResponse returnedValue = schemaRegistryControllerService.promoteSchema(buildPromoteSchemaRequest(false, "1")); @@ -425,6 +428,8 @@ public void promoteSchemaEnsureCorrectSchemaSelectedV2Success() throws Exception .thenReturn(buildValidationResponse(true)); mockSchemaCreation(); when(manageDatabase.getEnv(eq(101), eq(8))).thenReturn(Optional.of(createEnv(8))); + when(commonUtilsService.isNotAuthorizedUser(userDetails, PermissionType.REQUEST_CREATE_SCHEMAS)) + .thenReturn(false); ApiResponse returnedValue = schemaRegistryControllerService.promoteSchema(buildPromoteSchemaRequest(false, "2")); @@ -447,6 +452,8 @@ public void promoteSchemaEnsureCorrectSchemaSelectedV3Success() throws Exception .thenReturn(buildValidationResponse(true)); mockSchemaCreation(); when(manageDatabase.getEnv(eq(101), eq(8))).thenReturn(Optional.of(createEnv(8))); + when(commonUtilsService.isNotAuthorizedUser(userDetails, PermissionType.REQUEST_CREATE_SCHEMAS)) + .thenReturn(false); ApiResponse returnedValue = schemaRegistryControllerService.promoteSchema(buildPromoteSchemaRequest(false, "3")); @@ -470,6 +477,8 @@ public void promoteSchemaEnsureCorrectSchemaSelectedV4Success() throws Exception .thenReturn(buildValidationResponse(true)); mockSchemaCreation(); when(manageDatabase.getEnv(eq(101), eq(8))).thenReturn(Optional.of(createEnv(8))); + when(commonUtilsService.isNotAuthorizedUser(userDetails, PermissionType.REQUEST_CREATE_SCHEMAS)) + .thenReturn(false); ApiResponse returnedValue = schemaRegistryControllerService.promoteSchema(buildPromoteSchemaRequest(false, "4")); @@ -492,6 +501,8 @@ public void promoteSchemaWithInCompatibleSchemaReturnFailure() throws Exception .thenReturn(buildValidationResponse(false)); mockSchemaCreation(); when(manageDatabase.getEnv(eq(101), eq(8))).thenReturn(Optional.of(createEnv(8))); + when(commonUtilsService.isNotAuthorizedUser(userDetails, PermissionType.REQUEST_CREATE_SCHEMAS)) + .thenReturn(false); ApiResponse returnedValue = schemaRegistryControllerService.promoteSchema(buildPromoteSchemaRequest(false, "4")); @@ -514,7 +525,7 @@ public void uploadSchemaIncompatibleSchemaError() throws KlawException { when(commonUtilsService.getEnvsFromUserId(anyString())) .thenReturn(new HashSet<>(Collections.singletonList("1"))); when(commonUtilsService.getTenantId(anyString())).thenReturn(101); - when(commonUtilsService.isNotAuthorizedUser(any(), any(PermissionType.class))) + when(commonUtilsService.isNotAuthorizedUser(userDetails, PermissionType.REQUEST_CREATE_SCHEMAS)) .thenReturn(false); mockGetEnvironment(); when(manageDatabase.getEnv(eq(101), eq(1))).thenReturn(Optional.of(createEnv(1))); @@ -619,7 +630,7 @@ public void uploadSchema_NoValidationOnSave() throws KlawException { when(commonUtilsService.getEnvsFromUserId(anyString())) .thenReturn(new HashSet<>(Collections.singletonList("1"))); when(commonUtilsService.getTenantId(anyString())).thenReturn(101); - when(commonUtilsService.isNotAuthorizedUser(any(), any(PermissionType.class))) + when(commonUtilsService.isNotAuthorizedUser(userDetails, PermissionType.REQUEST_CREATE_SCHEMAS)) .thenReturn(false); when(handleDbRequests.requestForSchema(any())).thenReturn(ApiResultStatus.SUCCESS.value); when(commonUtilsService.getTopicsForTopicName(anyString(), anyInt())) @@ -650,7 +661,7 @@ public void uploadSchema_ValidationPropertyNotSet() throws KlawException { when(commonUtilsService.getEnvsFromUserId(anyString())) .thenReturn(new HashSet<>(Collections.singletonList("1"))); when(commonUtilsService.getTenantId(anyString())).thenReturn(101); - when(commonUtilsService.isNotAuthorizedUser(any(), any(PermissionType.class))) + when(commonUtilsService.isNotAuthorizedUser(userDetails, PermissionType.REQUEST_CREATE_SCHEMAS)) .thenReturn(false); mockGetEnvironment(); when(manageDatabase.getEnv(eq(101), eq(1))).thenReturn(Optional.of(createEnv(1))); @@ -689,6 +700,9 @@ public void getListofSchemaRequestsIn_NEWEST_FIRST_ORDER() { when(handleDbRequests.getAllUsersInfoForTeam(anyInt(), anyInt())).thenReturn(List.of(userInfo)); when(handleDbRequests.getEnvDetails(anyString(), anyInt())).thenReturn(this.env); when(manageDatabase.getTeamNameFromTeamId(anyInt(), anyInt())).thenReturn("teamname"); + when(commonUtilsService.isNotAuthorizedUser( + userDetails, PermissionType.APPROVE_ALL_REQUESTS_TEAMS)) + .thenReturn(false); List ordered_response = schemaRegistryControllerService.getSchemaRequests( @@ -736,6 +750,9 @@ public void getListofSchemaRequestsIn_OLDEST_FIRST_ORDER() { when(handleDbRequests.getAllUsersInfoForTeam(anyInt(), anyInt())).thenReturn(List.of(userInfo)); when(handleDbRequests.getEnvDetails(anyString(), anyInt())).thenReturn(this.env); when(manageDatabase.getTeamNameFromTeamId(anyInt(), anyInt())).thenReturn("teamname"); + when(commonUtilsService.isNotAuthorizedUser( + userDetails, PermissionType.APPROVE_ALL_REQUESTS_TEAMS)) + .thenReturn(false); List ordered_response = schemaRegistryControllerService.getSchemaRequests( @@ -969,6 +986,6 @@ private void stubUserInfo() { when(handleDbRequests.getUsersInfo(anyString())).thenReturn(userInfo); when(userInfo.getTeamId()).thenReturn(101); when(userInfo.getRole()).thenReturn("USER"); - when(mailService.getUserName(any())).thenReturn("kwusera"); + when(mailService.getUserName(userDetails)).thenReturn("kwusera"); } } diff --git a/core/src/test/java/io/aiven/klaw/service/SchemaRegistrySyncControllerServiceTest.java b/core/src/test/java/io/aiven/klaw/service/SchemaRegistrySyncControllerServiceTest.java index 169747d9e..c2a277dbe 100644 --- a/core/src/test/java/io/aiven/klaw/service/SchemaRegistrySyncControllerServiceTest.java +++ b/core/src/test/java/io/aiven/klaw/service/SchemaRegistrySyncControllerServiceTest.java @@ -51,12 +51,8 @@ import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; import org.mockito.Mock; -import org.mockito.Mockito; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; -import org.springframework.security.core.Authentication; -import org.springframework.security.core.context.SecurityContext; -import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.test.context.junit.jupiter.SpringExtension; import org.springframework.test.util.ReflectionTestUtils; @@ -98,15 +94,8 @@ public void setUp() throws Exception { schemaRegistrySyncControllerService, "commonUtilsService", commonUtilsService); when(manageDatabase.getHandleDbRequests()).thenReturn(handleDbRequests); - loginMock(); - } - - private void loginMock() { - Authentication authentication = Mockito.mock(Authentication.class); - SecurityContext securityContext = Mockito.mock(SecurityContext.class); - when(securityContext.getAuthentication()).thenReturn(authentication); - when(authentication.getPrincipal()).thenReturn(userDetails); - SecurityContextHolder.setContext(securityContext); + when(commonUtilsService.getPrincipal()).thenReturn(userDetails); + when(commonUtilsService.isNotAuthorizedUser(any(), any(PermissionType.class))).thenReturn(true); } @Test @@ -124,7 +113,7 @@ public void getSchemasOfEnvironmentNotInSyncSourceCluster() throws Exception { kwClustersMap.put(1, utilMethods.getKwClusters()); when(handleDbRequests.getEnvDetails(anyString(), anyInt())).thenReturn(env); - when(commonUtilsService.isNotAuthorizedUser(any(), any(PermissionType.class))) + when(commonUtilsService.isNotAuthorizedUser(userDetails, PermissionType.SYNC_SCHEMAS)) .thenReturn(false); when(commonUtilsService.getTenantId(anyString())).thenReturn(101); when(manageDatabase.getTeamNameFromTeamId(eq(101), eq(10))).thenReturn("Team1"); @@ -159,7 +148,7 @@ public void getSchemasOfEnvironmentInSyncAndNotInSyncSourceCluster() throws Exce kwClustersMap.put(1, utilMethods.getKwClusters()); when(handleDbRequests.getEnvDetails(anyString(), anyInt())).thenReturn(env); - when(commonUtilsService.isNotAuthorizedUser(any(), any(PermissionType.class))) + when(commonUtilsService.isNotAuthorizedUser(userDetails, PermissionType.SYNC_SCHEMAS)) .thenReturn(false); when(commonUtilsService.getTenantId(anyString())).thenReturn(101); when(manageDatabase.getTeamNameFromTeamId(eq(101), eq(10))).thenReturn("Team1"); @@ -220,7 +209,7 @@ public void getSchemasOfEnvironmentSourceMetadata() throws Exception { List topics = utilMethods.generateTopics(14); when(handleDbRequests.getEnvDetails(anyString(), anyInt())).thenReturn(env); - when(commonUtilsService.isNotAuthorizedUser(any(), any(PermissionType.class))) + when(commonUtilsService.isNotAuthorizedUser(userDetails, PermissionType.SYNC_BACK_SCHEMAS)) .thenReturn(false); when(commonUtilsService.getTenantId(anyString())).thenReturn(101); when(manageDatabase.getTeamNameFromTeamId(eq(101), eq(10))).thenReturn("Team1"); @@ -252,7 +241,7 @@ public void getSchemasOfEnvironmentNoSchemasSourceMetadata() throws Exception { List topics = utilMethods.generateTopics(14); when(handleDbRequests.getEnvDetails(anyString(), anyInt())).thenReturn(env); - when(commonUtilsService.isNotAuthorizedUser(any(), any(PermissionType.class))) + when(commonUtilsService.isNotAuthorizedUser(userDetails, PermissionType.SYNC_BACK_SCHEMAS)) .thenReturn(false); when(commonUtilsService.getTenantId(anyString())).thenReturn(101); when(manageDatabase.getTeamNameFromTeamId(eq(101), eq(10))).thenReturn("Team1"); @@ -287,7 +276,7 @@ public void updateDbFromCluster() throws Exception { when(handleDbRequests.getEnvDetails(anyString(), anyInt())).thenReturn(env); when(commonUtilsService.getTenantId(anyString())).thenReturn(101); - when(commonUtilsService.isNotAuthorizedUser(any(), any(PermissionType.class))) + when(commonUtilsService.isNotAuthorizedUser(userDetails, PermissionType.SYNC_SCHEMAS)) .thenReturn(false); when(manageDatabase.getClusters(any(), anyInt())).thenReturn(kwClustersMap); @@ -330,7 +319,7 @@ public void updateClusterFromDb() throws Exception { when(handleDbRequests.getEnvDetails(anyString(), anyInt())).thenReturn(env); when(commonUtilsService.getTenantId(anyString())).thenReturn(101); - when(commonUtilsService.isNotAuthorizedUser(any(), any(PermissionType.class))) + when(commonUtilsService.isNotAuthorizedUser(userDetails, PermissionType.SYNC_BACK_SCHEMAS)) .thenReturn(false); when(manageDatabase.getClusters(any(), anyInt())).thenReturn(kwClustersMap); @@ -388,7 +377,7 @@ public void getSchemaOfTopicFromSourceCluster() throws Exception { when(handleDbRequests.getEnvDetails(anyString(), anyInt())).thenReturn(env); when(commonUtilsService.getTenantId(anyString())).thenReturn(101); - when(commonUtilsService.isNotAuthorizedUser(any(), any(PermissionType.class))) + when(commonUtilsService.isNotAuthorizedUser(userDetails, PermissionType.SYNC_SCHEMAS)) .thenReturn(false); when(manageDatabase.getClusters(any(), anyInt())).thenReturn(kwClustersMap); when(clusterApiService.getAvroSchema(anyString(), any(), anyString(), anyString(), anyInt())) @@ -416,7 +405,7 @@ public void getSchemaOfTopicFromSourceMetadata() throws Exception { when(handleDbRequests.getEnvDetails(anyString(), anyInt())).thenReturn(env); when(commonUtilsService.getTenantId(anyString())).thenReturn(101); - when(commonUtilsService.isNotAuthorizedUser(any(), any(PermissionType.class))) + when(commonUtilsService.isNotAuthorizedUser(userDetails, PermissionType.SYNC_BACK_SCHEMAS)) .thenReturn(false); MessageSchema schema = utilMethods.getMSchemas().get(0); schema.setTopicname(topicName); @@ -453,7 +442,7 @@ public void deleteOrphanedSchemaMetaDataFromDb(List schemasToBeDeleted) when(handleDbRequests.getEnvDetails(anyString(), anyInt())).thenReturn(env); when(commonUtilsService.getTenantId(anyString())).thenReturn(101); - when(commonUtilsService.isNotAuthorizedUser(any(), any(PermissionType.class))) + when(commonUtilsService.isNotAuthorizedUser(userDetails, PermissionType.SYNC_SCHEMAS)) .thenReturn(false); when(manageDatabase.getClusters(any(), anyInt())).thenReturn(kwClustersMap); @@ -492,7 +481,7 @@ public void getSchemaOfTopicFromSourceMetadataWithSchemasToBeDeleted() throws Ex kwClustersMap.put(1, utilMethods.getKwClusters()); when(handleDbRequests.getEnvDetails(anyString(), anyInt())).thenReturn(env); - when(commonUtilsService.isNotAuthorizedUser(any(), any(PermissionType.class))) + when(commonUtilsService.isNotAuthorizedUser(userDetails, PermissionType.SYNC_SCHEMAS)) .thenReturn(false); when(commonUtilsService.getTenantId(anyString())).thenReturn(101); when(manageDatabase.getTeamNameFromTeamId(eq(101), eq(10))).thenReturn("Team1"); @@ -537,7 +526,7 @@ public void getSchemasOfEnvironmentFromMetadataWithTopicDeletedAndSchemaStillAva kwClustersMap.put(1, utilMethods.getKwClusters()); when(handleDbRequests.getEnvDetails(anyString(), anyInt())).thenReturn(env); - when(commonUtilsService.isNotAuthorizedUser(any(), any(PermissionType.class))) + when(commonUtilsService.isNotAuthorizedUser(userDetails, PermissionType.SYNC_SCHEMAS)) .thenReturn(false); when(commonUtilsService.getTenantId(anyString())).thenReturn(101); when(manageDatabase.getTeamNameFromTeamId(eq(101), eq(3))).thenReturn("Team1"); @@ -589,7 +578,7 @@ public void getSchemasOfEnvironmentFromMetadataWithSchemaDeletedFromCluster() th clusterResp.setSchemaInfoOfTopicList(new ArrayList<>()); when(manageDatabase.getTeamNameFromTeamId(eq(101), eq(3))).thenReturn("Team1"); when(handleDbRequests.getEnvDetails(anyString(), anyInt())).thenReturn(env); - when(commonUtilsService.isNotAuthorizedUser(any(), any(PermissionType.class))) + when(commonUtilsService.isNotAuthorizedUser(userDetails, PermissionType.SYNC_SCHEMAS)) .thenReturn(false); when(commonUtilsService.getTenantId(anyString())).thenReturn(101); when(manageDatabase.getTeamNameFromTeamId(eq(101), eq(10))).thenReturn("Team1"); @@ -642,7 +631,7 @@ public void getSchemasOfEnvironmentFromMetadataExceptonContactingCluster() throw SchemasInfoOfClusterResponse clusterResp = new SchemasInfoOfClusterResponse(); clusterResp.setSchemaInfoOfTopicList(new ArrayList<>()); when(handleDbRequests.getEnvDetails(anyString(), anyInt())).thenReturn(env); - when(commonUtilsService.isNotAuthorizedUser(any(), any(PermissionType.class))) + when(commonUtilsService.isNotAuthorizedUser(userDetails, PermissionType.SYNC_SCHEMAS)) .thenReturn(false); when(commonUtilsService.getTenantId(anyString())).thenReturn(101); when(manageDatabase.getClusters(any(), anyInt())).thenReturn(kwClustersMap); diff --git a/core/src/test/java/io/aiven/klaw/service/ServerConfigServiceTest.java b/core/src/test/java/io/aiven/klaw/service/ServerConfigServiceTest.java index 42d8b0167..8dec5c755 100644 --- a/core/src/test/java/io/aiven/klaw/service/ServerConfigServiceTest.java +++ b/core/src/test/java/io/aiven/klaw/service/ServerConfigServiceTest.java @@ -38,12 +38,8 @@ import org.mockito.ArgumentCaptor; import org.mockito.Captor; import org.mockito.Mock; -import org.mockito.Mockito; import org.springframework.context.annotation.AnnotationConfigApplicationContext; import org.springframework.core.env.Environment; -import org.springframework.security.core.Authentication; -import org.springframework.security.core.context.SecurityContext; -import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.test.context.junit.jupiter.SpringExtension; @@ -70,15 +66,15 @@ public class ServerConfigServiceTest { public void setUp() { AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(); this.env = context.getEnvironment(); - loginMock(); serverConfigService = new ServerConfigService(env, commonUtilsService, mailService, managedb); + when(commonUtilsService.getPrincipal()).thenReturn(userDetails); + when(commonUtilsService.isNotAuthorizedUser(any(), any(PermissionType.class))).thenReturn(true); } @Test @Order(1) public void getAllPropsNotAuthorized() { - when(commonUtilsService.isNotAuthorizedUser(any(), any(PermissionType.class))).thenReturn(true); serverConfigService.getAllProperties(); Collection collection = serverConfigService.getAllProps(); assertThat(collection).isEmpty(); // filtering for spring. and klaw. @@ -87,21 +83,13 @@ public void getAllPropsNotAuthorized() { @Test @Order(2) public void getAllProps() { - when(commonUtilsService.isNotAuthorizedUser(any(), any(PermissionType.class))) + when(commonUtilsService.isNotAuthorizedUser(userDetails, PermissionType.UPDATE_SERVERCONFIG)) .thenReturn(false); serverConfigService.getAllProperties(); Collection collection = serverConfigService.getAllProps(); assertThat(collection).isEmpty(); // filtering for spring. and klaw. } - private void loginMock() { - Authentication authentication = Mockito.mock(Authentication.class); - SecurityContext securityContext = Mockito.mock(SecurityContext.class); - when(securityContext.getAuthentication()).thenReturn(authentication); - when(authentication.getPrincipal()).thenReturn(userDetails); - SecurityContextHolder.setContext(securityContext); - } - @Test @Order(3) public void givenValidTenantModelAllResources_returnSuccess() @@ -129,6 +117,9 @@ public void givenValidTenantModelAllResources_returnSuccess() config.setTenantModel(prop); KwPropertiesModel request = createKwPropertiesModel(KLAW_TENANT_CONFIG, mapper.writeValueAsString(config)); + when(commonUtilsService.isNotAuthorizedUser(userDetails, PermissionType.UPDATE_SERVERCONFIG)) + .thenReturn(false); + // Execute ApiResponse response = serverConfigService.updateKwCustomProperty(request); @@ -167,6 +158,9 @@ public void givenValidTenantModelTopicsOnly_returnSuccess() config.setTenantModel(prop); KwPropertiesModel request = createKwPropertiesModel(KLAW_TENANT_CONFIG, mapper.writeValueAsString(config)); + when(commonUtilsService.isNotAuthorizedUser(userDetails, PermissionType.UPDATE_SERVERCONFIG)) + .thenReturn(false); + // Execute ApiResponse response = serverConfigService.updateKwCustomProperty(request); @@ -212,6 +206,9 @@ public void givenKafkaTopicThatDoesNotExist_returnFailure() config.setTenantModel(prop); KwPropertiesModel request = createKwPropertiesModel(KLAW_TENANT_CONFIG, mapper.writeValueAsString(config)); + when(commonUtilsService.isNotAuthorizedUser(userDetails, PermissionType.UPDATE_SERVERCONFIG)) + .thenReturn(false); + // Execute ApiResponse response = serverConfigService.updateKwCustomProperty(request); @@ -246,6 +243,9 @@ public void givenSchemaThatDoesNotExist_returnFailure() config.setTenantModel(prop); KwPropertiesModel request = createKwPropertiesModel(KLAW_TENANT_CONFIG, mapper.writeValueAsString(config)); + when(commonUtilsService.isNotAuthorizedUser(userDetails, PermissionType.UPDATE_SERVERCONFIG)) + .thenReturn(false); + // Execute ApiResponse response = serverConfigService.updateKwCustomProperty(request); @@ -261,6 +261,9 @@ public void givenSchemaThatDoesNotExist_returnFailure() public void givenInvalidJson_returnFailure() throws KlawException { stubValidateTests(); KwPropertiesModel request = createKwPropertiesModel(KLAW_TENANT_CONFIG, "{}"); + when(commonUtilsService.isNotAuthorizedUser(userDetails, PermissionType.UPDATE_SERVERCONFIG)) + .thenReturn(false); + // Execute ApiResponse response = serverConfigService.updateKwCustomProperty(request); @@ -289,6 +292,9 @@ public void givenValidTenantModelKafkaConnectOnly_returnSuccess() config.setTenantModel(prop); KwPropertiesModel request = createKwPropertiesModel(KLAW_TENANT_CONFIG, mapper.writeValueAsString(config)); + when(commonUtilsService.isNotAuthorizedUser(userDetails, PermissionType.UPDATE_SERVERCONFIG)) + .thenReturn(false); + // Execute ApiResponse response = serverConfigService.updateKwCustomProperty(request); @@ -304,6 +310,8 @@ public void givenRequestForConfig_returnCorrectConfig() stubValidateTests(); when(managedb.getKwPropertiesMap(101)).thenReturn(buildFullDbObject()); + when(commonUtilsService.isNotAuthorizedUser(userDetails, PermissionType.UPDATE_SERVERCONFIG)) + .thenReturn(false); // Execute List response = serverConfigService.getAllEditableProps(); @@ -350,6 +358,8 @@ public void givenRequestForConfigWithNoneSet_returnCorrectConfig() dbObject.put(KLAW_TENANT_CONFIG, map); when(managedb.getKwPropertiesMap(101)).thenReturn(dbObject); + when(commonUtilsService.isNotAuthorizedUser(userDetails, PermissionType.UPDATE_SERVERCONFIG)) + .thenReturn(false); // Execute List response = serverConfigService.getAllEditableProps(); @@ -373,6 +383,9 @@ public void givenValidTenantModelTopicsInvalidEnvsClustersOnly_returnFailure() config.setTenantModel(prop); KwPropertiesModel request = createKwPropertiesModel(KLAW_TENANT_CONFIG, mapper.writeValueAsString(config)); + when(commonUtilsService.isNotAuthorizedUser(userDetails, PermissionType.UPDATE_SERVERCONFIG)) + .thenReturn(false); + // Execute ApiResponse response = serverConfigService.updateKwCustomProperty(request); diff --git a/core/src/test/java/io/aiven/klaw/service/TopicControllerServiceTest.java b/core/src/test/java/io/aiven/klaw/service/TopicControllerServiceTest.java index 6e202b2dd..2144f335b 100644 --- a/core/src/test/java/io/aiven/klaw/service/TopicControllerServiceTest.java +++ b/core/src/test/java/io/aiven/klaw/service/TopicControllerServiceTest.java @@ -61,13 +61,9 @@ import org.mockito.ArgumentCaptor; import org.mockito.Captor; import org.mockito.Mock; -import org.mockito.Mockito; import org.springframework.dao.DataIntegrityViolationException; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; -import org.springframework.security.core.Authentication; -import org.springframework.security.core.context.SecurityContext; -import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.test.context.junit.jupiter.SpringExtension; import org.springframework.test.util.ReflectionTestUtils; @@ -122,15 +118,8 @@ public void setUp() throws Exception { rolesPermissionsControllerService); when(manageDatabase.getHandleDbRequests()).thenReturn(handleDbRequests); - loginMock(); - } - - private void loginMock() { - Authentication authentication = Mockito.mock(Authentication.class); - SecurityContext securityContext = Mockito.mock(SecurityContext.class); - when(securityContext.getAuthentication()).thenReturn(authentication); - when(authentication.getPrincipal()).thenReturn(userDetails); - SecurityContextHolder.setContext(securityContext); + when(commonUtilsService.getPrincipal()).thenReturn(userDetails); + when(commonUtilsService.isNotAuthorizedUser(any(), any(PermissionType.class))).thenReturn(true); } @Test @@ -144,8 +133,6 @@ public void createTopicsSuccessAdvancedTopicConfigs() when(tenantConfig.get(anyInt())).thenReturn(tenantConfigModel); when(tenantConfigModel.getBaseSyncEnvironment()).thenReturn("1"); stubUserInfo(); - when(commonUtilsService.isNotAuthorizedUser(any(), any(PermissionType.class))) - .thenReturn(false); when(manageDatabase.getKafkaEnvList(anyInt())).thenReturn(utilMethods.getEnvLists()); when(manageDatabase.getTeamsAndAllowedEnvs(anyInt(), anyInt())) .thenReturn(Collections.singletonList("1")); @@ -167,8 +154,6 @@ public void createTopicsSuccessDefaultValues() throws KlawException, KlawNotAuth when(tenantConfig.get(anyInt())).thenReturn(tenantConfigModel); when(tenantConfigModel.getBaseSyncEnvironment()).thenReturn("1"); stubUserInfo(); - when(commonUtilsService.isNotAuthorizedUser(any(), any(PermissionType.class))) - .thenReturn(false); when(manageDatabase.getKafkaEnvList(anyInt())).thenReturn(utilMethods.getEnvLists()); when(manageDatabase.getTeamsAndAllowedEnvs(anyInt(), anyInt())) .thenReturn(Collections.singletonList("1")); @@ -192,8 +177,6 @@ public void createTopicsFailureInvalidPartitions() when(tenantConfig.get(anyInt())).thenReturn(tenantConfigModel); when(tenantConfigModel.getBaseSyncEnvironment()).thenReturn("1"); stubUserInfo(); - when(commonUtilsService.isNotAuthorizedUser(any(), any(PermissionType.class))) - .thenReturn(false); when(manageDatabase.getKafkaEnvList(anyInt())).thenReturn(utilMethods.getEnvLists()); when(manageDatabase.getTeamsAndAllowedEnvs(anyInt(), anyInt())) .thenReturn(Collections.singletonList("1")); @@ -213,8 +196,6 @@ public void createTopicsFailureInvalidClusterTenantIds() when(tenantConfig.get(anyInt())).thenReturn(tenantConfigModel); when(tenantConfigModel.getBaseSyncEnvironment()).thenReturn("1"); stubUserInfo(); - when(commonUtilsService.isNotAuthorizedUser(any(), any(PermissionType.class))) - .thenReturn(false); when(manageDatabase.getKafkaEnvList(anyInt())).thenReturn(utilMethods.getEnvListsIncorrect1()); when(manageDatabase.getTeamsAndAllowedEnvs(anyInt(), anyInt())) .thenReturn(Collections.singletonList("1")); @@ -236,8 +217,6 @@ public void createTopicsFailureInvalidTopicDescriptionLength() when(tenantConfig.get(anyInt())).thenReturn(tenantConfigModel); when(tenantConfigModel.getBaseSyncEnvironment()).thenReturn("1"); stubUserInfo(); - when(commonUtilsService.isNotAuthorizedUser(any(), any(PermissionType.class))) - .thenReturn(false); when(manageDatabase.getKafkaEnvList(anyInt())).thenReturn(utilMethods.getEnvListsIncorrect1()); when(manageDatabase.getTeamsAndAllowedEnvs(anyInt(), anyInt())) .thenReturn(Collections.singletonList("1")); @@ -262,8 +241,6 @@ public void createTopicsFailureInvalidTopicDescriptionLength() public void createTopicDeleteRequestFailureTopicAlreadyExists() { String topicName = "testtopic1"; String envId = "1"; - when(commonUtilsService.isNotAuthorizedUser(any(), any(PermissionType.class))) - .thenReturn(false); when(commonUtilsService.getTenantId(anyString())).thenReturn(101); when(handleDbRequests.getTopicRequests(anyString(), anyString(), anyString(), anyInt())) .thenReturn(getListTopicRequests()); @@ -285,8 +262,6 @@ public void createTopicDeleteRequestFailureNotOwnerTeamOfTopic() { String topicName = "testtopic1"; String envId = "1"; stubUserInfo(); - when(commonUtilsService.isNotAuthorizedUser(any(), any(PermissionType.class))) - .thenReturn(false); when(commonUtilsService.getTenantId(anyString())).thenReturn(101); when(handleDbRequests.getTopicRequests(anyString(), anyString(), anyString(), anyInt())) .thenReturn(Collections.emptyList()); @@ -312,8 +287,6 @@ public void createTopicDeleteRequestFailureTopicWithSubscriptions() { String envId = "1"; stubUserInfo(); when(commonUtilsService.getTeamId(anyString())).thenReturn(1); - when(commonUtilsService.isNotAuthorizedUser(any(), any(PermissionType.class))) - .thenReturn(false); when(commonUtilsService.getTenantId(anyString())).thenReturn(101); when(handleDbRequests.getTopicRequests(anyString(), anyString(), anyString(), anyInt())) .thenReturn(Collections.emptyList()); @@ -339,8 +312,6 @@ public void createTopicDeleteRequestFailureTopicNotInCluster() { String envId = "2"; stubUserInfo(); when(userInfo.getTeamId()).thenReturn(1); - when(commonUtilsService.isNotAuthorizedUser(any(), any(PermissionType.class))) - .thenReturn(false); when(commonUtilsService.getTenantId(anyString())).thenReturn(101); when(handleDbRequests.getTopicRequests(anyString(), anyString(), anyString(), anyInt())) .thenReturn(Collections.emptyList()); @@ -366,8 +337,6 @@ public void createTopicDeleteRequestSuccessDefaultValues() { String envId = "1"; stubUserInfo(); when(commonUtilsService.getTeamId(anyString())).thenReturn(1); - when(commonUtilsService.isNotAuthorizedUser(any(), any(PermissionType.class))) - .thenReturn(false); when(commonUtilsService.getTenantId(anyString())).thenReturn(101); when(handleDbRequests.getTopicRequests(anyString(), anyString(), anyString(), anyInt())) .thenReturn(Collections.emptyList()); @@ -666,8 +635,6 @@ public void deleteTopicRequests() throws KlawException { when(handleDbRequests.deleteTopicRequest(anyInt(), anyString(), anyInt())) .thenReturn(ApiResultStatus.SUCCESS.value); when(mailService.getUserName(any())).thenReturn("uiuser1"); - when(commonUtilsService.isNotAuthorizedUser(any(), any(PermissionType.class))) - .thenReturn(false); ApiResponse resultResp = topicControllerService.deleteTopicRequests("1001"); assertThat(resultResp.getMessage()).isEqualTo(ApiResultStatus.SUCCESS.value); } @@ -681,6 +648,8 @@ public void approveTopicRequests() throws KlawException { ApiResponse apiResponse = ApiResponse.SUCCESS; stubUserInfo(); + when(commonUtilsService.isNotAuthorizedUser(userDetails, PermissionType.APPROVE_TOPICS)) + .thenReturn(false); when(handleDbRequests.getTopicRequestsForTopic(anyInt(), anyInt())).thenReturn(topicRequest); when(handleDbRequests.updateTopicRequest(any(), anyString())) .thenReturn( @@ -718,6 +687,8 @@ public void approveTopicClaimRequests() throws KlawException { CRUDResponse.builder().resultStatus(ApiResultStatus.SUCCESS.value).build()); when(commonUtilsService.getTopicsForTopicName(anyString(), anyInt())) .thenReturn(List.of(getTopic(topicName))); + when(commonUtilsService.isNotAuthorizedUser(userDetails, PermissionType.APPROVE_TOPICS)) + .thenReturn(false); when(clusterApiService.approveTopicRequests( anyString(), anyString(), @@ -756,6 +727,8 @@ public void approveTopicUpdateRequests() throws KlawException { CRUDResponse.builder().resultStatus(ApiResultStatus.SUCCESS.value).build()); when(commonUtilsService.getTopicsForTopicName(anyString(), anyInt())) .thenReturn(List.of(getTopic(topicName))); + when(commonUtilsService.isNotAuthorizedUser(userDetails, PermissionType.APPROVE_TOPICS)) + .thenReturn(false); when(clusterApiService.approveTopicRequests( anyString(), anyString(), @@ -788,6 +761,8 @@ public void approveTopicRequestsFailureResponseFromCluster() throws KlawExceptio when(handleDbRequests.updateTopicRequest(any(), anyString())) .thenReturn( CRUDResponse.builder().resultStatus(ApiResultStatus.SUCCESS.value).build()); + when(commonUtilsService.isNotAuthorizedUser(userDetails, PermissionType.APPROVE_TOPICS)) + .thenReturn(false); when(clusterApiService.approveTopicRequests( anyString(), anyString(), @@ -815,6 +790,8 @@ public void approveTopicRequestsFailureNotAllowed() throws KlawException { stubUserInfo(); when(handleDbRequests.getTopicRequestsForTopic(anyInt(), anyInt())).thenReturn(topicRequest); + when(commonUtilsService.isNotAuthorizedUser(userDetails, PermissionType.APPROVE_TOPICS)) + .thenReturn(false); ApiResponse apiResponse1 = topicControllerService.approveTopicRequests("" + topicId); assertThat(apiResponse1.getMessage()) @@ -1050,7 +1027,7 @@ public void declineTopicRequests() throws KlawException { stubUserInfo(); when(handleDbRequests.getTopicRequestsForTopic(anyInt(), anyInt())).thenReturn(topicRequest); - when(commonUtilsService.isNotAuthorizedUser(any(), any(PermissionType.class))) + when(commonUtilsService.isNotAuthorizedUser(userDetails, PermissionType.APPROVE_TOPICS)) .thenReturn(false); when(commonUtilsService.getEnvsFromUserId(anyString())) .thenReturn(new HashSet<>(Collections.singletonList("1"))); @@ -1071,7 +1048,7 @@ public void declineTopicRequestsFailureRequestDoesNotExist() throws KlawExceptio stubUserInfo(); when(handleDbRequests.getTopicRequestsForTopic(anyInt(), anyInt())).thenReturn(topicRequest); - when(commonUtilsService.isNotAuthorizedUser(any(), any(PermissionType.class))) + when(commonUtilsService.isNotAuthorizedUser(userDetails, PermissionType.APPROVE_TOPICS)) .thenReturn(false); when(handleDbRequests.declineTopicRequest(any(), anyString())) .thenReturn(ApiResultStatus.SUCCESS.value); @@ -1136,8 +1113,6 @@ public void updateTopicsSuccessAdvancedTopicConfigs() when(tenantConfig.get(anyInt())).thenReturn(tenantConfigModel); when(tenantConfigModel.getBaseSyncEnvironment()).thenReturn("1"); stubUserInfo(); - when(commonUtilsService.isNotAuthorizedUser(any(), any(PermissionType.class))) - .thenReturn(false); when(manageDatabase.getKafkaEnvList(anyInt())).thenReturn(utilMethods.getEnvLists()); when(manageDatabase.getTeamsAndAllowedEnvs(anyInt(), anyInt())) .thenReturn(Collections.singletonList("1")); @@ -1159,8 +1134,6 @@ public void updateTopicsSuccessDefaultValues() throws KlawException, KlawNotAuth when(tenantConfig.get(anyInt())).thenReturn(tenantConfigModel); when(tenantConfigModel.getBaseSyncEnvironment()).thenReturn("1"); stubUserInfo(); - when(commonUtilsService.isNotAuthorizedUser(any(), any(PermissionType.class))) - .thenReturn(false); when(manageDatabase.getKafkaEnvList(anyInt())).thenReturn(utilMethods.getEnvLists()); when(manageDatabase.getTeamsAndAllowedEnvs(anyInt(), anyInt())) .thenReturn(Collections.singletonList("1")); @@ -1184,8 +1157,6 @@ public void updateTopicsFailureInvalidPartitions() when(tenantConfig.get(anyInt())).thenReturn(tenantConfigModel); when(tenantConfigModel.getBaseSyncEnvironment()).thenReturn("1"); stubUserInfo(); - when(commonUtilsService.isNotAuthorizedUser(any(), any(PermissionType.class))) - .thenReturn(false); when(manageDatabase.getKafkaEnvList(anyInt())).thenReturn(utilMethods.getEnvLists()); when(manageDatabase.getTeamsAndAllowedEnvs(anyInt(), anyInt())) .thenReturn(Collections.singletonList("1")); @@ -1205,8 +1176,6 @@ public void updateTopicsFailureInvalidClusterTenantIds() when(tenantConfig.get(anyInt())).thenReturn(tenantConfigModel); when(tenantConfigModel.getBaseSyncEnvironment()).thenReturn("1"); stubUserInfo(); - when(commonUtilsService.isNotAuthorizedUser(any(), any(PermissionType.class))) - .thenReturn(false); when(manageDatabase.getKafkaEnvList(anyInt())).thenReturn(utilMethods.getEnvListsIncorrect1()); when(manageDatabase.getTeamsAndAllowedEnvs(anyInt(), anyInt())) .thenReturn(Collections.singletonList("1")); @@ -1327,8 +1296,6 @@ public void getClaimRequests_WhereTopicIsDeleted() { envListIds.add("DEV"); stubUserInfo(); when(commonUtilsService.getTenantId(any())).thenReturn(101); - when(commonUtilsService.isNotAuthorizedUser(any(), any(PermissionType.class))) - .thenReturn(false); List topicRequests = generateRequests(9); topicRequests.addAll(generateRequests(1, 7, RequestOperationType.CLAIM)); when(handleDbRequests.getAllTopicRequests( @@ -1375,8 +1342,6 @@ public void getClaimRequests_WhereTopicIsNotDeleted() { envListIds.add("DEV"); stubUserInfo(); when(commonUtilsService.getTenantId(any())).thenReturn(101); - when(commonUtilsService.isNotAuthorizedUser(any(), any(PermissionType.class))) - .thenReturn(false); List topicRequests = generateRequests(9); topicRequests.addAll(generateRequests(1, 7, RequestOperationType.CLAIM)); when(handleDbRequests.getAllTopicRequests( @@ -1440,6 +1405,8 @@ public void approveTopicClaimRequests_withAssocSchema_success() throws KlawExcep .thenReturn(new ResponseEntity<>(apiResponse, HttpStatus.OK)); when(commonUtilsService.getEnvsFromUserId(anyString())) .thenReturn(new HashSet<>(Collections.singletonList("1"))); + when(commonUtilsService.isNotAuthorizedUser(userDetails, PermissionType.APPROVE_TOPICS)) + .thenReturn(false); when(handleDbRequests.addToSynctopics(any())) .thenReturn( CRUDResponse.builder().resultStatus(ApiResultStatus.SUCCESS.value).build()); @@ -1472,6 +1439,8 @@ public void approveTopicClaimRequests_withAssocSchema_failure() throws KlawExcep CRUDResponse.builder().resultStatus(ApiResultStatus.SUCCESS.value).build()); when(commonUtilsService.getTopicsForTopicName(anyString(), anyInt())) .thenReturn(List.of(getTopic(topicName))); + when(commonUtilsService.isNotAuthorizedUser(userDetails, PermissionType.APPROVE_TOPICS)) + .thenReturn(false); when(clusterApiService.approveTopicRequests( anyString(), anyString(), @@ -1512,8 +1481,6 @@ public void editTopicRequestFailureRequestNotOwned() when(tenantConfig.get(anyInt())).thenReturn(tenantConfigModel); when(tenantConfigModel.getBaseSyncEnvironment()).thenReturn("1"); stubUserInfo(); - when(commonUtilsService.isNotAuthorizedUser(any(), any(PermissionType.class))) - .thenReturn(false); when(manageDatabase.getKafkaEnvList(anyInt())).thenReturn(utilMethods.getEnvLists()); when(manageDatabase.getTeamsAndAllowedEnvs(anyInt(), anyInt())) .thenReturn(Collections.singletonList("1")); @@ -1773,10 +1740,9 @@ public void approvePromoteTopicRequests() throws KlawException { TopicRequest topicRequest = getTopicRequest(TOPIC_1); topicRequest.setRequestOperationType(RequestOperationType.CREATE.value); - when(commonUtilsService.isNotAuthorizedUser("userDetails", PermissionType.APPROVE_TOPICS)) + when(commonUtilsService.isNotAuthorizedUser(userDetails, PermissionType.APPROVE_TOPICS)) .thenReturn(false); - when(commonUtilsService.isNotAuthorizedUser( - "userDetails", PermissionType.APPROVE_TOPICS_CREATE)) + when(commonUtilsService.isNotAuthorizedUser(userDetails, PermissionType.APPROVE_TOPICS_CREATE)) .thenReturn(true); when(handleDbRequests.getTopicRequestsForTopic(anyInt(), anyInt())).thenReturn(topicRequest); when(manageDatabase.getKwPropertyValue(KLAW_OPTIONAL_PERMISSION_NEW_TOPIC_CREATION_KEY, 0)) diff --git a/core/src/test/java/io/aiven/klaw/service/TopicSyncControllerServiceTest.java b/core/src/test/java/io/aiven/klaw/service/TopicSyncControllerServiceTest.java index 916b51973..88b29b027 100644 --- a/core/src/test/java/io/aiven/klaw/service/TopicSyncControllerServiceTest.java +++ b/core/src/test/java/io/aiven/klaw/service/TopicSyncControllerServiceTest.java @@ -55,12 +55,8 @@ import org.mockito.ArgumentCaptor; import org.mockito.Captor; import org.mockito.Mock; -import org.mockito.Mockito; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; -import org.springframework.security.core.Authentication; -import org.springframework.security.core.context.SecurityContext; -import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.test.context.junit.jupiter.SpringExtension; import org.springframework.test.util.ReflectionTestUtils; @@ -124,7 +120,8 @@ public void setUp() throws Exception { topicSyncControllerService, "clusterApiService", clusterApiService); when(manageDatabase.getHandleDbRequests()).thenReturn(handleDbRequests); - loginMock(); + when(commonUtilsService.getPrincipal()).thenReturn(userDetails); + when(commonUtilsService.isNotAuthorizedUser(any(), any(PermissionType.class))).thenReturn(true); } private void environmentSetUp() { @@ -184,14 +181,6 @@ private void validatedEnvironmentSetUp(String repFactor, String maxPartitions) { when(commonUtilsService.getTenantId(anyString())).thenReturn(101); } - private void loginMock() { - Authentication authentication = Mockito.mock(Authentication.class); - SecurityContext securityContext = Mockito.mock(SecurityContext.class); - when(securityContext.getAuthentication()).thenReturn(authentication); - when(authentication.getPrincipal()).thenReturn(userDetails); - SecurityContextHolder.setContext(securityContext); - } - @Test @Order(1) public void updateSyncTopicsSuccess() throws KlawException { @@ -199,7 +188,7 @@ public void updateSyncTopicsSuccess() throws KlawException { when(manageDatabase.getTenantConfig()).thenReturn(tenantConfig); when(tenantConfig.get(anyInt())).thenReturn(tenantConfigModel); when(tenantConfigModel.getBaseSyncEnvironment()).thenReturn("1"); - when(commonUtilsService.isNotAuthorizedUser(any(), any(PermissionType.class))) + when(commonUtilsService.isNotAuthorizedUser(userDetails, PermissionType.SYNC_TOPICS)) .thenReturn(false); when(commonUtilsService.getEnvsFromUserId(anyString())) .thenReturn(new HashSet<>(Collections.singletonList("1"))); @@ -221,7 +210,7 @@ public void updateSyncTopicsNoUpdate() throws KlawException { when(manageDatabase.getTenantConfig()).thenReturn(tenantConfig); when(tenantConfig.get(anyInt())).thenReturn(tenantConfigModel); when(tenantConfigModel.getBaseSyncEnvironment()).thenReturn("1"); - when(commonUtilsService.isNotAuthorizedUser(any(), any(PermissionType.class))) + when(commonUtilsService.isNotAuthorizedUser(userDetails, PermissionType.SYNC_TOPICS)) .thenReturn(false); when(manageDatabase.getTeamsAndAllowedEnvs(anyInt(), anyInt())) .thenReturn(Collections.singletonList("1")); @@ -262,6 +251,8 @@ public void getSyncTopics() throws Exception { when(kwClusters.getClusterName()).thenReturn("cluster"); when(kwClusters.getClusterId()).thenReturn(1); when(kwClusters.getKafkaFlavor()).thenReturn(""); + when(commonUtilsService.isNotAuthorizedUser(userDetails, PermissionType.SYNC_TOPICS)) + .thenReturn(false); SyncTopicsList topicRequests = topicSyncControllerService.getSyncTopics( @@ -297,6 +288,9 @@ public void approveTopicRequestAllTopicsWhereOneTopicIsAlreadyCreated() throws K .resultStatus(ApiResultStatus.SUCCESS.value) .entities(List.of(new Topic())) .build()); + when(commonUtilsService.isNotAuthorizedUser(userDetails, PermissionType.SYNC_BACK_TOPICS)) + .thenReturn(false); + // execute ApiResponse retval = topicSyncControllerService.updateSyncBackTopics( @@ -347,6 +341,8 @@ public void approveTopicRequestAllTopicsCreateAll() throws KlawException { .build()); when(commonUtilsService.getTopicsForTopicName(anyString(), anyInt())) .thenReturn(List.of(createTopic(1, TOPIC_NAME_1, env.getId()))); + when(commonUtilsService.isNotAuthorizedUser(userDetails, PermissionType.SYNC_BACK_TOPICS)) + .thenReturn(false); // execute ApiResponse retval = @@ -401,6 +397,8 @@ public void approveTopicRequestSelectedWhereOneTopicIsAlreadyCreated() throws Kl .build()); when(commonUtilsService.getTopicsForTopicName(anyString(), anyInt())) .thenReturn(List.of(createTopic(1, TOPIC_NAME_1, env.getId()))); + when(commonUtilsService.isNotAuthorizedUser(userDetails, PermissionType.SYNC_BACK_TOPICS)) + .thenReturn(false); ApiResponse retval = topicSyncControllerService.updateSyncBackTopics( @@ -452,6 +450,8 @@ public void approveTopicRequestSelectedCreateAll() throws KlawException { .build()); when(commonUtilsService.getTopicsForTopicName(anyString(), anyInt())) .thenReturn(List.of(createTopic(1, TOPIC_NAME_1, env.getId()))); + when(commonUtilsService.isNotAuthorizedUser(userDetails, PermissionType.SYNC_BACK_TOPICS)) + .thenReturn(false); ApiResponse retval = topicSyncControllerService.updateSyncBackTopics( @@ -505,6 +505,8 @@ public void approveTopicRequestSelectedUnexpectedExceptionFromClusterApi() throw .build()); when(commonUtilsService.getTopicsForTopicName(anyString(), anyInt())) .thenReturn(List.of(createTopic(1, TOPIC_NAME_1, env.getId()))); + when(commonUtilsService.isNotAuthorizedUser(userDetails, PermissionType.SYNC_BACK_TOPICS)) + .thenReturn(false); ApiResponse retval = topicSyncControllerService.updateSyncBackTopics( @@ -551,6 +553,8 @@ public void getSyncList_noValidationSet_base() throws Exception { // from the DB when(handleDbRequests.getSyncTopics(eq("1"), eq(null), eq(101))).thenReturn(topics); when(manageDatabase.getTeamNameFromTeamId(eq(101), eq(10))).thenReturn("Team1"); + when(commonUtilsService.isNotAuthorizedUser(userDetails, PermissionType.SYNC_TOPICS)) + .thenReturn(false); SyncTopicsList syncTopics = topicSyncControllerService.getSyncTopics( @@ -587,6 +591,8 @@ public void getReconSyncList_noValidationSet_base() throws Exception { // from the DB when(handleDbRequests.getSyncTopics(eq("1"), eq(null), eq(101))).thenReturn(topics); when(manageDatabase.getTeamNameFromTeamId(eq(101), eq(10))).thenReturn("Team1"); + when(commonUtilsService.isNotAuthorizedUser(userDetails, PermissionType.SYNC_TOPICS)) + .thenReturn(false); SyncTopicsList syncTopics = topicSyncControllerService.getReconTopics( @@ -619,6 +625,8 @@ public void getSyncList_noValidationSet_TwoNotSynchronized() throws Exception { // from the DB when(handleDbRequests.getSyncTopics(eq("1"), eq(null), eq(101))).thenReturn(topics); when(manageDatabase.getTeamNameFromTeamId(eq(101), eq(10))).thenReturn("Team1"); + when(commonUtilsService.isNotAuthorizedUser(userDetails, PermissionType.SYNC_TOPICS)) + .thenReturn(false); SyncTopicsList syncTopics = topicSyncControllerService.getSyncTopics( @@ -656,6 +664,8 @@ public void getReconSyncList_noValidationSet_FiveNotSynched() throws Exception { // from the DB when(handleDbRequests.getSyncTopics(eq("1"), eq(null), eq(101))).thenReturn(topics); when(manageDatabase.getTeamNameFromTeamId(eq(101), eq(10))).thenReturn("Team1"); + when(commonUtilsService.isNotAuthorizedUser(userDetails, PermissionType.SYNC_TOPICS)) + .thenReturn(false); SyncTopicsList syncTopics = topicSyncControllerService.getReconTopics( @@ -692,6 +702,8 @@ public void getSyncList_noValidationSet_ThreeDeletedFromCluster_allTopics() thro // from the DB when(handleDbRequests.getSyncTopics(eq("1"), eq(null), eq(101))).thenReturn(topics); when(manageDatabase.getTeamNameFromTeamId(eq(101), eq(10))).thenReturn("Team1"); + when(commonUtilsService.isNotAuthorizedUser(userDetails, PermissionType.SYNC_TOPICS)) + .thenReturn(false); SyncTopicsList syncTopics = topicSyncControllerService.getSyncTopics( @@ -729,6 +741,8 @@ public void getReconSyncList_noValidationSet_FourDeletedFromCluster() throws Exc // from the DB when(handleDbRequests.getSyncTopics(eq("1"), eq(null), eq(101))).thenReturn(topics); when(manageDatabase.getTeamNameFromTeamId(eq(101), eq(10))).thenReturn("Team1"); + when(commonUtilsService.isNotAuthorizedUser(userDetails, PermissionType.SYNC_TOPICS)) + .thenReturn(false); SyncTopicsList syncTopics = topicSyncControllerService.getReconTopics( @@ -765,6 +779,8 @@ public void getSyncList_noValidationSet_ThreeDeletedFromCluster() throws Excepti // from the DB when(handleDbRequests.getSyncTopics(eq("1"), eq(null), eq(101))).thenReturn(topics); when(manageDatabase.getTeamNameFromTeamId(eq(101), eq(10))).thenReturn("Team1"); + when(commonUtilsService.isNotAuthorizedUser(userDetails, PermissionType.SYNC_TOPICS)) + .thenReturn(false); SyncTopicsList syncTopics = topicSyncControllerService.getSyncTopics( @@ -833,6 +849,8 @@ public void getSyncList_ValidationOn( // from the DB when(handleDbRequests.getSyncTopics(eq("1"), eq(null), eq(101))).thenReturn(topics); when(manageDatabase.getTeamNameFromTeamId(eq(101), eq(10))).thenReturn("Team1"); + when(commonUtilsService.isNotAuthorizedUser(userDetails, PermissionType.SYNC_TOPICS)) + .thenReturn(false); Integer tenantId = 101; SyncTopicsList syncTopics = @@ -911,6 +929,8 @@ public void getReconSyncList_ValidationOn( // from the DB when(handleDbRequests.getSyncTopics(eq("1"), eq(null), eq(101))).thenReturn(topics); when(manageDatabase.getTeamNameFromTeamId(eq(101), eq(10))).thenReturn("Team1"); + when(commonUtilsService.isNotAuthorizedUser(userDetails, PermissionType.SYNC_TOPICS)) + .thenReturn(false); SyncTopicsList syncTopics = topicSyncControllerService.getReconTopics( @@ -988,6 +1008,8 @@ public void getSyncList_ValidationOn_AllTopics( // from the DB when(handleDbRequests.getSyncTopics(eq("1"), eq(null), eq(101))).thenReturn(topics); when(manageDatabase.getTeamNameFromTeamId(eq(101), eq(10))).thenReturn("Team1"); + when(commonUtilsService.isNotAuthorizedUser(userDetails, PermissionType.SYNC_TOPICS)) + .thenReturn(false); SyncTopicsList syncTopics = topicSyncControllerService.getSyncTopics( @@ -1067,6 +1089,8 @@ public void getSyncList_FailedValidationOn_ReplicationAndPartitions( // from the DB when(handleDbRequests.getSyncTopics(eq("1"), eq(null), eq(101))).thenReturn(topics); when(manageDatabase.getTeamNameFromTeamId(eq(101), eq(10))).thenReturn("Team1"); + when(commonUtilsService.isNotAuthorizedUser(userDetails, PermissionType.SYNC_TOPICS)) + .thenReturn(false); SyncTopicsList syncTopics = topicSyncControllerService.getSyncTopics( @@ -1116,6 +1140,8 @@ public void getSyncList_FailedValidationOn_ReplicationAndPartitionsAreNull() thr // from the DB when(handleDbRequests.getSyncTopics(eq("1"), eq(null), eq(101))).thenReturn(topics); when(manageDatabase.getTeamNameFromTeamId(eq(101), eq(10))).thenReturn("Team1"); + when(commonUtilsService.isNotAuthorizedUser(userDetails, PermissionType.SYNC_TOPICS)) + .thenReturn(false); SyncTopicsList syncTopics = topicSyncControllerService.getSyncTopics( @@ -1202,7 +1228,7 @@ private List getAvailableTeams() { private void stubUserInfo() { when(handleDbRequests.getUsersInfo(anyString())).thenReturn(userInfo); when(userInfo.getTeamId()).thenReturn(101); - when(mailService.getUserName(any())).thenReturn(USERNAME); + when(mailService.getUserName(userDetails)).thenReturn(USERNAME); when(commonUtilsService.getTenantId(eq(USERNAME))).thenReturn(TENANT_ID); when(handleDbRequests.getAllTeams(eq(101))).thenReturn(getAvailableTeams()); /// added diff --git a/core/src/test/java/io/aiven/klaw/service/UiConfigControllerServiceTest.java b/core/src/test/java/io/aiven/klaw/service/UiConfigControllerServiceTest.java index e164161d5..325d2d2bc 100644 --- a/core/src/test/java/io/aiven/klaw/service/UiConfigControllerServiceTest.java +++ b/core/src/test/java/io/aiven/klaw/service/UiConfigControllerServiceTest.java @@ -25,10 +25,6 @@ import org.junit.jupiter.api.TestMethodOrder; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; -import org.mockito.Mockito; -import org.springframework.security.core.Authentication; -import org.springframework.security.core.context.SecurityContext; -import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.provisioning.InMemoryUserDetailsManager; import org.springframework.test.context.junit.jupiter.SpringExtension; @@ -81,15 +77,7 @@ public void setUp() throws Exception { ReflectionTestUtils.setField( envsClustersTenantsControllerService, "commonUtilsService", commonUtilsService); when(manageDatabase.getHandleDbRequests()).thenReturn(handleDbRequests); - loginMock(); - } - - private void loginMock() { - Authentication authentication = Mockito.mock(Authentication.class); - SecurityContext securityContext = Mockito.mock(SecurityContext.class); - when(securityContext.getAuthentication()).thenReturn(authentication); - when(authentication.getPrincipal()).thenReturn(userDetails); - SecurityContextHolder.setContext(securityContext); + when(commonUtilsService.isNotAuthorizedUser(any(), any(PermissionType.class))).thenReturn(true); } @Test @@ -99,7 +87,7 @@ public void getEnvs1() { stubUserInfo(); when(commonUtilsService.getEnvProperty(anyInt(), anyString())).thenReturn("1"); when(manageDatabase.getKafkaEnvList(anyInt())).thenReturn(getAllEnvs()); - when(commonUtilsService.isNotAuthorizedUser(any(), any(PermissionType.class))) + when(commonUtilsService.isNotAuthorizedUser(userDetails, PermissionType.ADD_EDIT_DELETE_ENVS)) .thenReturn(false); when(manageDatabase.getTenantMap()).thenReturn(tenantMap); when(tenantMap.get(anyInt())).thenReturn("1"); @@ -117,7 +105,7 @@ public void getEnvs1() { @Order(4) public void getSchemaRegEnvs() { stubUserInfo(); - when(commonUtilsService.isNotAuthorizedUser(any(), any(PermissionType.class))) + when(commonUtilsService.isNotAuthorizedUser(userDetails, PermissionType.ADD_EDIT_DELETE_ENVS)) .thenReturn(false); when(handleDbRequests.getAllSchemaRegEnvs(1)).thenReturn(getAllSchemaEnvs()); diff --git a/core/src/test/java/io/aiven/klaw/service/UsersTeamsControllerServiceTest.java b/core/src/test/java/io/aiven/klaw/service/UsersTeamsControllerServiceTest.java index 487a20e96..1b2705310 100644 --- a/core/src/test/java/io/aiven/klaw/service/UsersTeamsControllerServiceTest.java +++ b/core/src/test/java/io/aiven/klaw/service/UsersTeamsControllerServiceTest.java @@ -75,11 +75,7 @@ import org.junit.platform.commons.util.StringUtils; import org.mockito.ArgumentCaptor; import org.mockito.Mock; -import org.mockito.Mockito; -import org.springframework.security.core.Authentication; import org.springframework.security.core.GrantedAuthority; -import org.springframework.security.core.context.SecurityContext; -import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.crypto.factory.PasswordEncoderFactories; import org.springframework.security.provisioning.InMemoryUserDetailsManager; @@ -138,7 +134,8 @@ public void setUp() { usersTeamsControllerService, "encryptorSecretKey", ENCRYPTOR_SECRET_KEY); when(manageDatabase.getHandleDbRequests()).thenReturn(handleDbRequests); userInfo = utilMethods.getUserInfoMockDao(); - loginMock(); + when(commonUtilsService.getPrincipal()).thenReturn(userDetails); + when(commonUtilsService.isNotAuthorizedUser(any(), any(PermissionType.class))).thenReturn(true); } @Test @@ -178,19 +175,19 @@ public void updateProfileFailureDbUpdate() { @Test public void updateUserNotAuthorized() throws KlawException { UserInfoModel userInfoModel = utilMethods.getUserInfoMock(); - when(commonUtilsService.isNotAuthorizedUser(any(), any(PermissionType.class))).thenReturn(true); ApiResponse apiResponse = usersTeamsControllerService.updateUser(userInfoModel); assertThat(apiResponse.getMessage()).isEqualTo(ApiResultStatus.NOT_AUTHORIZED.value); } @Test public void updateUserNotAuthorizedToUpdateSuperAdmin() throws KlawException { + final String userName = "testUser"; UserInfoModel userInfoModel = utilMethods.getUserInfoMock(); - when(commonUtilsService.isNotAuthorizedUser(any(), any(PermissionType.class))) + when(commonUtilsService.isNotAuthorizedUser(userName, PermissionType.ADD_EDIT_DELETE_USERS)) .thenReturn(false); when(handleDbRequests.getUsersInfo(anyString())).thenReturn(userInfo); when(commonUtilsService.getTenantId(anyString())).thenReturn(101); - when(mailService.getUserName(any())).thenReturn("testuser"); + when(mailService.getUserName(userDetails)).thenReturn(userName); when(manageDatabase.getRolesPermissionsPerTenant(anyInt())) .thenReturn(utilMethods.getRolesPermsMapForSuperuser()); ApiResponse apiResponse = usersTeamsControllerService.updateUser(userInfoModel); @@ -643,11 +640,12 @@ public void deleteTeamFailureDbException() { @Test public void deleteUserFailureHasRequests() throws KlawException { - when(commonUtilsService.isNotAuthorizedUser(any(), any(PermissionType.class))) + String userName = "testuser"; + when(commonUtilsService.isNotAuthorizedUser(userDetails, PermissionType.ADD_EDIT_DELETE_USERS)) .thenReturn(false); when(handleDbRequests.getUsersInfo(anyString())).thenReturn(userInfo); when(commonUtilsService.getTenantId(anyString())).thenReturn(TEST_TENANT_ID); - when(mailService.getUserName(any())).thenReturn("testuser"); + when(mailService.getUserName(userDetails)).thenReturn(userName); when(manageDatabase.getRolesPermissionsPerTenant(anyInt())).thenReturn(new HashMap<>()); when(handleDbRequests.existsComponentsCountForUser("testuser", TEST_TENANT_ID)) .thenReturn(true); @@ -659,7 +657,10 @@ public void deleteUserFailureHasRequests() throws KlawException { @Test public void deleteUserFailureisAdmin() throws KlawException { - when(commonUtilsService.isNotAuthorizedUser(any(), any(PermissionType.class))) + when(commonUtilsService.isNotAuthorizedUser(userDetails, PermissionType.ADD_EDIT_DELETE_USERS)) + .thenReturn(false); + when(commonUtilsService.isNotAuthorizedUser( + userDetails, PermissionType.FULL_ACCESS_USERS_TEAMS_ROLES)) .thenReturn(false); when(handleDbRequests.getUsersInfo(anyString())).thenReturn(userInfo); when(commonUtilsService.getTenantId(anyString())).thenReturn(TEST_TENANT_ID); @@ -673,7 +674,7 @@ public void deleteUserFailureisAdmin() throws KlawException { @Test public void deleteUserSuccessNormalUser() throws KlawException { - when(commonUtilsService.isNotAuthorizedUser(any(), any(PermissionType.class))) + when(commonUtilsService.isNotAuthorizedUser(userDetails, PermissionType.ADD_EDIT_DELETE_USERS)) .thenReturn(false); when(handleDbRequests.getUsersInfo(anyString())).thenReturn(userInfo); when(commonUtilsService.getTenantId(anyString())).thenReturn(TEST_TENANT_ID); @@ -687,8 +688,8 @@ public void deleteUserSuccessNormalUser() throws KlawException { @Test public void deleteUserFailureNoSuperUserPermission() throws KlawException { - when(commonUtilsService.isNotAuthorizedUser(any(), any(PermissionType.class))) - .thenReturn(false, true); + when(commonUtilsService.isNotAuthorizedUser(userDetails, PermissionType.ADD_EDIT_DELETE_USERS)) + .thenReturn(false); when(handleDbRequests.getUsersInfo(anyString())).thenReturn(userInfo); when(commonUtilsService.getTenantId(anyString())).thenReturn(TEST_TENANT_ID); when(mailService.getUserName(any())).thenReturn("testuser"); @@ -700,7 +701,6 @@ public void deleteUserFailureNoSuperUserPermission() throws KlawException { @Test public void deleteUserFailureNoDeletionPermission() throws KlawException { - when(commonUtilsService.isNotAuthorizedUser(any(), any(PermissionType.class))).thenReturn(true); when(handleDbRequests.getUsersInfo(anyString())).thenReturn(userInfo); when(commonUtilsService.getTenantId(anyString())).thenReturn(TEST_TENANT_ID); when(mailService.getUserName(any())).thenReturn("testuser"); @@ -805,8 +805,6 @@ public void addNewTeamFailureWithExistingTeamName() throws KlawException { public void addNewTeamFailureWithUnAuthorizedUser() throws KlawException { TeamModel teamModel = utilMethods.getTeamModelMock(); - when(commonUtilsService.isNotAuthorizedUser(any(), any(PermissionType.class))).thenReturn(true); - ApiResponse apiResponse = usersTeamsControllerService.addNewTeam(teamModel, true); assertThat(apiResponse).isSameAs(ApiResponse.NOT_AUTHORIZED); } @@ -832,8 +830,6 @@ public void updateTeamSuccessWhenNoEnvList() throws KlawException { @Test public void updateTeamWhenUnAuthorizedUser() throws KlawException { - when(commonUtilsService.isNotAuthorizedUser(userDetails, PermissionType.ADD_EDIT_DELETE_TEAMS)) - .thenReturn(true); TeamModel teamModel = utilMethods.getTeamModelMock(); ApiResponse apiResponse = usersTeamsControllerService.updateTeam(teamModel); @@ -1366,6 +1362,8 @@ public void getNewUserRequestsSuccess(int count) throws KlawNotAuthorizedExcepti when(mailService.getUserName(userDetails)).thenReturn(TEST_AUTHENTICATED_USER_UNAME); when(commonUtilsService.getTenantId(TEST_AUTHENTICATED_USER_UNAME)) .thenReturn(authenticatedUserTenantId); + when(commonUtilsService.isNotAuthorizedUser(userDetails, PermissionType.ADD_EDIT_DELETE_USERS)) + .thenReturn(false); when(handleDbRequests.getAllRegisterUsersInformation()).thenReturn(regUserList); when(manageDatabase.getTenantMap()).thenReturn(tenantMapMock); @@ -1397,6 +1395,8 @@ public static Stream getNewUserRequestsSuccess() { @Test public void getNewUserRequestsWithNoRequestsInDBNullPointerException() { + when(commonUtilsService.isNotAuthorizedUser(userDetails, PermissionType.ADD_EDIT_DELETE_USERS)) + .thenReturn(false); when(mailService.getUserName(userDetails)).thenReturn(TEST_AUTHENTICATED_USER_UNAME); when(commonUtilsService.getTenantId(TEST_AUTHENTICATED_USER_UNAME)).thenReturn(TEST_TENANT_ID); when(handleDbRequests.getAllRegisterUsersInformation()).thenReturn(null); @@ -1410,9 +1410,6 @@ public void getNewUserRequestsWithNoRequestsInDBNullPointerException() { @Test public void getNewUserRequestsWithUnAuthorizedUser() { - when(commonUtilsService.isNotAuthorizedUser(userDetails, PermissionType.ADD_EDIT_DELETE_USERS)) - .thenReturn(true); - assertThatExceptionOfType(KlawNotAuthorizedException.class) .isThrownBy(() -> usersTeamsControllerService.getNewUserRequests()) .withMessage("You are not authorized to view this information."); @@ -1513,9 +1510,6 @@ public void approveNewUserRequestsFailureWithLDAPAuth() { @Test public void approveNewUserRequestsFailureWithUnAuthorizedUser() throws KlawException { - when(commonUtilsService.isNotAuthorizedUser(userDetails, PermissionType.ADD_EDIT_DELETE_USERS)) - .thenReturn(true); - ApiResponse response = usersTeamsControllerService.approveNewUserRequests( testNewRegUser.getUsername(), true, Integer.MIN_VALUE, null); @@ -1641,8 +1635,6 @@ public void declineNewUserRequestsDBFailure() { @Test public void declineNewUserRequestsAuthenticationFailure() throws KlawException { when(mailService.getUserName(userDetails)).thenReturn(TEST_AUTHENTICATED_USER_UNAME); - when(commonUtilsService.isNotAuthorizedUser(userDetails, PermissionType.ADD_EDIT_DELETE_USERS)) - .thenReturn(true); ApiResponse response = usersTeamsControllerService.declineNewUserRequests(TEST_NEW_USER_UNAME); @@ -1682,14 +1674,6 @@ public void getRegistrationInfoFromIdNoRegistrationInfo() { assertThat(response).isNull(); } - private void loginMock() { - Authentication authentication = Mockito.mock(Authentication.class); - SecurityContext securityContext = Mockito.mock(SecurityContext.class); - when(securityContext.getAuthentication()).thenReturn(authentication); - when(authentication.getPrincipal()).thenReturn(userDetails); - SecurityContextHolder.setContext(securityContext); - } - public UserDetails userDetails(String username, String password) { return new UserDetails() { @@ -1824,6 +1808,8 @@ private void addTwoDefaultTeamsVerifyCapturedTeams( private void addNewTeamSetupTest(String userName, String existingTeamName) { when(mailService.getUserName(any())).thenReturn(userName); when(commonUtilsService.getTenantId(anyString())).thenReturn(TEST_TENANT_ID); + when(commonUtilsService.isNotAuthorizedUser(userDetails, PermissionType.ADD_EDIT_DELETE_TEAMS)) + .thenReturn(false); when(manageDatabase.getTeamNamesForTenant(TEST_TENANT_ID)) .thenReturn(List.of(existingTeamName)); } diff --git a/core/src/test/java/io/aiven/klaw/service/UtilControllerServiceTest.java b/core/src/test/java/io/aiven/klaw/service/UtilControllerServiceTest.java index 343959ba1..06bd0c7f3 100644 --- a/core/src/test/java/io/aiven/klaw/service/UtilControllerServiceTest.java +++ b/core/src/test/java/io/aiven/klaw/service/UtilControllerServiceTest.java @@ -11,6 +11,7 @@ import io.aiven.klaw.helpers.db.rdbms.HandleDbRequestsJdbc; import io.aiven.klaw.model.ApiResponse; import io.aiven.klaw.model.enums.ApiResultStatus; +import io.aiven.klaw.model.enums.PermissionType; import io.aiven.klaw.model.requests.ResetEntityCache; import java.util.Collection; import org.junit.jupiter.api.BeforeEach; @@ -19,11 +20,7 @@ import org.junit.jupiter.api.TestMethodOrder; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; -import org.mockito.Mockito; -import org.springframework.security.core.Authentication; import org.springframework.security.core.GrantedAuthority; -import org.springframework.security.core.context.SecurityContext; -import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.test.context.junit.jupiter.SpringExtension; import org.springframework.test.util.ReflectionTestUtils; @@ -49,7 +46,8 @@ void setUp() { ReflectionTestUtils.setField(utilControllerService, "mailService", mailService); userInfo = utilMethods.getUserInfoMockDao(); when(manageDatabase.getHandleDbRequests()).thenReturn(handleDbRequests); - loginMock(); + when(commonUtilsService.getPrincipal()).thenReturn(userDetails); + when(commonUtilsService.isNotAuthorizedUser(any(), any(PermissionType.class))).thenReturn(true); } @Test @@ -57,6 +55,8 @@ public void resetCache() { ResetEntityCache resetEntityCache = utilMethods.getResetEntityCache(); when(handleDbRequests.getUsersInfo(anyString())).thenReturn(userInfo); when(mailService.getUserName(any())).thenReturn("anonymousUser"); + when(commonUtilsService.isNotAuthorizedUser(userDetails, PermissionType.ADD_EDIT_DELETE_USERS)) + .thenReturn(false); ApiResponse apiResponse = utilControllerService.resetCache(resetEntityCache); assertThat(apiResponse.getMessage()).isEqualTo(ApiResultStatus.SUCCESS.value); } @@ -66,18 +66,12 @@ public void resetCacheNotAuthorized() { ResetEntityCache resetEntityCache = utilMethods.getResetEntityCache(); when(handleDbRequests.getUsersInfo(anyString())).thenReturn(userInfo); when(mailService.getUserName(any())).thenReturn("testuser"); + when(commonUtilsService.isNotAuthorizedUser(userDetails, PermissionType.ADD_EDIT_DELETE_USERS)) + .thenReturn(false); ApiResponse apiResponse = utilControllerService.resetCache(resetEntityCache); assertThat(apiResponse.getMessage()).isEqualTo(ApiResultStatus.SUCCESS.value); } - private void loginMock() { - Authentication authentication = Mockito.mock(Authentication.class); - SecurityContext securityContext = Mockito.mock(SecurityContext.class); - when(securityContext.getAuthentication()).thenReturn(authentication); - when(authentication.getPrincipal()).thenReturn(userDetails); - SecurityContextHolder.setContext(securityContext); - } - public UserDetails userDetails(String username, String password) { return new UserDetails() {