diff --git a/application/src/main/java/org/thingsboard/server/controller/BaseController.java b/application/src/main/java/org/thingsboard/server/controller/BaseController.java index d65f3201bc..12a7bd65f9 100644 --- a/application/src/main/java/org/thingsboard/server/controller/BaseController.java +++ b/application/src/main/java/org/thingsboard/server/controller/BaseController.java @@ -1293,7 +1293,7 @@ public abstract class BaseController { protected EntityGroupInfo checkEntityGroupId(EntityGroupId entityGroupId, Operation operation) throws ThingsboardException { try { validateId(entityGroupId, id -> "Incorrect entityGroupId " + id); - EntityGroupInfo entityGroup = entityGroupService.findEntityGroupInfoById(getTenantId(), entityGroupId); + EntityGroupInfo entityGroup = entityGroupService.findEntityGroupInfoByTenantIdAndId(getTenantId(), entityGroupId); checkNotNull(entityGroup, "Entity group with id [" + entityGroupId + "] is not found"); accessControlService.checkEntityGroupInfoPermission(getCurrentUser(), operation, entityGroup); return entityGroup; diff --git a/application/src/main/java/org/thingsboard/server/controller/EntityGroupController.java b/application/src/main/java/org/thingsboard/server/controller/EntityGroupController.java index 3ca4e3dca5..40499b2d2f 100644 --- a/application/src/main/java/org/thingsboard/server/controller/EntityGroupController.java +++ b/application/src/main/java/org/thingsboard/server/controller/EntityGroupController.java @@ -965,7 +965,11 @@ public class EntityGroupController extends AutoCommitController { for (String strEntityGroupId : strEntityGroupIds) { entityGroupIds.add(new EntityGroupId(toUUID(strEntityGroupId))); } - return checkNotNull(entityGroupService.findEntityGroupEntityInfosByIds(tenantId, entityGroupIds, new PageLink(Integer.MAX_VALUE)).getData()); + List entityGroups = checkNotNull( + entityGroupService.findEntityGroupInfosByIds(tenantId, entityGroupIds, new PageLink(Integer.MAX_VALUE)).getData()); + return filterEntityGroupsByReadPermission(entityGroups).stream() + .map(entityGroup -> new EntityInfo(entityGroup.getId(), entityGroup.getName())) + .toList(); } @ApiOperation(value = "Get Owners (getOwners)", @@ -1164,15 +1168,14 @@ public class EntityGroupController extends AutoCommitController { EntityGroupInfo userGroup; if (shareGroupRequest.isAllUserGroup()) { - Optional userGroupOptional = entityGroupService.findEntityGroupInfoByTypeAndName(getTenantId(), shareGroupRequest.getOwnerId(), - EntityType.USER, EntityGroup.GROUP_ALL_NAME); + Optional userGroupOptional = findAllUserGroup(shareGroupRequest.getOwnerId()); if (userGroupOptional.isPresent()) { userGroup = userGroupOptional.get(); } else { throw new ThingsboardException("Requested item wasn't found!", ThingsboardErrorCode.ITEM_NOT_FOUND); } } else { - userGroup = checkNotNull(entityGroupService.findEntityGroupInfoById(getTenantId(), shareGroupRequest.getUserGroupId())); + userGroup = checkNotNull(entityGroupService.findEntityGroupInfoByTenantIdAndId(getTenantId(), shareGroupRequest.getUserGroupId())); } accessControlService.checkEntityGroupInfoPermission(getCurrentUser(), Operation.WRITE, userGroup); @@ -1250,7 +1253,7 @@ public class EntityGroupController extends AutoCommitController { checkParameter("userGroupId", strUserGroupId); checkParameter("roleId", strRoleId); EntityGroupId userGroupId = new EntityGroupId(toUUID(strUserGroupId)); - EntityGroup userGroup = entityGroupService.findEntityGroupById(getTenantId(), userGroupId); + EntityGroup userGroup = entityGroupService.findEntityGroupInfoByTenantIdAndId(getTenantId(), userGroupId); if (userGroup == null) { throw new ThingsboardException("User group with requested id: " + userGroupId + " wasn't found!", ThingsboardErrorCode.ITEM_NOT_FOUND); } @@ -1303,7 +1306,7 @@ public class EntityGroupController extends AutoCommitController { private EntityGroup resolveEntityGroup(UUID entityGroupUuid) throws ThingsboardException { EntityGroupId entityGroupId = new EntityGroupId(entityGroupUuid); - EntityGroup entityGroup = entityGroupService.findEntityGroupById(getTenantId(), entityGroupId); + EntityGroup entityGroup = entityGroupService.findEntityGroupInfoByTenantIdAndId(getTenantId(), entityGroupId); if (entityGroup == null) { throw new ThingsboardException("Entity group with requested id: " + entityGroupId + " wasn't found!", ThingsboardErrorCode.ITEM_NOT_FOUND); } @@ -1313,15 +1316,14 @@ public class EntityGroupController extends AutoCommitController { private EntityGroupInfo resolveUserGroup(ShareGroupRequest shareGroupRequest) throws ThingsboardException { EntityGroupInfo userGroup; if (shareGroupRequest.isAllUserGroup()) { - Optional userGroupOptional = entityGroupService.findEntityGroupInfoByTypeAndName(getTenantId(), shareGroupRequest.getOwnerId(), - EntityType.USER, EntityGroup.GROUP_ALL_NAME); + Optional userGroupOptional = findAllUserGroup(shareGroupRequest.getOwnerId()); if (userGroupOptional.isPresent()) { userGroup = userGroupOptional.get(); } else { throw new ThingsboardException("Requested item wasn't found!", ThingsboardErrorCode.ITEM_NOT_FOUND); } } else { - userGroup = entityGroupService.findEntityGroupInfoById(getTenantId(), shareGroupRequest.getUserGroupId()); + userGroup = entityGroupService.findEntityGroupInfoByTenantIdAndId(getTenantId(), shareGroupRequest.getUserGroupId()); } if (userGroup == null) { throw new ThingsboardException("Specified user group wasn't found!", ThingsboardErrorCode.ITEM_NOT_FOUND); @@ -1329,6 +1331,12 @@ public class EntityGroupController extends AutoCommitController { return userGroup; } + private Optional findAllUserGroup(EntityId ownerId) throws ThingsboardException { + TenantId tenantId = getTenantId(); + return entityGroupService.findEntityGroupInfoByTypeAndName(tenantId, ownerId, EntityType.USER, EntityGroup.GROUP_ALL_NAME) + .map(group -> entityGroupService.findEntityGroupInfoByTenantIdAndId(tenantId, group.getId())); + } + private List resolveRoles(ShareGroupRequest shareGroupRequest) throws ThingsboardException { List roles = new ArrayList<>(1); if (shareGroupRequest.getRoleIds() != null && !shareGroupRequest.getRoleIds().isEmpty()) { diff --git a/application/src/main/java/org/thingsboard/server/controller/GroupPermissionController.java b/application/src/main/java/org/thingsboard/server/controller/GroupPermissionController.java index 130340ab33..71d2097da7 100644 --- a/application/src/main/java/org/thingsboard/server/controller/GroupPermissionController.java +++ b/application/src/main/java/org/thingsboard/server/controller/GroupPermissionController.java @@ -19,6 +19,7 @@ import org.thingsboard.server.common.data.EntityType; import org.thingsboard.server.common.data.audit.ActionType; import org.thingsboard.server.common.data.exception.ThingsboardErrorCode; import org.thingsboard.server.common.data.exception.ThingsboardException; +import org.thingsboard.server.common.data.group.EntityGroupInfo; import org.thingsboard.server.common.data.id.EntityGroupId; import org.thingsboard.server.common.data.id.EntityId; import org.thingsboard.server.common.data.id.GroupPermissionId; @@ -209,7 +210,8 @@ public class GroupPermissionController extends BaseController { @RequestBody List permissions) throws ThingsboardException, ExecutionException, InterruptedException { TenantId tenantId = getCurrentUser().getTenantId(); accessControlService.checkPermission(getCurrentUser(), Resource.GROUP_PERMISSION, Operation.READ); - List permissionInfoList = groupPermissionService.loadUserGroupPermissionInfoListAsync(tenantId, permissions).get(); + List readablePermissions = permissions.stream().filter(this::isReadableEntityGroup).toList(); + List permissionInfoList = groupPermissionService.loadUserGroupPermissionInfoListAsync(tenantId, readablePermissions).get(); return applyPermissionInfo(permissionInfoList); } @@ -259,6 +261,19 @@ public class GroupPermissionController extends BaseController { } } + private boolean isReadableEntityGroup(GroupPermission groupPermission) { + EntityGroupId entityGroupId = groupPermission.getEntityGroupId(); + if (entityGroupId == null || entityGroupId.isNullUid()) { + return true; + } + try { + EntityGroupInfo entityGroup = entityGroupService.findEntityGroupInfoByTenantIdAndId(getTenantId(), entityGroupId); + return entityGroup != null && accessControlService.hasEntityGroupInfoPermission(getCurrentUser(), Operation.READ, entityGroup); + } catch (ThingsboardException e) { + return false; + } + } + private boolean isAlreadyAssigned(TenantId tenantId, GroupPermission groupPermission) { if (groupPermission.getEntityGroupId() != null) { return groupPermissionService.findGroupPermissionByTenantIdAndEntityGroupIdAndUserGroupIdAndRoleId(tenantId, diff --git a/application/src/main/java/org/thingsboard/server/controller/SignUpController.java b/application/src/main/java/org/thingsboard/server/controller/SignUpController.java index 8f3048c0ff..7a3cf1eec2 100644 --- a/application/src/main/java/org/thingsboard/server/controller/SignUpController.java +++ b/application/src/main/java/org/thingsboard/server/controller/SignUpController.java @@ -576,7 +576,7 @@ public class SignUpController extends BaseController { permission.setTenantId(tenantId); permission.setUserGroupId(usersEntityGroup.getId()); if (permission.getEntityGroupId() != null) { - EntityGroup entityGroup = entityGroupService.findEntityGroupById(tenantId, permission.getEntityGroupId()); + EntityGroup entityGroup = entityGroupService.findEntityGroupInfoByTenantIdAndId(tenantId, permission.getEntityGroupId()); if (entityGroup != null) { permission.setEntityGroupType(entityGroup.getType()); groupPermissionService.saveGroupPermission(tenantId, permission); diff --git a/application/src/main/java/org/thingsboard/server/service/edge/rpc/processor/telemetry/BaseTelemetryProcessor.java b/application/src/main/java/org/thingsboard/server/service/edge/rpc/processor/telemetry/BaseTelemetryProcessor.java index 04d7939917..0f51d5525d 100644 --- a/application/src/main/java/org/thingsboard/server/service/edge/rpc/processor/telemetry/BaseTelemetryProcessor.java +++ b/application/src/main/java/org/thingsboard/server/service/edge/rpc/processor/telemetry/BaseTelemetryProcessor.java @@ -193,7 +193,7 @@ public abstract class BaseTelemetryProcessor extends BaseEdgeProcessor { } } case ENTITY_GROUP -> { - EntityGroup entityGroup = edgeCtx.getEntityGroupService().findEntityGroupById(tenantId, new EntityGroupId(entityId.getId())); + EntityGroup entityGroup = edgeCtx.getEntityGroupService().findEntityGroupInfoByTenantIdAndId(tenantId, new EntityGroupId(entityId.getId())); if (entityGroup != null) { metaData.putValue("entityGroupName", entityGroup.getName()); metaData.putValue("entityGroupType", entityGroup.getType().name()); diff --git a/application/src/main/java/org/thingsboard/server/service/iot_hub/DefaultIotHubService.java b/application/src/main/java/org/thingsboard/server/service/iot_hub/DefaultIotHubService.java index e6eae82ef6..86b9c5580a 100644 --- a/application/src/main/java/org/thingsboard/server/service/iot_hub/DefaultIotHubService.java +++ b/application/src/main/java/org/thingsboard/server/service/iot_hub/DefaultIotHubService.java @@ -257,7 +257,7 @@ public class DefaultIotHubService implements IotHubService { } private EntityGroupInfo checkEntityGroup(SecurityUser user, EntityGroupId entityGroupId) throws ThingsboardException { - EntityGroupInfo entityGroup = entityGroupService.findEntityGroupInfoById(user.getTenantId(), entityGroupId); + EntityGroupInfo entityGroup = entityGroupService.findEntityGroupInfoByTenantIdAndId(user.getTenantId(), entityGroupId); if (entityGroup == null) { throw new IllegalArgumentException("Entity group with id [" + entityGroupId + "] is not found"); } diff --git a/application/src/main/java/org/thingsboard/server/service/scheduler/DefaultSchedulerService.java b/application/src/main/java/org/thingsboard/server/service/scheduler/DefaultSchedulerService.java index 7cd5cc685c..9859d9052b 100644 --- a/application/src/main/java/org/thingsboard/server/service/scheduler/DefaultSchedulerService.java +++ b/application/src/main/java/org/thingsboard/server/service/scheduler/DefaultSchedulerService.java @@ -274,7 +274,7 @@ public class DefaultSchedulerService extends AbstractPartitionBasedService entityGroupFuture = entityGroupService.findEntityGroupInfoByIdAsync(currentUser.getTenantId(), new EntityGroupId(entityId.getId())); + ListenableFuture entityGroupFuture = entityGroupService.findEntityGroupInfoByTenantIdAndIdAsync(currentUser.getTenantId(), new EntityGroupId(entityId.getId())); Futures.addCallback(entityGroupFuture, getCallback(callback, entityGroup -> { if (entityGroup == null) { return ValidationResult.entityNotFound("Entity group with requested id wasn't found!"); diff --git a/application/src/test/java/org/thingsboard/server/controller/CustomMenuControllerTest.java b/application/src/test/java/org/thingsboard/server/controller/CustomMenuControllerTest.java index 48d5a691f6..e6bebce6d1 100644 --- a/application/src/test/java/org/thingsboard/server/controller/CustomMenuControllerTest.java +++ b/application/src/test/java/org/thingsboard/server/controller/CustomMenuControllerTest.java @@ -657,6 +657,120 @@ public class CustomMenuControllerTest extends AbstractControllerTest { assertThat(currentMenu.get("items")).isEmpty(); } + @Test + public void testCustomerUserMenuIgnoresMenuOfOtherTenant() throws Exception { + loginDifferentTenant(); + CustomMenu otherTenantMenu = new CustomMenu(); + otherTenantMenu.setName(RandomStringUtils.randomAlphabetic(10)); + otherTenantMenu.setScope(CMScope.CUSTOMER); + otherTenantMenu.setAssigneeType(CMAssigneeType.NO_ASSIGN); + otherTenantMenu = doPost("/api/customMenu", otherTenantMenu, CustomMenu.class); + idsToRemove.add(otherTenantMenu.getUuidId()); + CustomMenuConfig otherTenantMenuConfig = putRandomMenuConfig(otherTenantMenu.getId()); + String otherTenantMenuUrl = ((CustomMenuItem) otherTenantMenuConfig.getItems().get(2)).getUrl(); + + loginTenantAdmin(); + Customer customer = doGet("/api/customer/" + customerId.getId(), Customer.class); + customer.setCustomMenuId(otherTenantMenu.getId()); + doPost("/api/customer", customer).andExpect(status().isOk()); + + loginCustomerUser(); + JsonNode customerUserMenu = doGet("/api/customMenu", JsonNode.class); + assertThat(customerUserMenu.toString()).doesNotContain(otherTenantMenuUrl); + } + + @Test + public void testTenantUserMenuIgnoresMenuOfOtherTenant() throws Exception { + loginDifferentTenant(); + CustomMenu otherTenantMenu = new CustomMenu(); + otherTenantMenu.setName(RandomStringUtils.randomAlphabetic(10)); + otherTenantMenu.setScope(CMScope.TENANT); + otherTenantMenu.setAssigneeType(CMAssigneeType.NO_ASSIGN); + otherTenantMenu = doPost("/api/customMenu", otherTenantMenu, CustomMenu.class); + idsToRemove.add(otherTenantMenu.getUuidId()); + CustomMenuConfig otherTenantMenuConfig = putRandomMenuConfig(otherTenantMenu.getId()); + String otherTenantMenuUrl = ((CustomMenuItem) otherTenantMenuConfig.getItems().get(2)).getUrl(); + + loginTenantAdmin(); + User tenantAdmin = doGet("/api/user/" + tenantAdminUserId.getId(), User.class); + tenantAdmin.setCustomMenuId(otherTenantMenu.getId()); + doPost("/api/user", tenantAdmin).andExpect(status().isOk()); + assertThat(doGet("/api/user/" + tenantAdminUserId.getId(), User.class).getCustomMenuId()).isEqualTo(otherTenantMenu.getId()); + + JsonNode tenantAdminMenu = doGet("/api/customMenu", JsonNode.class); + assertThat(tenantAdminMenu.toString()).doesNotContain(otherTenantMenuUrl); + } + + @Test + public void testCustomMenuAssigneeListContainsOnlyCustomersOfMenuTenant() throws Exception { + loginTenantAdmin(); + CustomMenu customerMenu = new CustomMenu(); + customerMenu.setName(RandomStringUtils.randomAlphabetic(10)); + customerMenu.setScope(CMScope.CUSTOMER); + customerMenu.setAssigneeType(CMAssigneeType.CUSTOMERS); + customerMenu = doPost("/api/customMenu?assignToList=" + customerId, customerMenu, CustomMenu.class); + + loginDifferentTenant(); + Customer otherTenantCustomer = new Customer(); + otherTenantCustomer.setTitle("Other Tenant Customer"); + otherTenantCustomer.setCustomMenuId(customerMenu.getId()); + otherTenantCustomer = doPost("/api/customer", otherTenantCustomer, Customer.class); + + loginTenantAdmin(); + List assigneeList = doGetTyped("/api/customMenu/" + customerMenu.getId() + "/assigneeList", new TypeReference<>() {}); + assertThat(assigneeList).extracting(EntityInfo::getId).containsExactly(customerId); + doDelete("/api/customMenu/" + customerMenu.getId() + "?force=true").andExpect(status().isOk()); + + loginDifferentTenant(); + Customer otherTenantCustomerAfterDelete = doGet("/api/customer/" + otherTenantCustomer.getId(), Customer.class); + assertThat(otherTenantCustomerAfterDelete.getCustomMenuId()).isEqualTo(customerMenu.getId()); + } + + @Test + public void testCustomMenuAssigneeListContainsOnlyUsersOfMenuTenant() throws Exception { + loginTenantAdmin(); + CustomMenu userMenu = new CustomMenu(); + userMenu.setName(RandomStringUtils.randomAlphabetic(10)); + userMenu.setScope(CMScope.TENANT); + userMenu.setAssigneeType(CMAssigneeType.USERS); + userMenu = doPost("/api/customMenu?assignToList=" + tenantAdminUserId, userMenu, CustomMenu.class); + + loginDifferentTenant(); + User otherTenantUser = new User(); + otherTenantUser.setAuthority(Authority.TENANT_ADMIN); + otherTenantUser.setTenantId(differentTenantId); + otherTenantUser.setEmail("othertenantuser@thingsboard.org"); + otherTenantUser.setCustomMenuId(userMenu.getId()); + otherTenantUser = doPost("/api/user", otherTenantUser, User.class); + assertThat(otherTenantUser.getCustomMenuId()).isEqualTo(userMenu.getId()); + + loginTenantAdmin(); + List assigneeList = doGetTyped("/api/customMenu/" + userMenu.getId() + "/assigneeList", new TypeReference<>() {}); + assertThat(assigneeList).extracting(EntityInfo::getId).containsExactly(tenantAdminUserId); + doDelete("/api/customMenu/" + userMenu.getId() + "?force=true").andExpect(status().isOk()); + + loginDifferentTenant(); + User otherTenantUserAfterDelete = doGet("/api/user/" + otherTenantUser.getId(), User.class); + assertThat(otherTenantUserAfterDelete.getCustomMenuId()).isEqualTo(userMenu.getId()); + } + + @Test + public void testTenantUserGetsAssignedSystemMenu() throws Exception { + loginSysAdmin(); + CustomMenu systemMenu = new CustomMenu(); + systemMenu.setName(RandomStringUtils.randomAlphabetic(10)); + systemMenu.setScope(CMScope.TENANT); + systemMenu.setAssigneeType(CMAssigneeType.NO_ASSIGN); + systemMenu = doPost("/api/customMenu", systemMenu, CustomMenu.class); + idsToRemove.add(systemMenu.getUuidId()); + CustomMenuConfig systemMenuConfig = putRandomMenuConfig(systemMenu.getId()); + doPut("/api/customMenu/" + systemMenu.getId() + "/assign/USERS", List.of(tenantAdminUserId.getId())); + + loginTenantAdmin(); + JsonNode tenantAdminMenu = doGet("/api/customMenu", JsonNode.class); + assertCustomMenuConfig(tenantAdminMenu, systemMenuConfig); + } + private MvcResult getUserCustomMenu() throws Exception { return getUserCustomMenu(null); } diff --git a/application/src/test/java/org/thingsboard/server/controller/EntityGroupControllerTest.java b/application/src/test/java/org/thingsboard/server/controller/EntityGroupControllerTest.java index a6cbf93cca..23be30acc4 100644 --- a/application/src/test/java/org/thingsboard/server/controller/EntityGroupControllerTest.java +++ b/application/src/test/java/org/thingsboard/server/controller/EntityGroupControllerTest.java @@ -13,6 +13,7 @@ import org.testcontainers.shaded.org.apache.commons.lang3.RandomStringUtils; import org.thingsboard.common.util.JacksonUtil; import org.thingsboard.server.common.data.Dashboard; import org.thingsboard.server.common.data.Device; +import org.thingsboard.server.common.data.EntityInfo; import org.thingsboard.server.common.data.EntityType; import org.thingsboard.server.common.data.Tenant; import org.thingsboard.server.common.data.User; @@ -29,6 +30,7 @@ import org.thingsboard.server.common.data.page.PageData; import org.thingsboard.server.common.data.page.PageLink; import org.thingsboard.server.common.data.permission.GroupPermission; import org.thingsboard.server.common.data.permission.GroupPermissionInfo; +import org.thingsboard.server.common.data.permission.Operation; import org.thingsboard.server.common.data.permission.ShareGroupRequest; import org.thingsboard.server.common.data.role.Role; import org.thingsboard.server.common.data.role.RoleType; @@ -45,6 +47,8 @@ import java.util.stream.Collectors; import static org.assertj.core.api.Assertions.assertThat; import static org.hamcrest.Matchers.containsString; +import static org.hamcrest.Matchers.is; +import static org.hamcrest.Matchers.not; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; @DaoSqlTest @@ -180,11 +184,211 @@ public class EntityGroupControllerTest extends AbstractControllerTest { loginCustomerAdminUser(); otherTenantEntityGroup.setOwnerId(customerId); doPost("/api/entityGroup", otherTenantEntityGroup) - .andExpect(status().isForbidden()); + .andExpect(status().isNotFound()); assertThat(entityGroupService.findEntityGroupById(differentTenantId, otherTenantEntityGroup.getId()).getOwnerId()).isEqualTo(differentTenantId); } + @Test + public void testGetEntityGroupInfosByIdsReturnsOnlyOwnTenantGroups() throws Exception { + loginTenantAdmin(); + EntityGroup ownGroup = new EntityGroup(); + ownGroup.setName("Own Device Group"); + ownGroup.setType(EntityType.DEVICE); + ownGroup = doPost("/api/entityGroup", ownGroup, EntityGroup.class); + + loginDifferentTenant(); + EntityGroup otherTenantGroup = new EntityGroup(); + otherTenantGroup.setName("Other Tenant Device Group"); + otherTenantGroup.setType(EntityType.DEVICE); + otherTenantGroup = doPost("/api/entityGroup", otherTenantGroup, EntityGroup.class); + + loginTenantAdmin(); + List entityInfos = doGetTyped("/api/entityGroupInfos?entityGroupIds=" + ownGroup.getId().getId() + "," + otherTenantGroup.getId().getId(), + new TypeReference<>() {}); + assertThat(entityInfos).extracting(EntityInfo::getId).containsExactly(ownGroup.getId()); + } + + @Test + public void testGetEntityGroupInfosByIdsReturnsOnlyReadableGroups() throws Exception { + loginTenantAdmin(); + EntityGroup tenantGroup = new EntityGroup(); + tenantGroup.setName("Tenant Device Group"); + tenantGroup.setType(EntityType.DEVICE); + tenantGroup = doPost("/api/entityGroup", tenantGroup, EntityGroup.class); + + loginCustomerAdminUser(); + EntityGroup customerGroup = new EntityGroup(); + customerGroup.setName("Customer Device Group"); + customerGroup.setType(EntityType.DEVICE); + customerGroup.setOwnerId(customerId); + customerGroup = doPost("/api/entityGroup", customerGroup, EntityGroup.class); + + List entityInfos = doGetTyped("/api/entityGroupInfos?entityGroupIds=" + customerGroup.getId().getId() + "," + tenantGroup.getId().getId(), + new TypeReference<>() {}); + assertThat(entityInfos).extracting(EntityInfo::getId).containsExactly(customerGroup.getId()); + } + + @Test + public void testShareGroupWithUserGroupOfOtherTenantReturnsNotFound() throws Exception { + loginDifferentTenant(); + EntityGroup otherTenantUserGroup = new EntityGroup(); + otherTenantUserGroup.setName("Other Tenant User Group"); + otherTenantUserGroup.setType(EntityType.USER); + otherTenantUserGroup = doPost("/api/entityGroup", otherTenantUserGroup, EntityGroup.class); + + loginTenantAdmin(); + EntityGroup deviceGroup = new EntityGroup(); + deviceGroup.setName("Shared Device Group"); + deviceGroup.setType(EntityType.DEVICE); + deviceGroup = doPost("/api/entityGroup", deviceGroup, EntityGroup.class); + + ShareGroupRequest shareGroupRequest = new ShareGroupRequest(tenantId, false, otherTenantUserGroup.getId(), true, null); + doPost("/api/entityGroup/" + deviceGroup.getId().getId() + "/share", shareGroupRequest) + .andExpect(status().isNotFound()) + .andExpect(statusReason(not(containsString(otherTenantUserGroup.getName())))); + } + + @Test + public void testShareGroupV2WithUserGroupOfOtherTenantReturnsNotFound() throws Exception { + loginDifferentTenant(); + EntityGroup otherTenantUserGroup = new EntityGroup(); + otherTenantUserGroup.setName("Other Tenant User Group"); + otherTenantUserGroup.setType(EntityType.USER); + otherTenantUserGroup = doPost("/api/entityGroup", otherTenantUserGroup, EntityGroup.class); + + loginTenantAdmin(); + EntityGroup deviceGroup = new EntityGroup(); + deviceGroup.setName("Shared Device Group"); + deviceGroup.setType(EntityType.DEVICE); + deviceGroup = doPost("/api/entityGroup", deviceGroup, EntityGroup.class); + + ShareGroupRequest shareGroupRequest = new ShareGroupRequest(tenantId, false, otherTenantUserGroup.getId(), true, null); + doPost("/api/v2/entityGroup/" + deviceGroup.getId().getId() + "/share", shareGroupRequest) + .andExpect(status().isNotFound()) + .andExpect(statusReason(not(containsString(otherTenantUserGroup.getName())))); + } + + @Test + public void testShareGroupWithAllUsersGroupOfOtherTenantReturnsNotFound() throws Exception { + loginDifferentTenant(); + loginTenantAdmin(); + EntityGroup deviceGroup = createDeviceGroup("Shared Device Group", tenantId); + + ShareGroupRequest unknownOwnerRequest = new ShareGroupRequest(TenantId.fromUUID(UUID.randomUUID()), true, null, true, null); + doPost("/api/entityGroup/{entityGroupId}/share", unknownOwnerRequest, deviceGroup.getId().toString()) + .andExpect(status().isNotFound()) + .andExpect(statusReason(is(msgErrorNotFound))); + ShareGroupRequest otherTenantRequest = new ShareGroupRequest(differentTenantId, true, null, true, null); + doPost("/api/entityGroup/{entityGroupId}/share", otherTenantRequest, deviceGroup.getId().toString()) + .andExpect(status().isNotFound()) + .andExpect(statusReason(is(msgErrorNotFound))); + assertThat(findSharedUserGroupIds(deviceGroup)).isEmpty(); + } + + @Test + public void testShareGroupWithAllUsersGroupOfOwnCustomerSharesWithThatGroup() throws Exception { + loginTenantAdmin(); + EntityGroup deviceGroup = createDeviceGroup("Shared Device Group", tenantId); + EntityGroup customerAllUsersGroup = entityGroupService.findEntityGroupByTypeAndName(tenantId, customerId, + EntityType.USER, EntityGroup.GROUP_ALL_NAME).get(); + + ShareGroupRequest shareGroupRequest = new ShareGroupRequest(customerId, true, null, true, null); + doPost("/api/entityGroup/{entityGroupId}/share", shareGroupRequest, deviceGroup.getId().toString()) + .andExpect(status().isOk()); + assertThat(findSharedUserGroupIds(deviceGroup)).containsExactly(customerAllUsersGroup.getId()); + } + + @Test + public void testShareGroupV2WithAllUsersGroupOfOtherTenantReturnsNotFound() throws Exception { + loginDifferentTenant(); + loginTenantAdmin(); + EntityGroup deviceGroup = createDeviceGroup("Shared Device Group", tenantId); + + ShareGroupRequest unknownOwnerRequest = new ShareGroupRequest(TenantId.fromUUID(UUID.randomUUID()), true, null, true, null); + doPost("/api/v2/entityGroup/{entityGroupId}/share", unknownOwnerRequest, deviceGroup.getId().toString()) + .andExpect(status().isNotFound()) + .andExpect(statusReason(is(msgErrorNotFound))); + ShareGroupRequest otherTenantRequest = new ShareGroupRequest(differentTenantId, true, null, true, null); + doPost("/api/v2/entityGroup/{entityGroupId}/share", otherTenantRequest, deviceGroup.getId().toString()) + .andExpect(status().isNotFound()) + .andExpect(statusReason(is(msgErrorNotFound))); + assertThat(findSharedUserGroupIds(deviceGroup)).isEmpty(); + } + + @Test + public void testShareGroupV2WithAllUsersGroupOfOwnCustomerSharesWithThatGroup() throws Exception { + loginTenantAdmin(); + EntityGroup deviceGroup = createDeviceGroup("Shared Device Group", tenantId); + EntityGroup customerAllUsersGroup = entityGroupService.findEntityGroupByTypeAndName(tenantId, customerId, + EntityType.USER, EntityGroup.GROUP_ALL_NAME).get(); + + ShareGroupRequest shareGroupRequest = new ShareGroupRequest(customerId, true, null, true, null); + doPost("/api/v2/entityGroup/{entityGroupId}/share", shareGroupRequest, deviceGroup.getId().toString()) + .andExpect(status().isOk()); + assertThat(findSharedUserGroupIds(deviceGroup)).containsExactly(customerAllUsersGroup.getId()); + } + + @Test + public void testShareGroupToChildOwnerUserGroupWithGroupsOfOtherTenantReturnsNotFound() throws Exception { + loginDifferentTenant(); + EntityGroup otherTenantUserGroup = new EntityGroup(); + otherTenantUserGroup.setName("Other Tenant User Group"); + otherTenantUserGroup.setType(EntityType.USER); + otherTenantUserGroup = doPost("/api/entityGroup", otherTenantUserGroup, EntityGroup.class); + EntityGroup otherTenantDeviceGroup = new EntityGroup(); + otherTenantDeviceGroup.setName("Other Tenant Device Group"); + otherTenantDeviceGroup.setType(EntityType.DEVICE); + otherTenantDeviceGroup = doPost("/api/entityGroup", otherTenantDeviceGroup, EntityGroup.class); + + loginTenantAdmin(); + EntityGroup deviceGroup = new EntityGroup(); + deviceGroup.setName("Shared Device Group"); + deviceGroup.setType(EntityType.DEVICE); + deviceGroup = doPost("/api/entityGroup", deviceGroup, EntityGroup.class); + EntityGroup userGroup = new EntityGroup(); + userGroup.setName("Own User Group"); + userGroup.setType(EntityType.USER); + userGroup = doPost("/api/entityGroup", userGroup, EntityGroup.class); + Role role = new Role(); + role.setName("Read Group Role"); + role.setType(RoleType.GROUP); + role.setPermissions(JacksonUtil.valueToTree(List.of(Operation.READ))); + role = doPost("/api/role", role, Role.class); + + doPost("/api/entityGroup/" + deviceGroup.getId().getId() + "/" + otherTenantUserGroup.getId().getId() + "/" + role.getId().getId() + "/share") + .andExpect(status().isNotFound()); + doPost("/api/entityGroup/" + otherTenantDeviceGroup.getId().getId() + "/" + userGroup.getId().getId() + "/" + role.getId().getId() + "/share") + .andExpect(status().isNotFound()); + } + + @Test + public void testGetAttributesOfEntityGroupOfOtherTenantReturnsNotFound() throws Exception { + loginDifferentTenant(); + EntityGroup otherTenantGroup = new EntityGroup(); + otherTenantGroup.setName("Other Tenant Asset Group"); + otherTenantGroup.setType(EntityType.ASSET); + otherTenantGroup = doPost("/api/entityGroup", otherTenantGroup, EntityGroup.class); + + loginTenantAdmin(); + doGetAsync("/api/plugins/telemetry/ENTITY_GROUP/" + otherTenantGroup.getId().getId() + "/values/attributes") + .andExpect(status().isNotFound()); + } + + @Test + public void testGetEntityGroupOfOtherTenantReturnsNotFound() throws Exception { + loginDifferentTenant(); + EntityGroup otherTenantGroup = new EntityGroup(); + otherTenantGroup.setName("Other Tenant Asset Group"); + otherTenantGroup.setType(EntityType.ASSET); + otherTenantGroup = doPost("/api/entityGroup", otherTenantGroup, EntityGroup.class); + + loginTenantAdmin(); + doGet("/api/entityGroup/" + otherTenantGroup.getId().getId()) + .andExpect(status().isNotFound()) + .andExpect(statusReason(not(containsString(otherTenantGroup.getName())))); + } + @Test public void testShouldNotUpdateNonExistingEntityGroup() throws Exception { loginTenantAdmin(); @@ -577,4 +781,9 @@ public class EntityGroupControllerTest extends AbstractControllerTest { .getData().stream().map(GroupPermission::getRoleId).collect(Collectors.toList()); } + private List findSharedUserGroupIds(EntityGroup entityGroup) { + return groupPermissionService.findGroupPermissionByTenantIdAndEntityGroupId(tenantId, entityGroup.getId(), new PageLink(100)) + .getData().stream().map(GroupPermission::getUserGroupId).collect(Collectors.toList()); + } + } diff --git a/application/src/test/java/org/thingsboard/server/controller/GroupPermissionControllerTest.java b/application/src/test/java/org/thingsboard/server/controller/GroupPermissionControllerTest.java index cb0257c9f0..7c3cd65e07 100644 --- a/application/src/test/java/org/thingsboard/server/controller/GroupPermissionControllerTest.java +++ b/application/src/test/java/org/thingsboard/server/controller/GroupPermissionControllerTest.java @@ -7,6 +7,7 @@ import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Test; +import org.springframework.beans.factory.annotation.Autowired; import org.testcontainers.shaded.org.apache.commons.lang3.RandomStringUtils; import org.thingsboard.server.common.data.Customer; import org.thingsboard.server.common.data.EntityType; @@ -14,12 +15,15 @@ import org.thingsboard.server.common.data.Tenant; import org.thingsboard.server.common.data.User; import org.thingsboard.server.common.data.group.EntityGroup; import org.thingsboard.server.common.data.id.EntityId; +import org.thingsboard.server.common.data.page.PageLink; import org.thingsboard.server.common.data.permission.AllowedPermissionsInfo; import org.thingsboard.server.common.data.permission.GroupPermission; import org.thingsboard.server.common.data.permission.GroupPermissionInfo; +import org.thingsboard.server.common.data.permission.ShareGroupRequest; import org.thingsboard.server.common.data.role.Role; import org.thingsboard.server.common.data.role.RoleType; import org.thingsboard.server.common.data.security.Authority; +import org.thingsboard.server.dao.grouppermission.GroupPermissionService; import org.thingsboard.server.dao.service.DaoSqlTest; import java.util.ArrayList; @@ -35,6 +39,9 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers. @DaoSqlTest public class GroupPermissionControllerTest extends AbstractControllerTest { + @Autowired + private GroupPermissionService groupPermissionService; + private IdComparator idComparator; private Tenant savedTenant; private User tenantAdmin; @@ -278,6 +285,97 @@ public class GroupPermissionControllerTest extends AbstractControllerTest { checkPermissionOwners(loadedGroupPermissionsInfo, List.of(subCustomerId)); } + @Test + public void testLoadUserGroupPermissionInfosReturnsOnlyOwnTenantData() throws Exception { + loginDifferentTenant(); + Role otherTenantRole = doPost("/api/role", newRole("Other Tenant Role", RoleType.GROUP), Role.class); + EntityGroup otherTenantGroup = new EntityGroup(); + otherTenantGroup.setType(EntityType.DEVICE); + otherTenantGroup.setName("Other Tenant Device Group"); + otherTenantGroup = doPost("/api/entityGroup", otherTenantGroup, EntityGroup.class); + + loginTenantAdmin(); + Role ownRole = doPost("/api/role", newRole("Own Role", RoleType.GROUP), Role.class); + + GroupPermission otherTenantRolePermission = new GroupPermission(); + otherTenantRolePermission.setRoleId(otherTenantRole.getId()); + GroupPermission otherTenantGroupPermission = new GroupPermission(); + otherTenantGroupPermission.setRoleId(ownRole.getId()); + otherTenantGroupPermission.setEntityGroupId(otherTenantGroup.getId()); + + List infos = doPostWithTypedResponse("/api/userGroup/groupPermissions/info", + List.of(otherTenantRolePermission, otherTenantGroupPermission), new TypeReference<>() {}); + assertThat(infos).isEmpty(); + } + + @Test + public void testLoadUserGroupPermissionInfosReturnsOnlyReadableGroups() throws Exception { + loginTenantAdmin(); + Role role = doPost("/api/role", newRole("Group Role", RoleType.GROUP), Role.class); + EntityGroup tenantGroup = new EntityGroup(); + tenantGroup.setType(EntityType.DEVICE); + tenantGroup.setName("Tenant Device Group"); + tenantGroup = doPost("/api/entityGroup", tenantGroup, EntityGroup.class); + + loginCustomerAdminUser(); + EntityGroup customerGroup = new EntityGroup(); + customerGroup.setType(EntityType.DEVICE); + customerGroup.setName("Customer Device Group"); + customerGroup.setOwnerId(customerId); + customerGroup = doPost("/api/entityGroup", customerGroup, EntityGroup.class); + + GroupPermission tenantGroupPermission = new GroupPermission(); + tenantGroupPermission.setRoleId(role.getId()); + tenantGroupPermission.setEntityGroupId(tenantGroup.getId()); + GroupPermission customerGroupPermission = new GroupPermission(); + customerGroupPermission.setRoleId(role.getId()); + customerGroupPermission.setEntityGroupId(customerGroup.getId()); + + List infos = doPostWithTypedResponse("/api/userGroup/groupPermissions/info", + List.of(tenantGroupPermission, customerGroupPermission), new TypeReference<>() {}); + assertThat(infos).extracting(GroupPermissionInfo::getEntityGroupId).containsExactly(customerGroup.getId()); + } + + @Test + public void testLoadUserGroupPermissionInfosKeepsSystemRoles() throws Exception { + loginTenantAdmin(); + EntityGroup tenantAdminsGroup = findGroupByOwnerIdTypeAndName(tenantId, EntityType.USER, EntityGroup.GROUP_TENANT_ADMINS_NAME); + List storedInfos = doGetTyped("/api/userGroup/" + tenantAdminsGroup.getId() + "/groupPermissions", + new TypeReference<>() {}); + assertThat(storedInfos).isNotEmpty(); + assertThat(storedInfos).allSatisfy(info -> assertThat(info.getRole().getTenantId().isSysTenantId()).isTrue()); + + List permissions = storedInfos.stream().map(GroupPermission::new).toList(); + List infos = doPostWithTypedResponse("/api/userGroup/groupPermissions/info", permissions, new TypeReference<>() {}); + assertThat(infos).hasSameSizeAs(permissions); + assertThat(infos).allSatisfy(info -> assertThat(info.getRole()).isNotNull()); + } + + @Test + public void testShareGroupWithRoleOfOtherTenantIsRejected() throws Exception { + loginDifferentTenant(); + Role otherTenantRole = doPost("/api/role", newRole("Other Tenant Role", RoleType.GROUP), Role.class); + + loginTenantAdmin(); + EntityGroup deviceGroup = new EntityGroup(); + deviceGroup.setType(EntityType.DEVICE); + deviceGroup.setName("Shared Device Group"); + deviceGroup = doPost("/api/entityGroup", deviceGroup, EntityGroup.class); + + ShareGroupRequest shareGroupRequest = new ShareGroupRequest(tenantId, true, null, false, List.of(otherTenantRole.getId())); + doPost("/api/entityGroup/{entityGroupId}/share", shareGroupRequest, deviceGroup.getId().toString()) + .andExpect(status().isForbidden()); + + assertThat(groupPermissionService.findGroupPermissionByTenantIdAndRoleId(tenantId, otherTenantRole.getId(), new PageLink(10)).getData()).isEmpty(); + } + + private Role newRole(String roleName, RoleType roleType) { + Role role = new Role(); + role.setName(roleName); + role.setType(roleType); + return role; + } + @Test public void testCustomerAdminCannotUpdateTenantGroupPermission() throws Exception { loginTenantAdmin(); diff --git a/application/src/test/java/org/thingsboard/server/controller/SignUpControllerSqlTest.java b/application/src/test/java/org/thingsboard/server/controller/SignUpControllerSqlTest.java index 3305001fbd..04c3a93bf7 100644 --- a/application/src/test/java/org/thingsboard/server/controller/SignUpControllerSqlTest.java +++ b/application/src/test/java/org/thingsboard/server/controller/SignUpControllerSqlTest.java @@ -16,6 +16,7 @@ import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.test.context.bean.override.mockito.MockitoSpyBean; import org.testcontainers.shaded.org.apache.commons.lang3.RandomStringUtils; +import org.thingsboard.common.util.JacksonUtil; import org.thingsboard.server.common.data.AdminSettings; import org.thingsboard.server.common.data.Customer; import org.thingsboard.server.common.data.CustomerInfo; @@ -60,6 +61,7 @@ import org.thingsboard.server.common.data.signup.SignUpResult; import org.thingsboard.server.common.data.wl.WhiteLabelingType; import org.thingsboard.server.dao.customer.CustomerService; import org.thingsboard.server.dao.group.EntityGroupService; +import org.thingsboard.server.dao.grouppermission.GroupPermissionService; import org.thingsboard.server.dao.menu.CustomMenuDao; import org.thingsboard.server.dao.service.DaoSqlTest; import org.thingsboard.server.dao.settings.AdminSettingsService; @@ -134,6 +136,9 @@ public class SignUpControllerSqlTest extends AbstractControllerTest { @Autowired protected WhiteLabelingService whiteLabelingService; + @Autowired + private GroupPermissionService groupPermissionService; + @Before public void beforeTest() throws Exception { loginTenantAdmin(); @@ -373,6 +378,31 @@ public class SignUpControllerSqlTest extends AbstractControllerTest { removeCreatedUser(user); } + @Test + public void testSelfRegisterUserSkipsPermissionForGroupOfOtherTenant() throws Exception { + loginDifferentTenant(); + EntityGroup otherTenantGroup = new EntityGroup(); + otherTenantGroup.setName("Other Tenant Device Group"); + otherTenantGroup.setType(EntityType.DEVICE); + otherTenantGroup = doPost("/api/entityGroup", otherTenantGroup, EntityGroup.class); + + loginTenantAdmin(); + Role role = new Role(); + role.setName("Self Registration Group Role"); + role.setType(RoleType.GROUP); + role.setPermissions(JacksonUtil.toJsonNode("[\"READ\"]")); + role = doPost("/api/role", role, Role.class); + GroupPermission permission = new GroupPermission(); + permission.setRoleId(role.getId()); + permission.setEntityGroupId(otherTenantGroup.getId()); + createWebSelfRegistrationSettings(List.of(permission)); + + doSignUp(createWebSignUpRequest(CUSTOMER_TEST_EMAIL)); + + assertThat(groupPermissionService.findGroupPermissionByTenantIdAndRoleId(tenantId, role.getId(), new PageLink(10)).getData()).isEmpty(); + removeCreatedUser(userService.findUserByEmail(tenantId, CUSTOMER_TEST_EMAIL)); + } + @Test public void testResendEmailActivationForPendingSignUpUser() throws Exception { createWebSelfRegistrationSettings(); diff --git a/application/src/test/java/org/thingsboard/server/edge/DeviceEdgeTest.java b/application/src/test/java/org/thingsboard/server/edge/DeviceEdgeTest.java index db600a0d17..49736cdb3d 100644 --- a/application/src/test/java/org/thingsboard/server/edge/DeviceEdgeTest.java +++ b/application/src/test/java/org/thingsboard/server/edge/DeviceEdgeTest.java @@ -679,6 +679,61 @@ public class DeviceEdgeTest extends AbstractEdgeTest { Assert.assertEquals(deviceName + " Updated", device.getName()); } + @Test + public void testSendDeviceToCloudAddsDeviceOnlyToGroupOfEdgeTenant() throws Exception { + loginDifferentTenant(); + EntityGroup otherTenantGroup = new EntityGroup(); + otherTenantGroup.setType(EntityType.DEVICE); + otherTenantGroup.setName("Other Tenant Device Group"); + otherTenantGroup = doPost("/api/entityGroup", otherTenantGroup, EntityGroup.class); + loginTenantAdmin(); + + Device deviceMsg = buildDeviceForUplinkMsg("Edge Device In Group", "test"); + UplinkMsg.Builder uplinkMsgBuilder = UplinkMsg.newBuilder(); + DeviceUpdateMsg.Builder deviceUpdateMsgBuilder = DeviceUpdateMsg.newBuilder(); + deviceUpdateMsgBuilder.setIdMSB(deviceMsg.getUuidId().getMostSignificantBits()); + deviceUpdateMsgBuilder.setIdLSB(deviceMsg.getUuidId().getLeastSignificantBits()); + deviceUpdateMsgBuilder.setEntityGroupIdMSB(otherTenantGroup.getUuidId().getMostSignificantBits()); + deviceUpdateMsgBuilder.setEntityGroupIdLSB(otherTenantGroup.getUuidId().getLeastSignificantBits()); + deviceUpdateMsgBuilder.setEntity(JacksonUtil.toString(deviceMsg)); + deviceUpdateMsgBuilder.setMsgType(UpdateMsgType.ENTITY_CREATED_RPC_MESSAGE); + uplinkMsgBuilder.addDeviceUpdateMsg(deviceUpdateMsgBuilder.build()); + + edgeImitator.expectResponsesAmount(1); + edgeImitator.sendUplinkMsg(uplinkMsgBuilder.build()); + Assert.assertTrue(edgeImitator.waitForResponses()); + + Device device = doGet("/api/device/" + deviceMsg.getId().getId(), Device.class); + Assert.assertNotNull(device); + Assert.assertFalse(entityGroupService.isEntityInGroup(differentTenantId, device.getId(), otherTenantGroup.getId())); + } + + @Test + public void testDeleteDeviceFromGroupOnCloudKeepsGroupsOfOtherTenant() throws Exception { + loginDifferentTenant(); + EntityGroup otherTenantGroup = new EntityGroup(); + otherTenantGroup.setType(EntityType.DEVICE); + otherTenantGroup.setName("Other Tenant Device Group"); + otherTenantGroup = doPost("/api/entityGroup", otherTenantGroup, EntityGroup.class); + Device otherTenantDevice = saveDevice("Other Tenant Device", "test", otherTenantGroup.getId()); + loginTenantAdmin(); + + UplinkMsg.Builder uplinkMsgBuilder = UplinkMsg.newBuilder(); + DeviceUpdateMsg.Builder deviceUpdateMsgBuilder = DeviceUpdateMsg.newBuilder(); + deviceUpdateMsgBuilder.setIdMSB(otherTenantDevice.getUuidId().getMostSignificantBits()); + deviceUpdateMsgBuilder.setIdLSB(otherTenantDevice.getUuidId().getLeastSignificantBits()); + deviceUpdateMsgBuilder.setEntityGroupIdMSB(otherTenantGroup.getUuidId().getMostSignificantBits()); + deviceUpdateMsgBuilder.setEntityGroupIdLSB(otherTenantGroup.getUuidId().getLeastSignificantBits()); + deviceUpdateMsgBuilder.setMsgType(UpdateMsgType.ENTITY_DELETED_RPC_MESSAGE); + uplinkMsgBuilder.addDeviceUpdateMsg(deviceUpdateMsgBuilder.build()); + + edgeImitator.expectResponsesAmount(1); + edgeImitator.sendUplinkMsg(uplinkMsgBuilder.build()); + Assert.assertTrue(edgeImitator.waitForResponses()); + + Assert.assertTrue(entityGroupService.isEntityInGroup(differentTenantId, otherTenantDevice.getId(), otherTenantGroup.getId())); + } + @Test public void testRpcCall() throws Exception { Device device = saveDeviceOnCloudAndVerifyDeliveryToEdge(); diff --git a/application/src/test/java/org/thingsboard/server/edge/TelemetryEdgeTest.java b/application/src/test/java/org/thingsboard/server/edge/TelemetryEdgeTest.java index 031b646b00..c4f4e25942 100644 --- a/application/src/test/java/org/thingsboard/server/edge/TelemetryEdgeTest.java +++ b/application/src/test/java/org/thingsboard/server/edge/TelemetryEdgeTest.java @@ -390,4 +390,49 @@ public class TelemetryEdgeTest extends AbstractEdgeTest { }); } + @Test + public void testSendEntityGroupAttributesAndTelemetryForGroupOfDifferentTenantToCloud() throws Exception { + loginDifferentTenant(); + EntityGroup entityGroup = new EntityGroup(); + entityGroup.setType(EntityType.DEVICE); + entityGroup.setName("Different Tenant Device Group"); + EntityGroup savedEntityGroup = doPost("/api/entityGroup", entityGroup, EntityGroup.class); + loginTenantAdmin(); + + EntityDataProto entityData = EntityDataProto.newBuilder() + .setEntityIdMSB(savedEntityGroup.getUuidId().getMostSignificantBits()) + .setEntityIdLSB(savedEntityGroup.getUuidId().getLeastSignificantBits()) + .setEntityType(EntityType.ENTITY_GROUP.name()) + .setAttributesUpdatedMsg(TransportProtos.PostAttributeMsg.newBuilder() + .addKv(TransportProtos.KeyValueProto.newBuilder() + .setKey("groupKey") + .setType(TransportProtos.KeyValueType.STRING_V) + .setStringV("groupValue").build()) + .build()) + .setPostAttributeScope(DataConstants.SERVER_SCOPE) + .setPostTelemetryMsg(TransportProtos.PostTelemetryMsg.newBuilder() + .addTsKvList(TransportProtos.TsKvListProto.newBuilder() + .setTs(System.currentTimeMillis()) + .addKv(TransportProtos.KeyValueProto.newBuilder() + .setKey("groupTemperature") + .setType(TransportProtos.KeyValueType.LONG_V) + .setLongV(25).build()) + .build()) + .build()) + .build(); + sendUplinkMsgAndWaitForResponse(uplinkMsgBuilder -> uplinkMsgBuilder.addEntityData(entityData)); + + loginDifferentTenant(); + String keysUrl = "/api/plugins/telemetry/ENTITY_GROUP/" + savedEntityGroup.getUuidId() + "/keys/"; + Awaitility.await() + .pollDelay(3, TimeUnit.SECONDS) + .atMost(10, TimeUnit.SECONDS) + .untilAsserted(() -> { + List attributeKeys = doGetAsyncTyped(keysUrl + "attributes/" + DataConstants.SERVER_SCOPE, new TypeReference<>() {}); + Assert.assertTrue(attributeKeys.isEmpty()); + List timeseriesKeys = doGetAsyncTyped(keysUrl + "timeseries", new TypeReference<>() {}); + Assert.assertTrue(timeseriesKeys.isEmpty()); + }); + } + } diff --git a/application/src/test/java/org/thingsboard/server/service/scheduler/sql/SchedulerEventTest.java b/application/src/test/java/org/thingsboard/server/service/scheduler/sql/SchedulerEventTest.java index 4bc4fbed43..72de51dc2d 100644 --- a/application/src/test/java/org/thingsboard/server/service/scheduler/sql/SchedulerEventTest.java +++ b/application/src/test/java/org/thingsboard/server/service/scheduler/sql/SchedulerEventTest.java @@ -4,6 +4,8 @@ package org.thingsboard.server.service.scheduler.sql; import com.fasterxml.jackson.databind.node.ObjectNode; import com.google.common.util.concurrent.ListeningScheduledExecutorService; +import com.google.common.util.concurrent.MoreExecutors; +import org.awaitility.Awaitility; import org.junit.Before; import org.junit.Test; import org.mockito.Mockito; @@ -11,13 +13,22 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.util.ReflectionTestUtils; import org.thingsboard.common.util.JacksonUtil; import org.thingsboard.server.common.data.Device; +import org.thingsboard.server.common.data.DeviceProfileInfo; +import org.thingsboard.server.common.data.EntityType; +import org.thingsboard.server.common.data.OtaPackageInfo; +import org.thingsboard.server.common.data.SaveOtaPackageInfoRequest; +import org.thingsboard.server.common.data.group.EntityGroup; +import org.thingsboard.server.common.data.id.DeviceProfileId; import org.thingsboard.server.common.data.id.EntityId; import org.thingsboard.server.common.data.scheduler.SchedulerEvent; import org.thingsboard.server.controller.AbstractControllerTest; +import org.thingsboard.server.dao.ota.DeviceGroupOtaPackageService; import org.thingsboard.server.dao.service.DaoSqlTest; import org.thingsboard.server.queue.discovery.TbServiceInfoProvider; import org.thingsboard.server.service.scheduler.DefaultSchedulerService; +import java.util.Map; +import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; @@ -31,7 +42,9 @@ import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.timeout; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; +import static org.thingsboard.server.common.data.DataConstants.UPDATE_FIRMWARE; import static org.thingsboard.server.common.data.msg.TbMsgType.RPC_CALL_FROM_SERVER_TO_DEVICE; +import static org.thingsboard.server.common.data.ota.OtaPackageType.FIRMWARE; import static org.thingsboard.server.dao.scheduler.BaseSchedulerEventService.getOriginatorId; @DaoSqlTest @@ -43,6 +56,9 @@ public class SchedulerEventTest extends AbstractControllerTest { @Autowired TbServiceInfoProvider serviceInfoProvider; + @Autowired + DeviceGroupOtaPackageService deviceGroupOtaPackageService; + @Before public void before() throws Exception { loginTenantAdmin(); @@ -126,6 +142,52 @@ public class SchedulerEventTest extends AbstractControllerTest { ), any()); } + @Test + public void shouldNotUpdateFirmwareOfDeviceGroupOfAnotherTenant() throws Exception { + DeviceProfileInfo deviceProfile = doGet("/api/deviceProfileInfo/default", DeviceProfileInfo.class); + SaveOtaPackageInfoRequest firmwareRequest = new SaveOtaPackageInfoRequest(); + firmwareRequest.setDeviceProfileId(new DeviceProfileId(deviceProfile.getId().getId())); + firmwareRequest.setType(FIRMWARE); + firmwareRequest.setTitle("My firmware"); + firmwareRequest.setVersion("v1.0"); + firmwareRequest.setUsesUrl(false); + OtaPackageInfo firmware = doPost("/api/otaPackage", firmwareRequest, OtaPackageInfo.class); + + loginDifferentTenant(); + EntityGroup otherTenantGroup = new EntityGroup(); + otherTenantGroup.setName("Other Tenant Devices"); + otherTenantGroup.setType(EntityType.DEVICE); + otherTenantGroup = doPost("/api/entityGroup", otherTenantGroup, EntityGroup.class); + loginTenantAdmin(); + + Object originalExecutor = ReflectionTestUtils.getField(schedulerService, "scheduledExecutor"); + ListeningScheduledExecutorService executor = MoreExecutors.listeningDecorator(Executors.newSingleThreadScheduledExecutor()); + ReflectionTestUtils.setField(schedulerService, "scheduledExecutor", executor); + try { + SchedulerEvent schedulerEvent = new SchedulerEvent(); + schedulerEvent.setName("Firmware update"); + schedulerEvent.setType(UPDATE_FIRMWARE); + schedulerEvent.setEnabled(true); + ObjectNode schedule = JacksonUtil.newObjectNode(); + schedule.put("startTime", Long.MAX_VALUE); + schedule.put("timezone", "UTC"); + schedulerEvent.setSchedule(schedule); + schedulerEvent.setOriginatorId(otherTenantGroup.getId()); + ObjectNode configuration = JacksonUtil.newObjectNode(); + configuration.set("msgBody", JacksonUtil.valueToTree(firmware.getId())); + schedulerEvent.setConfiguration(configuration); + SchedulerEvent savedSchedulerEvent = doPost("/api/schedulerEvent", schedulerEvent, SchedulerEvent.class); + + Map eventsMetaData = (Map) ReflectionTestUtils.getField(schedulerService, "eventsMetaData"); + Awaitility.await().atMost(10, TimeUnit.SECONDS).until(() -> eventsMetaData.containsKey(savedSchedulerEvent.getId())); + ReflectionTestUtils.invokeMethod(schedulerService, "processEvent", tenantId, savedSchedulerEvent.getId()); + } finally { + ReflectionTestUtils.setField(schedulerService, "scheduledExecutor", originalExecutor); + executor.shutdownNow(); + } + assertThat(deviceGroupOtaPackageService.findDeviceGroupOtaPackageByGroupIdAndType(otherTenantGroup.getId(), FIRMWARE)).isNull(); + } + private SchedulerEvent createSchedulerEvent(EntityId originatorId, boolean enabled) { SchedulerEvent schedulerEvent = new SchedulerEvent(); schedulerEvent.setName("TestRpc"); diff --git a/common/dao-api/src/main/java/org/thingsboard/server/dao/group/EntityGroupService.java b/common/dao-api/src/main/java/org/thingsboard/server/dao/group/EntityGroupService.java index 177a94438a..5f2c6897d2 100644 --- a/common/dao-api/src/main/java/org/thingsboard/server/dao/group/EntityGroupService.java +++ b/common/dao-api/src/main/java/org/thingsboard/server/dao/group/EntityGroupService.java @@ -37,6 +37,10 @@ public interface EntityGroupService extends EntityDaoService { ListenableFuture findEntityGroupInfoByIdAsync(TenantId tenantId, EntityGroupId entityGroupId); + EntityGroupInfo findEntityGroupInfoByTenantIdAndId(TenantId tenantId, EntityGroupId entityGroupId); + + ListenableFuture findEntityGroupInfoByTenantIdAndIdAsync(TenantId tenantId, EntityGroupId entityGroupId); + EntityGroup saveEntityGroup(TenantId tenantId, EntityId parentEntityId, EntityGroup entityGroup); EntityGroup createEntityGroupAll(TenantId tenantId, EntityId parentEntityId, EntityType groupType); diff --git a/dao/src/main/java/org/thingsboard/server/dao/group/BaseEntityGroupService.java b/dao/src/main/java/org/thingsboard/server/dao/group/BaseEntityGroupService.java index 207470c488..80fc2d92c0 100644 --- a/dao/src/main/java/org/thingsboard/server/dao/group/BaseEntityGroupService.java +++ b/dao/src/main/java/org/thingsboard/server/dao/group/BaseEntityGroupService.java @@ -183,6 +183,20 @@ public class BaseEntityGroupService extends AbstractCachedEntityService INCORRECT_ENTITY_GROUP_ID + id); + return entityGroupInfoDao.findByTenantIdAndId(tenantId, entityGroupId.getId()); + } + + @Override + public ListenableFuture findEntityGroupInfoByTenantIdAndIdAsync(TenantId tenantId, EntityGroupId entityGroupId) { + log.trace("Executing findEntityGroupInfoByTenantIdAndIdAsync, tenantId [{}], entityGroupId [{}]", tenantId, entityGroupId); + validateId(entityGroupId, id -> INCORRECT_ENTITY_GROUP_ID + id); + return entityGroupInfoDao.findByTenantIdAndIdAsync(tenantId, entityGroupId.getId()); + } + @Override public EntityGroup saveEntityGroup(TenantId tenantId, EntityId parentEntityId, EntityGroup entityGroup) { log.trace("Executing saveEntityGroup [{}]", entityGroup); diff --git a/dao/src/main/java/org/thingsboard/server/dao/group/EntityGroupInfoDao.java b/dao/src/main/java/org/thingsboard/server/dao/group/EntityGroupInfoDao.java index 6cf69ec7f4..a57c4c987d 100644 --- a/dao/src/main/java/org/thingsboard/server/dao/group/EntityGroupInfoDao.java +++ b/dao/src/main/java/org/thingsboard/server/dao/group/EntityGroupInfoDao.java @@ -2,6 +2,7 @@ // SPDX-License-Identifier: BUSL-1.1 package org.thingsboard.server.dao.group; +import com.google.common.util.concurrent.ListenableFuture; import org.thingsboard.server.common.data.EntityInfo; import org.thingsboard.server.common.data.EntityType; import org.thingsboard.server.common.data.group.EntityGroupInfo; @@ -16,6 +17,10 @@ import java.util.UUID; public interface EntityGroupInfoDao extends Dao { + EntityGroupInfo findByTenantIdAndId(TenantId tenantId, UUID entityGroupId); + + ListenableFuture findByTenantIdAndIdAsync(TenantId tenantId, UUID entityGroupId); + EntityInfo findEntityGroupEntityInfoById(TenantId tenantId, UUID entityGroupId); PageData findEntityGroupsByType(UUID tenantId, UUID parentEntityId, EntityType parentEntityType, EntityType groupType, PageLink pageLink); diff --git a/dao/src/main/java/org/thingsboard/server/dao/grouppermission/GroupPermissionServiceImpl.java b/dao/src/main/java/org/thingsboard/server/dao/grouppermission/GroupPermissionServiceImpl.java index 7a62e5ae0b..4fa030ef64 100644 --- a/dao/src/main/java/org/thingsboard/server/dao/grouppermission/GroupPermissionServiceImpl.java +++ b/dao/src/main/java/org/thingsboard/server/dao/grouppermission/GroupPermissionServiceImpl.java @@ -15,6 +15,7 @@ import org.springframework.transaction.annotation.Transactional; import org.thingsboard.common.util.JacksonUtil; import org.thingsboard.server.common.data.EntityType; import org.thingsboard.server.common.data.group.EntityGroup; +import org.thingsboard.server.common.data.group.EntityGroupInfo; import org.thingsboard.server.common.data.id.EntityGroupId; import org.thingsboard.server.common.data.id.EntityId; import org.thingsboard.server.common.data.id.GroupPermissionId; @@ -303,13 +304,16 @@ public class GroupPermissionServiceImpl extends AbstractEntityService implements } private ListenableFuture fetchUserGroupPermissionInfoAsync(TenantId tenantId, GroupPermission groupPermission) { - ListenableFuture roleFuture = roleDao.findByIdAsync(tenantId, groupPermission.getRoleId().getId()); + ListenableFuture roleFuture = findRoleAsync(tenantId, groupPermission.getRoleId()); return Futures.transformAsync(roleFuture, role -> { GroupPermissionInfo groupPermissionInfo = new GroupPermissionInfo(groupPermission); groupPermissionInfo.setRole(role); if (groupPermission.getEntityGroupId() != null && !groupPermission.getEntityGroupId().isNullUid()) { - ListenableFuture entityGroup = entityGroupService.findEntityGroupByIdAsync(tenantId, groupPermission.getEntityGroupId()); + ListenableFuture entityGroup = entityGroupService.findEntityGroupInfoByTenantIdAndIdAsync(tenantId, groupPermission.getEntityGroupId()); return Futures.transform(entityGroup, entityGroup1 -> { + if (entityGroup1 == null) { + return null; + } groupPermissionInfo.setEntityGroupName(entityGroup1.getName()); groupPermissionInfo.setEntityGroupType(entityGroup1.getType()); EntityId ownerId = entityGroup1.getOwnerId(); @@ -324,12 +328,15 @@ public class GroupPermissionServiceImpl extends AbstractEntityService implements } private ListenableFuture fetchEntityGroupPermissionInfoAsync(TenantId tenantId, GroupPermission groupPermission) { - ListenableFuture roleFuture = roleDao.findByIdAsync(tenantId, groupPermission.getRoleId().getId()); + ListenableFuture roleFuture = findRoleAsync(tenantId, groupPermission.getRoleId()); return Futures.transformAsync(roleFuture, role -> { GroupPermissionInfo groupPermissionInfo = new GroupPermissionInfo(groupPermission); groupPermissionInfo.setRole(role); - ListenableFuture userGroup = entityGroupService.findEntityGroupByIdAsync(tenantId, groupPermission.getUserGroupId()); + ListenableFuture userGroup = entityGroupService.findEntityGroupInfoByTenantIdAndIdAsync(tenantId, groupPermission.getUserGroupId()); return Futures.transform(userGroup, userGroup1 -> { + if (userGroup1 == null) { + return null; + } groupPermissionInfo.setUserGroupName(userGroup1.getName()); EntityId ownerId = userGroup1.getOwnerId(); groupPermissionInfo.setUserGroupOwnerId(ownerId); @@ -339,6 +346,12 @@ public class GroupPermissionServiceImpl extends AbstractEntityService implements }, MoreExecutors.directExecutor()); } + private ListenableFuture findRoleAsync(TenantId tenantId, RoleId roleId) { + return Futures.transform(roleDao.findByIdAsync(tenantId, roleId.getId()), + role -> role != null && (tenantId.equals(role.getTenantId()) || role.getTenantId().isSysTenantId()) ? role : null, + MoreExecutors.directExecutor()); + } + private final PaginatedRemover tenantGroupPermissionRemover = new PaginatedRemover<>() { @Override diff --git a/dao/src/main/java/org/thingsboard/server/dao/menu/CustomMenuServiceImpl.java b/dao/src/main/java/org/thingsboard/server/dao/menu/CustomMenuServiceImpl.java index 0a652fa014..55c1c050e4 100644 --- a/dao/src/main/java/org/thingsboard/server/dao/menu/CustomMenuServiceImpl.java +++ b/dao/src/main/java/org/thingsboard/server/dao/menu/CustomMenuServiceImpl.java @@ -185,8 +185,10 @@ public class CustomMenuServiceImpl extends AbstractCachedEntityService Collections.emptyList(); case CUSTOMERS -> customerService.findCustomersByCustomMenuId(customMenuInfo.getId()).stream() + .filter(customer -> isAvailableToTenant(customMenuInfo, customer.getTenantId())) .map(customer -> new EntityInfo(customer.getId(), customer.getName())).toList(); case USERS -> userService.findUsersByCustomMenuId(customMenuInfo.getId()).stream() + .filter(user -> isAvailableToTenant(customMenuInfo, user.getTenantId())) .map(user -> new EntityInfo(user.getId(), user.getName())).toList(); default -> throw new RuntimeException("Invalid custom menu assignee type '" + customMenuInfo.getAssigneeType() + "' specified for custom menu!"); @@ -334,7 +336,7 @@ public class CustomMenuServiceImpl extends AbstractCachedEntityService { private final TenantService tenantService; - private final EntityGroupDao entityGroupDao; + private final EntityGroupInfoDao entityGroupInfoDao; private final RoleDao roleDao; private final GroupPermissionDao groupPermissionDao; @@ -52,7 +52,7 @@ public class GroupPermissionDataValidator extends DataValidator if (groupPermission.getUserGroupId() == null || groupPermission.getUserGroupId().isNullUid()) { throw new DataValidationException("Group Permission userGroupId should be specified!"); } else { - EntityGroup entityGroup = entityGroupDao.findById(tenantId, groupPermission.getUserGroupId().getId()); + EntityGroup entityGroup = entityGroupInfoDao.findByTenantIdAndId(groupPermission.getTenantId(), groupPermission.getUserGroupId().getId()); if (entityGroup == null) { throw new DataValidationException("Group Permission is referencing to non-existent user group!"); } else if (entityGroup.getType() != EntityType.USER) { @@ -63,7 +63,7 @@ public class GroupPermissionDataValidator extends DataValidator throw new DataValidationException("Group Permission roleId should be specified!"); } else { Role role = roleDao.findById(tenantId, groupPermission.getRoleId().getId()); - if (role == null) { + if (role == null || !(role.getTenantId().equals(groupPermission.getTenantId()) || role.getTenantId().isSysTenantId())) { throw new DataValidationException("Group Permission is referencing to non-existent role!"); } } @@ -72,7 +72,7 @@ public class GroupPermissionDataValidator extends DataValidator } if (!groupPermission.getEntityGroupId().isNullUid()) { - EntityGroup entityGroup = entityGroupDao.findById(tenantId, groupPermission.getEntityGroupId().getId()); + EntityGroup entityGroup = entityGroupInfoDao.findByTenantIdAndId(groupPermission.getTenantId(), groupPermission.getEntityGroupId().getId()); if (entityGroup == null) { throw new DataValidationException("Group Permission is referencing to non-existent entity group!"); } diff --git a/dao/src/main/java/org/thingsboard/server/dao/sql/group/EntityGroupInfoRepository.java b/dao/src/main/java/org/thingsboard/server/dao/sql/group/EntityGroupInfoRepository.java index eeffe3a19c..01290bc3aa 100644 --- a/dao/src/main/java/org/thingsboard/server/dao/sql/group/EntityGroupInfoRepository.java +++ b/dao/src/main/java/org/thingsboard/server/dao/sql/group/EntityGroupInfoRepository.java @@ -16,6 +16,12 @@ import java.util.UUID; public interface EntityGroupInfoRepository extends JpaRepository { + String OWNED_WITHIN_TENANT = "((e.ownerId = :tenantId AND e.ownerType = 'TENANT') OR " + + "(e.ownerType = 'CUSTOMER' AND EXISTS (SELECT 1 FROM CustomerEntity c WHERE c.id = e.ownerId AND c.tenantId = :tenantId)))"; + + @Query("SELECT e FROM EntityGroupInfoEntity e WHERE e.id = :entityGroupId AND " + OWNED_WITHIN_TENANT) + EntityGroupInfoEntity findByTenantIdAndId(@Param("tenantId") UUID tenantId, @Param("entityGroupId") UUID entityGroupId); + @Query("SELECT new org.thingsboard.server.common.data.EntityInfo(e.id, 'ENTITY_GROUP', e.name) " + "FROM EntityGroupEntity e " + "WHERE e.id = :entityGroupId") @@ -65,16 +71,20 @@ public interface EntityGroupInfoRepository extends JpaRepository findEntityGroupsByIds(@Param("entityGroupIds") List entityGroupIds, + Page findEntityGroupsByIds(@Param("tenantId") UUID tenantId, + @Param("entityGroupIds") List entityGroupIds, @Param("textSearch") String textSearch, Pageable pageable); @Query("SELECT new org.thingsboard.server.common.data.EntityInfo(e.id, 'ENTITY_GROUP', e.name) " + "FROM EntityGroupEntity e " + "WHERE e.id IN :entityGroupIds " + + "AND " + OWNED_WITHIN_TENANT + " " + "AND (:textSearch IS NULL OR ilike(e.name, CONCAT('%', :textSearch, '%')) = true)") - Page findEntityGroupEntityInfosByIds(@Param("entityGroupIds") List entityGroupIds, + Page findEntityGroupEntityInfosByIds(@Param("tenantId") UUID tenantId, + @Param("entityGroupIds") List entityGroupIds, @Param("textSearch") String textSearch, Pageable pageable); diff --git a/dao/src/main/java/org/thingsboard/server/dao/sql/group/JpaEntityGroupInfoDao.java b/dao/src/main/java/org/thingsboard/server/dao/sql/group/JpaEntityGroupInfoDao.java index b0d7c837c8..bc4e675502 100644 --- a/dao/src/main/java/org/thingsboard/server/dao/sql/group/JpaEntityGroupInfoDao.java +++ b/dao/src/main/java/org/thingsboard/server/dao/sql/group/JpaEntityGroupInfoDao.java @@ -2,6 +2,7 @@ // SPDX-License-Identifier: BUSL-1.1 package org.thingsboard.server.dao.sql.group; +import com.google.common.util.concurrent.ListenableFuture; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Component; @@ -38,6 +39,16 @@ public class JpaEntityGroupInfoDao extends JpaAbstractDao findByTenantIdAndIdAsync(TenantId tenantId, UUID entityGroupId) { + return service.submit(() -> findByTenantIdAndId(tenantId, entityGroupId)); + } + @Override public EntityInfo findEntityGroupEntityInfoById(TenantId tenantId, UUID entityGroupId) { return entityGroupInfoRepository.findEntityGroupEntityInfoById(entityGroupId); @@ -90,6 +101,7 @@ public class JpaEntityGroupInfoDao extends JpaAbstractDao findEntityGroupsByIds(UUID tenantId, List entityGroupIds, PageLink pageLink) { return DaoUtil.toPageData(entityGroupInfoRepository .findEntityGroupsByIds( + tenantId, entityGroupIds, pageLink.getTextSearch(), DaoUtil.toPageable(pageLink))); @@ -99,6 +111,7 @@ public class JpaEntityGroupInfoDao extends JpaAbstractDao findEntityGroupEntityInfosByIds(UUID tenantId, List entityGroupIds, PageLink pageLink) { return DaoUtil.pageToPageData(entityGroupInfoRepository .findEntityGroupEntityInfosByIds( + tenantId, entityGroupIds, pageLink.getTextSearch(), DaoUtil.toPageable(pageLink))); diff --git a/dao/src/test/java/org/thingsboard/server/dao/service/EntityGroupServiceTest.java b/dao/src/test/java/org/thingsboard/server/dao/service/EntityGroupServiceTest.java index edea605cf3..a9564579d4 100644 --- a/dao/src/test/java/org/thingsboard/server/dao/service/EntityGroupServiceTest.java +++ b/dao/src/test/java/org/thingsboard/server/dao/service/EntityGroupServiceTest.java @@ -15,6 +15,7 @@ import org.springframework.beans.factory.annotation.Autowired; import org.thingsboard.common.util.JacksonUtil; import org.thingsboard.common.util.ThingsBoardExecutors; import org.thingsboard.server.common.data.AttributeScope; +import org.thingsboard.server.common.data.Customer; import org.thingsboard.server.common.data.Device; import org.thingsboard.server.common.data.EntityType; import org.thingsboard.server.common.data.ShortEntityView; @@ -31,6 +32,7 @@ import org.thingsboard.server.common.data.id.CustomerId; import org.thingsboard.server.common.data.id.EntityGroupId; import org.thingsboard.server.common.data.id.EntityId; import org.thingsboard.server.common.data.id.IdBased; +import org.thingsboard.server.common.data.id.TenantId; import org.thingsboard.server.common.data.kv.AttributeKvEntry; import org.thingsboard.server.common.data.kv.AttributesSaveResult; import org.thingsboard.server.common.data.kv.BaseAttributeKvEntry; @@ -45,6 +47,7 @@ import org.thingsboard.server.common.data.permission.Operation; import org.thingsboard.server.common.data.permission.Resource; import org.thingsboard.server.dao.asset.AssetService; import org.thingsboard.server.dao.attributes.AttributesService; +import org.thingsboard.server.dao.customer.CustomerService; import org.thingsboard.server.dao.device.DeviceService; import org.thingsboard.server.dao.edge.EdgeService; import org.thingsboard.server.dao.group.EntityGroupService; @@ -81,6 +84,8 @@ public class EntityGroupServiceTest extends AbstractServiceTest { EntityGroupService entityGroupService; @Autowired EdgeService edgeService; + @Autowired + CustomerService customerService; private MergedUserPermissions mergedUserPermissions; @@ -100,6 +105,34 @@ public class EntityGroupServiceTest extends AbstractServiceTest { executor.shutdownNow(); } + @Test + public void testFindEntityGroupInfoByTenantIdAndId() { + EntityGroup tenantGroup = new EntityGroup(); + tenantGroup.setName("Tenant Device Group"); + tenantGroup.setType(EntityType.DEVICE); + tenantGroup = entityGroupService.saveEntityGroup(tenantId, tenantId, tenantGroup); + + Customer customer = new Customer(); + customer.setTenantId(tenantId); + customer.setTitle("Group Owner Customer"); + customer = customerService.saveCustomer(customer); + EntityGroup customerGroup = new EntityGroup(); + customerGroup.setName("Customer Device Group"); + customerGroup.setType(EntityType.DEVICE); + customerGroup = entityGroupService.saveEntityGroup(tenantId, customer.getId(), customerGroup); + + TenantId otherTenantId = createTenant().getId(); + EntityGroup otherTenantGroup = new EntityGroup(); + otherTenantGroup.setName("Other Tenant Device Group"); + otherTenantGroup.setType(EntityType.DEVICE); + otherTenantGroup = entityGroupService.saveEntityGroup(otherTenantId, otherTenantId, otherTenantGroup); + + assertThat(entityGroupService.findEntityGroupInfoByTenantIdAndId(tenantId, tenantGroup.getId()).getId()).isEqualTo(tenantGroup.getId()); + assertThat(entityGroupService.findEntityGroupInfoByTenantIdAndId(tenantId, customerGroup.getId()).getId()).isEqualTo(customerGroup.getId()); + assertThat(entityGroupService.findEntityGroupInfoByTenantIdAndId(tenantId, otherTenantGroup.getId())).isNull(); + assertThat(entityGroupService.findEntityGroupInfoByTenantIdAndId(otherTenantId, otherTenantGroup.getId()).getId()).isEqualTo(otherTenantGroup.getId()); + } + @Test public void testFindGroupEntityIds() throws ExecutionException, InterruptedException, TimeoutException { List> futures = new ArrayList<>(97);