From 10be49e416969af95af575c44cef63b621d8ecef Mon Sep 17 00:00:00 2001 From: Viacheslav Klimov Date: Thu, 12 Nov 2026 02:34:01 +0200 Subject: [PATCH 01/11] Add tenant-scoped entity group info lookups (cherry picked from commit 32e5572136f778ae3c41213b10e245776ee348d6) --- .../server/dao/group/EntityGroupService.java | 4 +++ .../dao/group/BaseEntityGroupService.java | 14 ++++++++ .../server/dao/group/EntityGroupInfoDao.java | 5 +++ .../sql/group/EntityGroupInfoRepository.java | 13 ++++++-- .../dao/sql/group/JpaEntityGroupInfoDao.java | 13 ++++++++ .../dao/service/EntityGroupServiceTest.java | 33 +++++++++++++++++++ 6 files changed, 80 insertions(+), 2 deletions(-) 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/sql/group/EntityGroupInfoRepository.java b/dao/src/main/java/org/thingsboard/server/dao/sql/group/EntityGroupInfoRepository.java index eeffe3a19c..079ec133cb 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 @@ -14,8 +14,13 @@ import org.thingsboard.server.dao.model.sql.EntityGroupInfoEntity; import java.util.List; import java.util.UUID; +import static org.thingsboard.server.dao.sql.group.EntityGroupRepository.TENANT_ID_FILTER; + public interface EntityGroupInfoRepository extends JpaRepository { + @Query("SELECT e FROM EntityGroupInfoEntity e WHERE e.id = :entityGroupId AND " + TENANT_ID_FILTER) + 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 +70,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 " + TENANT_ID_FILTER + " " + "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); From 6f8c48f1b9859ba9d3a1c1933632f40e8d3c3bc6 Mon Sep 17 00:00:00 2001 From: Viacheslav Klimov Date: Thu, 12 Nov 2026 02:34:01 +0200 Subject: [PATCH 02/11] Resolve group permission roles and groups within the tenant (cherry picked from commit d2196f11ec27253944534761a4f560a1153fe207) --- .../controller/GroupPermissionController.java | 17 +++- .../server/controller/SignUpController.java | 2 +- .../GroupPermissionControllerTest.java | 98 +++++++++++++++++++ .../controller/SignUpControllerSqlTest.java | 39 +++++++- .../GroupPermissionServiceImpl.java | 21 +++- .../GroupPermissionDataValidator.java | 10 +- 6 files changed, 175 insertions(+), 12 deletions(-) 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 9d26820989..156ec85e5a 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; @@ -218,7 +219,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); } @@ -255,6 +257,19 @@ public class GroupPermissionController extends BaseController { return groupPermissions; } + 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 7f06d2b8bb..d4dc93781d 100644 --- a/application/src/main/java/org/thingsboard/server/controller/SignUpController.java +++ b/application/src/main/java/org/thingsboard/server/controller/SignUpController.java @@ -616,7 +616,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/test/java/org/thingsboard/server/controller/GroupPermissionControllerTest.java b/application/src/test/java/org/thingsboard/server/controller/GroupPermissionControllerTest.java index 342151bee4..84ccf2dd73 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().isBadRequest()); + + 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; + } + private void checkPermissionOwners(List groupPermissionsInfos, List ownerIds) { for (GroupPermissionInfo groupPermissionInfo : groupPermissionsInfos) { assertTrue(ownerIds.contains(groupPermissionInfo.getUserGroupOwnerId())); 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 398b5193b4..d0634a1410 100644 --- a/application/src/test/java/org/thingsboard/server/controller/SignUpControllerSqlTest.java +++ b/application/src/test/java/org/thingsboard/server/controller/SignUpControllerSqlTest.java @@ -12,6 +12,7 @@ import org.mockito.Mockito; import org.springframework.beans.factory.annotation.Autowired; 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.Customer; import org.thingsboard.server.common.data.CustomerInfo; import org.thingsboard.server.common.data.Dashboard; @@ -34,6 +35,9 @@ import org.thingsboard.server.common.data.notification.NotificationDeliveryMetho import org.thingsboard.server.common.data.notification.NotificationType; import org.thingsboard.server.common.data.oauth2.PlatformType; import org.thingsboard.server.common.data.page.PageLink; +import org.thingsboard.server.common.data.permission.GroupPermission; +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.common.data.security.UserCredentials; import org.thingsboard.server.common.data.selfregistration.DefaultDashboardParams; @@ -48,6 +52,7 @@ import org.thingsboard.server.common.data.signup.SignUpRequest; import org.thingsboard.server.common.data.signup.SignUpResult; 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; @@ -117,6 +122,9 @@ public class SignUpControllerSqlTest extends AbstractControllerTest { @Autowired protected WhiteLabelingService whiteLabelingService; + @Autowired + private GroupPermissionService groupPermissionService; + @Before public void beforeTest() throws Exception { loginTenantAdmin(); @@ -261,6 +269,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(); @@ -372,6 +405,10 @@ public class SignUpControllerSqlTest extends AbstractControllerTest { } private void createWebSelfRegistrationSettings() { + createWebSelfRegistrationSettings(Collections.emptyList()); + } + + private void createWebSelfRegistrationSettings(List permissions) { Domain domain = constructDomain("localhost"); Domain savedDomain = doPost("/api/domain", domain, Domain.class); @@ -385,7 +422,7 @@ public class SignUpControllerSqlTest extends AbstractControllerTest { selfRegistrationParams.setShowPrivacyPolicy(true); selfRegistrationParams.setDomainId(savedDomain.getId()); selfRegistrationParams.setNotificationRecipient(createNotificationTarget(currentUserId).getId()); - selfRegistrationParams.setPermissions(Collections.emptyList()); + selfRegistrationParams.setPermissions(permissions); doPost("/api/selfRegistration/selfRegistrationParams", selfRegistrationParams, JsonNode.class); 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/service/validator/GroupPermissionDataValidator.java b/dao/src/main/java/org/thingsboard/server/dao/service/validator/GroupPermissionDataValidator.java index 4e5116a491..93f0a6eddd 100644 --- a/dao/src/main/java/org/thingsboard/server/dao/service/validator/GroupPermissionDataValidator.java +++ b/dao/src/main/java/org/thingsboard/server/dao/service/validator/GroupPermissionDataValidator.java @@ -12,7 +12,7 @@ import org.thingsboard.server.common.data.id.EntityId; import org.thingsboard.server.common.data.id.TenantId; import org.thingsboard.server.common.data.permission.GroupPermission; import org.thingsboard.server.common.data.role.Role; -import org.thingsboard.server.dao.group.EntityGroupDao; +import org.thingsboard.server.dao.group.EntityGroupInfoDao; import org.thingsboard.server.dao.grouppermission.GroupPermissionDao; import org.thingsboard.server.dao.role.RoleDao; import org.thingsboard.server.dao.service.DataValidator; @@ -24,7 +24,7 @@ import org.thingsboard.server.exception.DataValidationException; public class GroupPermissionDataValidator extends DataValidator { 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!"); } From a7ac43daeb6bbd3e8a3d12392829629bd30b5bb7 Mon Sep 17 00:00:00 2001 From: Viacheslav Klimov Date: Thu, 12 Nov 2026 02:34:01 +0200 Subject: [PATCH 03/11] Answer entity group requests of other tenants as not found (cherry picked from commit 7ccb975993bcc1e126d282df0152534f775f55c5) --- .../server/controller/BaseController.java | 2 +- .../controller/EntityGroupController.java | 15 ++- .../service/security/AccessValidator.java | 2 +- .../controller/EntityGroupControllerTest.java | 125 +++++++++++++++++- 4 files changed, 136 insertions(+), 8 deletions(-) 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 13a122ed38..ab1ffaafe9 100644 --- a/application/src/main/java/org/thingsboard/server/controller/BaseController.java +++ b/application/src/main/java/org/thingsboard/server/controller/BaseController.java @@ -1244,7 +1244,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 2146550658..179365bb6b 100644 --- a/application/src/main/java/org/thingsboard/server/controller/EntityGroupController.java +++ b/application/src/main/java/org/thingsboard/server/controller/EntityGroupController.java @@ -964,7 +964,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)", @@ -1170,7 +1174,8 @@ public class EntityGroupController extends AutoCommitController { 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()); + checkNotNull(userGroup, "Entity group with id [" + shareGroupRequest.getUserGroupId() + "] is not found"); } accessControlService.checkEntityGroupInfoPermission(getCurrentUser(), Operation.WRITE, userGroup); @@ -1243,7 +1248,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); } @@ -1296,7 +1301,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); } @@ -1314,7 +1319,7 @@ public class EntityGroupController extends AutoCommitController { 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); diff --git a/application/src/main/java/org/thingsboard/server/service/security/AccessValidator.java b/application/src/main/java/org/thingsboard/server/service/security/AccessValidator.java index 8a7129668a..f8652a1a53 100644 --- a/application/src/main/java/org/thingsboard/server/service/security/AccessValidator.java +++ b/application/src/main/java/org/thingsboard/server/service/security/AccessValidator.java @@ -642,7 +642,7 @@ public class AccessValidator { if (currentUser.isSystemAdmin()) { callback.onSuccess(ValidationResult.accessDenied(SYSTEM_ADMINISTRATOR_IS_NOT_ALLOWED_TO_PERFORM_THIS_OPERATION)); } else { - ListenableFuture 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/EntityGroupControllerTest.java b/application/src/test/java/org/thingsboard/server/controller/EntityGroupControllerTest.java index 53eeedd183..71914b0442 100644 --- a/application/src/test/java/org/thingsboard/server/controller/EntityGroupControllerTest.java +++ b/application/src/test/java/org/thingsboard/server/controller/EntityGroupControllerTest.java @@ -12,6 +12,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; @@ -23,6 +24,7 @@ import org.thingsboard.server.common.data.id.IdBased; import org.thingsboard.server.common.data.page.PageData; import org.thingsboard.server.common.data.page.PageLink; 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; @@ -38,6 +40,7 @@ import java.util.stream.Collectors; import static org.assertj.core.api.Assertions.assertThat; import static org.hamcrest.Matchers.containsString; +import static org.hamcrest.Matchers.not; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; @DaoSqlTest @@ -167,11 +170,131 @@ 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 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(); From 0f5c471a4826a61d7f58a35e93852b31b3635e31 Mon Sep 17 00:00:00 2001 From: Viacheslav Klimov Date: Thu, 12 Nov 2026 02:34:01 +0200 Subject: [PATCH 04/11] Resolve custom menus and their assignees within the menu tenant (cherry picked from commit 55e7f60fb72b485b8c2471c14567a8f73f8e610d) --- .../controller/CustomMenuControllerTest.java | 64 +++++++++++++++++++ .../dao/menu/CustomMenuServiceImpl.java | 15 ++++- 2 files changed, 77 insertions(+), 2 deletions(-) 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..4c4e609d3f 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,70 @@ 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 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 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/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 Date: Thu, 12 Nov 2026 02:34:01 +0200 Subject: [PATCH 05/11] Resolve edge and scheduler event group ids within the tenant (cherry picked from commit 265a40873e64acc9eb2a5747e2c1825b70e12c34) --- .../edge/rpc/processor/BaseEdgeProcessor.java | 9 ++- .../processor/asset/AssetEdgeProcessor.java | 2 +- .../dashboard/DashboardEdgeProcessor.java | 2 +- .../processor/device/DeviceEdgeProcessor.java | 2 +- .../entityview/EntityViewEdgeProcessor.java | 2 +- .../telemetry/BaseTelemetryProcessor.java | 2 +- .../scheduler/DefaultSchedulerService.java | 2 +- .../server/edge/DeviceEdgeTest.java | 55 +++++++++++++++++++ 8 files changed, 69 insertions(+), 7 deletions(-) diff --git a/application/src/main/java/org/thingsboard/server/service/edge/rpc/processor/BaseEdgeProcessor.java b/application/src/main/java/org/thingsboard/server/service/edge/rpc/processor/BaseEdgeProcessor.java index 71d16a966e..e8a761cf55 100644 --- a/application/src/main/java/org/thingsboard/server/service/edge/rpc/processor/BaseEdgeProcessor.java +++ b/application/src/main/java/org/thingsboard/server/service/edge/rpc/processor/BaseEdgeProcessor.java @@ -527,7 +527,7 @@ public abstract class BaseEdgeProcessor implements EdgeProcessor { protected void safeAddEntityToGroup(TenantId tenantId, EntityGroupId entityGroupId, EntityId entityId) { if (entityGroupId != null && !ModelConstants.NULL_UUID.equals(entityGroupId.getId())) { - EntityGroup entityGroup = edgeCtx.getEntityGroupService().findEntityGroupById(tenantId, entityGroupId); + EntityGroup entityGroup = edgeCtx.getEntityGroupService().findEntityGroupInfoByTenantIdAndId(tenantId, entityGroupId); if (entityGroup != null) { edgeCtx.getEntityGroupService().addEntityToEntityGroup(tenantId, entityGroupId, entityId); } @@ -595,4 +595,11 @@ public abstract class BaseEdgeProcessor implements EdgeProcessor { } } + protected void safeRemoveEntityFromGroup(TenantId tenantId, EntityGroupId entityGroupId, EntityId entityId) { + EntityGroup entityGroup = edgeCtx.getEntityGroupService().findEntityGroupInfoByTenantIdAndId(tenantId, entityGroupId); + if (entityGroup != null) { + edgeCtx.getEntityGroupService().removeEntityFromEntityGroup(tenantId, entityGroupId, entityId); + } + } + } diff --git a/application/src/main/java/org/thingsboard/server/service/edge/rpc/processor/asset/AssetEdgeProcessor.java b/application/src/main/java/org/thingsboard/server/service/edge/rpc/processor/asset/AssetEdgeProcessor.java index c39a57e635..c72acdec48 100644 --- a/application/src/main/java/org/thingsboard/server/service/edge/rpc/processor/asset/AssetEdgeProcessor.java +++ b/application/src/main/java/org/thingsboard/server/service/edge/rpc/processor/asset/AssetEdgeProcessor.java @@ -55,7 +55,7 @@ public class AssetEdgeProcessor extends BaseAssetProcessor implements AssetProce if (assetUpdateMsg.hasEntityGroupIdMSB() && assetUpdateMsg.hasEntityGroupIdLSB()) { EntityGroupId entityGroupId = new EntityGroupId( new UUID(assetUpdateMsg.getEntityGroupIdMSB(), assetUpdateMsg.getEntityGroupIdLSB())); - edgeCtx.getEntityGroupService().removeEntityFromEntityGroup(tenantId, entityGroupId, assetId); + safeRemoveEntityFromGroup(tenantId, entityGroupId, assetId); } else if (EdgeVersionComparator.INSTANCE.compare(edgeVersion, EdgeVersion.V_4_3_0) >= 0) { deleteAsset(tenantId, edge, assetId); } else { diff --git a/application/src/main/java/org/thingsboard/server/service/edge/rpc/processor/dashboard/DashboardEdgeProcessor.java b/application/src/main/java/org/thingsboard/server/service/edge/rpc/processor/dashboard/DashboardEdgeProcessor.java index 64960cde69..a8b66aebab 100644 --- a/application/src/main/java/org/thingsboard/server/service/edge/rpc/processor/dashboard/DashboardEdgeProcessor.java +++ b/application/src/main/java/org/thingsboard/server/service/edge/rpc/processor/dashboard/DashboardEdgeProcessor.java @@ -51,7 +51,7 @@ public class DashboardEdgeProcessor extends BaseDashboardProcessor implements Da if (dashboardUpdateMsg.hasEntityGroupIdMSB() && dashboardUpdateMsg.hasEntityGroupIdLSB()) { EntityGroupId entityGroupId = new EntityGroupId( new UUID(dashboardUpdateMsg.getEntityGroupIdMSB(), dashboardUpdateMsg.getEntityGroupIdLSB())); - edgeCtx.getEntityGroupService().removeEntityFromEntityGroup(tenantId, entityGroupId, dashboardId); + safeRemoveEntityFromGroup(tenantId, entityGroupId, dashboardId); } else if (EdgeVersionComparator.INSTANCE.compare(edgeVersion, EdgeVersion.V_4_3_0) >= 0) { deleteDashboard(tenantId, edge, dashboardId); } else { diff --git a/application/src/main/java/org/thingsboard/server/service/edge/rpc/processor/device/DeviceEdgeProcessor.java b/application/src/main/java/org/thingsboard/server/service/edge/rpc/processor/device/DeviceEdgeProcessor.java index 2e50c72ebb..4b161747ba 100644 --- a/application/src/main/java/org/thingsboard/server/service/edge/rpc/processor/device/DeviceEdgeProcessor.java +++ b/application/src/main/java/org/thingsboard/server/service/edge/rpc/processor/device/DeviceEdgeProcessor.java @@ -72,7 +72,7 @@ public class DeviceEdgeProcessor extends BaseDeviceProcessor implements DevicePr if (deviceUpdateMsg.hasEntityGroupIdMSB() && deviceUpdateMsg.hasEntityGroupIdLSB()) { EntityGroupId entityGroupId = new EntityGroupId( new UUID(deviceUpdateMsg.getEntityGroupIdMSB(), deviceUpdateMsg.getEntityGroupIdLSB())); - edgeCtx.getEntityGroupService().removeEntityFromEntityGroup(tenantId, entityGroupId, deviceId); + safeRemoveEntityFromGroup(tenantId, entityGroupId, deviceId); } else if (EdgeVersionComparator.INSTANCE.compare(edgeVersion, EdgeVersion.V_4_3_0) >= 0) { deleteDevice(tenantId, edge, deviceId); } else { diff --git a/application/src/main/java/org/thingsboard/server/service/edge/rpc/processor/entityview/EntityViewEdgeProcessor.java b/application/src/main/java/org/thingsboard/server/service/edge/rpc/processor/entityview/EntityViewEdgeProcessor.java index ee3aafb725..a40416ad9b 100644 --- a/application/src/main/java/org/thingsboard/server/service/edge/rpc/processor/entityview/EntityViewEdgeProcessor.java +++ b/application/src/main/java/org/thingsboard/server/service/edge/rpc/processor/entityview/EntityViewEdgeProcessor.java @@ -54,7 +54,7 @@ public class EntityViewEdgeProcessor extends BaseEntityViewProcessor implements if (entityViewUpdateMsg.hasEntityGroupIdMSB() && entityViewUpdateMsg.hasEntityGroupIdLSB()) { EntityGroupId entityGroupId = new EntityGroupId( new UUID(entityViewUpdateMsg.getEntityGroupIdMSB(), entityViewUpdateMsg.getEntityGroupIdLSB())); - edgeCtx.getEntityGroupService().removeEntityFromEntityGroup(tenantId, entityGroupId, entityViewId); + safeRemoveEntityFromGroup(tenantId, entityGroupId, entityViewId); } else if (EdgeVersionComparator.INSTANCE.compare(edgeVersion, EdgeVersion.V_4_3_0) >= 0) { deleteEntityView(tenantId, edge, entityViewId); } else { 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 3332de3aad..8ea5dbe106 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/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 Date: Thu, 12 Nov 2026 05:23:24 +0200 Subject: [PATCH 06/11] Resolve edge user group removals within the tenant --- .../service/edge/rpc/processor/user/UserEdgeProcessor.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/application/src/main/java/org/thingsboard/server/service/edge/rpc/processor/user/UserEdgeProcessor.java b/application/src/main/java/org/thingsboard/server/service/edge/rpc/processor/user/UserEdgeProcessor.java index 3d4e6805da..2c7a2e98b5 100644 --- a/application/src/main/java/org/thingsboard/server/service/edge/rpc/processor/user/UserEdgeProcessor.java +++ b/application/src/main/java/org/thingsboard/server/service/edge/rpc/processor/user/UserEdgeProcessor.java @@ -63,7 +63,7 @@ public class UserEdgeProcessor extends BaseUserProcessor implements UserProcesso if (userUpdateMsg.hasEntityGroupIdMSB() && userUpdateMsg.hasEntityGroupIdLSB()) { EntityGroupId entityGroupId = new EntityGroupId( new UUID(userUpdateMsg.getEntityGroupIdMSB(), userUpdateMsg.getEntityGroupIdLSB())); - edgeCtx.getEntityGroupService().removeEntityFromEntityGroup(tenantId, entityGroupId, userId); + safeRemoveEntityFromGroup(tenantId, entityGroupId, userId); yield Futures.immediateFuture(null); } else if (EdgeVersionComparator.INSTANCE.compare(edgeVersion, EdgeVersion.V_4_3_0) >= 0) { deleteUserAndPushEntityDeletedEventToRuleEngine(tenantId, userId, edge); From bd199e6c84866086e0349a78ac3136dd82bd6ba3 Mon Sep 17 00:00:00 2001 From: Viacheslav Klimov Date: Thu, 12 Nov 2026 05:23:24 +0200 Subject: [PATCH 07/11] Resolve the IoT Hub dashboard group within the tenant --- .../service/iot_hub/DefaultIotHubService.java | 2 +- .../iot_hub/DefaultIotHubServiceTest.java | 39 ++++++++++++++++++- 2 files changed, 39 insertions(+), 2 deletions(-) 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 c74c8be477..b7c1a4b44d 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 @@ -297,7 +297,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/test/java/org/thingsboard/server/service/iot_hub/DefaultIotHubServiceTest.java b/application/src/test/java/org/thingsboard/server/service/iot_hub/DefaultIotHubServiceTest.java index cb9221db18..687b0ad91d 100644 --- a/application/src/test/java/org/thingsboard/server/service/iot_hub/DefaultIotHubServiceTest.java +++ b/application/src/test/java/org/thingsboard/server/service/iot_hub/DefaultIotHubServiceTest.java @@ -1,5 +1,6 @@ // SPDX-FileCopyrightText: Copyright The ThingsBoard Authors -// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Modifications Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: Apache-2.0 AND BUSL-1.1 package org.thingsboard.server.service.iot_hub; import com.fasterxml.jackson.databind.JsonNode; @@ -13,13 +14,19 @@ import org.mockito.Mock; import org.mockito.Spy; import org.mockito.junit.jupiter.MockitoExtension; import org.thingsboard.common.util.JacksonUtil; +import org.thingsboard.server.common.data.EntityType; +import org.thingsboard.server.common.data.group.EntityGroupInfo; +import org.thingsboard.server.common.data.id.EntityGroupId; import org.thingsboard.server.common.data.id.IotHubInstalledItemId; import org.thingsboard.server.common.data.id.TenantId; import org.thingsboard.server.common.data.iot_hub.DashboardInstalledItemDescriptor; import org.thingsboard.server.common.data.iot_hub.IotHubInstalledItem; +import org.thingsboard.server.dao.group.EntityGroupService; import org.thingsboard.server.dao.iot_hub.IotHubInstalledItemService; import org.thingsboard.server.service.security.model.SecurityUser; +import org.thingsboard.server.service.security.permission.AccessControlService; +import java.nio.charset.StandardCharsets; import java.util.List; import java.util.UUID; @@ -33,6 +40,7 @@ import static org.mockito.Mockito.doNothing; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.inOrder; +import static org.mockito.Mockito.lenient; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; @@ -48,6 +56,10 @@ class DefaultIotHubServiceTest { private IotHubRestClient iotHubRestClient; @Mock private IotHubInstalledItemService iotHubInstalledItemService; + @Mock + private EntityGroupService entityGroupService; + @Mock + private AccessControlService accessControlService; @Spy @InjectMocks @@ -411,4 +423,29 @@ class DefaultIotHubServiceTest { assertThat(result.isRolledBack()).isFalse(); assertThat(result.getErrorMessage()).contains("install failed"); } + + @Test + void installItemVersion_dashboardWithGroupOfAnotherTenant_reportsGroupNotFound() throws Exception { + mockTenant(); + String versionId = UUID.randomUUID().toString(); + when(iotHubRestClient.getVersionInfo(versionId)) + .thenReturn(version(versionId, UUID.randomUUID().toString(), "DASHBOARD", "Dashboard", "1.0")); + when(iotHubRestClient.getVersionFileData(versionId)).thenReturn("{\"title\":\"Dashboard\"}".getBytes(StandardCharsets.UTF_8)); + + TenantId otherTenantId = TenantId.fromUUID(UUID.randomUUID()); + EntityGroupInfo otherTenantGroup = new EntityGroupInfo(); + otherTenantGroup.setId(new EntityGroupId(UUID.randomUUID())); + otherTenantGroup.setTenantId(otherTenantId); + otherTenantGroup.setOwnerId(otherTenantId); + otherTenantGroup.setType(EntityType.DASHBOARD); + otherTenantGroup.setName("Dashboards"); + lenient().when(entityGroupService.findEntityGroupInfoById(tenantId, otherTenantGroup.getId())).thenReturn(otherTenantGroup); + JsonNode data = JacksonUtil.newObjectNode().put("entityGroupId", otherTenantGroup.getId().getId().toString()); + + InstallItemVersionResult result = service.installItemVersion(user, versionId, data, null); + + assertThat(result.isSuccess()).isFalse(); + assertThat(result.getErrorMessage()).isEqualTo("Entity group with id [" + otherTenantGroup.getId() + "] is not found"); + verify(accessControlService, never()).checkEntityGroupInfoPermission(any(), any(), any()); + } } From 71cfc0d500942b4ce32e0becedf0e8850990c3b2 Mon Sep 17 00:00:00 2001 From: Viacheslav Klimov Date: Thu, 12 Nov 2026 05:23:24 +0200 Subject: [PATCH 08/11] Cover the v2 group share and the user's own custom menu with ids of another tenant --- .../controller/CustomMenuControllerTest.java | 22 +++++++++++++++++++ .../controller/EntityGroupControllerTest.java | 20 +++++++++++++++++ 2 files changed, 42 insertions(+) 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 4c4e609d3f..cbf8ca2276 100644 --- a/application/src/test/java/org/thingsboard/server/controller/CustomMenuControllerTest.java +++ b/application/src/test/java/org/thingsboard/server/controller/CustomMenuControllerTest.java @@ -679,6 +679,28 @@ public class CustomMenuControllerTest extends AbstractControllerTest { 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(); 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 71914b0442..fd18e8c67d 100644 --- a/application/src/test/java/org/thingsboard/server/controller/EntityGroupControllerTest.java +++ b/application/src/test/java/org/thingsboard/server/controller/EntityGroupControllerTest.java @@ -235,6 +235,26 @@ public class EntityGroupControllerTest extends AbstractControllerTest { .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 testShareGroupToChildOwnerUserGroupWithGroupsOfOtherTenantReturnsNotFound() throws Exception { loginDifferentTenant(); From 653b2a76db7388dc449ccffe31e3863099cbd843 Mon Sep 17 00:00:00 2001 From: Viacheslav Klimov Date: Fri, 13 Nov 2026 11:57:52 +0200 Subject: [PATCH 09/11] Treat the All users group of another tenant as not found when sharing a group --- .../controller/EntityGroupController.java | 12 ++-- .../controller/EntityGroupControllerTest.java | 66 +++++++++++++++++++ 2 files changed, 74 insertions(+), 4 deletions(-) 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 9e0f5c582a..40499b2d2f 100644 --- a/application/src/main/java/org/thingsboard/server/controller/EntityGroupController.java +++ b/application/src/main/java/org/thingsboard/server/controller/EntityGroupController.java @@ -1168,8 +1168,7 @@ 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 { @@ -1317,8 +1316,7 @@ 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 { @@ -1333,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/test/java/org/thingsboard/server/controller/EntityGroupControllerTest.java b/application/src/test/java/org/thingsboard/server/controller/EntityGroupControllerTest.java index c14f97b2f8..23be30acc4 100644 --- a/application/src/test/java/org/thingsboard/server/controller/EntityGroupControllerTest.java +++ b/application/src/test/java/org/thingsboard/server/controller/EntityGroupControllerTest.java @@ -47,6 +47,7 @@ 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; @@ -268,6 +269,66 @@ public class EntityGroupControllerTest extends AbstractControllerTest { .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(); @@ -720,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()); + } + } From 387ac28dd720f8f058301fccbced40f040c17005 Mon Sep 17 00:00:00 2001 From: Viacheslav Klimov Date: Fri, 13 Nov 2026 13:33:16 +0200 Subject: [PATCH 10/11] Cover custom menu users, scheduler group originators and edge group telemetry of another tenant in tests --- .../controller/CustomMenuControllerTest.java | 28 +++++++++ .../server/edge/TelemetryEdgeTest.java | 45 ++++++++++++++ .../scheduler/sql/SchedulerEventTest.java | 62 +++++++++++++++++++ 3 files changed, 135 insertions(+) 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 cbf8ca2276..e6bebce6d1 100644 --- a/application/src/test/java/org/thingsboard/server/controller/CustomMenuControllerTest.java +++ b/application/src/test/java/org/thingsboard/server/controller/CustomMenuControllerTest.java @@ -726,6 +726,34 @@ public class CustomMenuControllerTest extends AbstractControllerTest { 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(); 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"); From db4bcc851e67ee9f92bd9fdefea882fc4630c3a5 Mon Sep 17 00:00:00 2001 From: Viacheslav Klimov Date: Fri, 13 Nov 2026 13:56:34 +0200 Subject: [PATCH 11/11] Check the owner of a group by its customer's primary key in tenant-scoped group queries --- .../dao/sql/group/EntityGroupInfoRepository.java | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) 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 079ec133cb..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 @@ -14,11 +14,12 @@ import org.thingsboard.server.dao.model.sql.EntityGroupInfoEntity; import java.util.List; import java.util.UUID; -import static org.thingsboard.server.dao.sql.group.EntityGroupRepository.TENANT_ID_FILTER; - public interface EntityGroupInfoRepository extends JpaRepository { - @Query("SELECT e FROM EntityGroupInfoEntity e WHERE e.id = :entityGroupId AND " + TENANT_ID_FILTER) + 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) " + @@ -70,7 +71,7 @@ public interface EntityGroupInfoRepository extends JpaRepository findEntityGroupsByIds(@Param("tenantId") UUID tenantId, @Param("entityGroupIds") List entityGroupIds, @@ -80,7 +81,7 @@ public interface EntityGroupInfoRepository extends JpaRepository findEntityGroupEntityInfosByIds(@Param("tenantId") UUID tenantId, @Param("entityGroupIds") List entityGroupIds,