From 2b98dfc3246bee0a90cd79cab062eeb7edbdd276 Mon Sep 17 00:00:00 2001 From: Viacheslav Klimov Date: Thu, 12 Nov 2026 00:24:36 +0200 Subject: [PATCH] Check roles against the current user's permissions when sharing an entity group (cherry picked from commit c294cb232f4a64150cfe2e2b573f7d5fb3e702ff) --- .../controller/EntityGroupController.java | 45 ++++- .../controller/EntityGroupControllerTest.java | 168 ++++++++++++++++++ 2 files changed, 204 insertions(+), 9 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 2146550658..6a763b0fab 100644 --- a/application/src/main/java/org/thingsboard/server/controller/EntityGroupController.java +++ b/application/src/main/java/org/thingsboard/server/controller/EntityGroupController.java @@ -57,6 +57,7 @@ import org.thingsboard.server.common.data.permission.Operation; import org.thingsboard.server.common.data.permission.Resource; 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.config.annotations.ApiOperation; import org.thingsboard.server.dao.owner.OwnerService; @@ -1142,7 +1143,8 @@ public class EntityGroupController extends AutoCommitController { @ApiOperation(value = "Share the Entity Group (shareEntityGroup)", notes = "Share the entity group with certain user group based on the provided Share Group Request. " + - "The request is quite flexible and processing of the request involves multiple security checks using platform RBAC feature." + "The request is quite flexible and processing of the request involves multiple security checks using platform RBAC feature. " + + "Each role in 'roleIds' must be a group role readable by the current user, and each of its operations must be granted to the current user for the entity group or its entities." + TENANT_OR_CUSTOMER_AUTHORITY_PARAGRAPH + RBAC_GROUP_WRITE_CHECK) @PreAuthorize("hasAnyAuthority('TENANT_ADMIN', 'CUSTOMER_USER')") @PostMapping(value = "/entityGroup/{entityGroupId}/share") @@ -1170,13 +1172,18 @@ 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 = checkNotNull(entityGroupService.findEntityGroupInfoById(getTenantId(), shareGroupRequest.getUserGroupId())); } accessControlService.checkEntityGroupInfoPermission(getCurrentUser(), Operation.WRITE, userGroup); - List roleIds; + List roles; if (shareGroupRequest.getRoleIds() != null && !shareGroupRequest.getRoleIds().isEmpty()) { - roleIds = shareGroupRequest.getRoleIds(); + roles = new ArrayList<>(); + for (RoleId roleId : shareGroupRequest.getRoleIds()) { + Role role = checkRoleId(roleId, Operation.READ); + checkGroupRoleAllowedForShare(role, entityGroup); + roles.add(role); + } } else { Role role; if (shareGroupRequest.isReadElseWrite()) { @@ -1184,15 +1191,15 @@ public class EntityGroupController extends AutoCommitController { } else { role = roleService.findOrCreateWriteEntityGroupRole(getTenantId(), getCurrentUser().getCustomerId()); } - roleIds = Collections.singletonList(role.getId()); + roles = Collections.singletonList(role); } - for (RoleId roleId : roleIds) { + for (Role role : roles) { GroupPermission groupPermission = new GroupPermission(); groupPermission.setTenantId(getTenantId()); groupPermission.setEntityGroupId(entityGroup.getId()); groupPermission.setEntityGroupType(entityGroup.getType()); - groupPermission.setRoleId(roleId); + groupPermission.setRoleId(role.getId()); groupPermission.setUserGroupId(userGroup.getId()); GroupPermission savedGroupPermission = checkNotNull(groupPermissionService.saveGroupPermission(getTenantId(), groupPermission)); @@ -1501,9 +1508,29 @@ public class EntityGroupController extends AutoCommitController { } } - private void shareGroup(Role role, EntityGroup userGroup, EntityGroup entityGroup, Set mergedOperations) throws ThingsboardException { + private void checkGroupRoleAllowedForShare(Role role, EntityGroup entityGroup) throws ThingsboardException { + if (role.getType() == RoleType.GENERIC) { + throw new ThingsboardException("Can't assign Generic Role to entity group!", ThingsboardErrorCode.BAD_REQUEST_PARAMS); + } + MergedUserPermissions userPermissions = getCurrentUser().getUserPermissions(); + Resource groupResource = Resource.groupResourceFromGroupType(entityGroup.getType()); + Resource entityResource = Resource.resourceFromEntityType(entityGroup.getType()); + for (Operation operation : toRoleOperations(role)) { + if (!userPermissions.hasGenericPermission(groupResource, operation) + && !userPermissions.hasGenericPermission(entityResource, operation) + && !userPermissions.hasGroupPermissions(entityGroup.getId(), operation)) { + throw permissionDenied(); + } + } + } + + private List toRoleOperations(Role role) { CollectionType collectionType = TypeFactory.defaultInstance().constructCollectionType(List.class, Operation.class); - List roleOperations = JacksonUtil.readValue(role.getPermissions().toString(), collectionType); + return JacksonUtil.readValue(role.getPermissions().toString(), collectionType); + } + + private void shareGroup(Role role, EntityGroup userGroup, EntityGroup entityGroup, Set mergedOperations) throws ThingsboardException { + List roleOperations = toRoleOperations(role); if (!mergedOperations.isEmpty() && (mergedOperations.contains(Operation.ALL) || mergedOperations.containsAll(roleOperations))) { GroupPermission savedGroupPermission = groupPermissionService.saveGroupPermission(getTenantId(), new GroupPermission(getTenantId(), userGroup.getId(), role.getId(), entityGroup.getId(), entityGroup.getId().getEntityType(), false)); userPermissionsService.onGroupPermissionUpdated(savedGroupPermission); 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..a6cbf93cca 100644 --- a/application/src/test/java/org/thingsboard/server/controller/EntityGroupControllerTest.java +++ b/application/src/test/java/org/thingsboard/server/controller/EntityGroupControllerTest.java @@ -8,6 +8,7 @@ import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.test.web.servlet.ResultActions; import org.testcontainers.shaded.org.apache.commons.lang3.RandomStringUtils; import org.thingsboard.common.util.JacksonUtil; import org.thingsboard.server.common.data.Dashboard; @@ -18,15 +19,21 @@ import org.thingsboard.server.common.data.User; import org.thingsboard.server.common.data.edge.Edge; import org.thingsboard.server.common.data.group.EntityGroup; import org.thingsboard.server.common.data.group.EntityGroupInfo; +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.RoleId; +import org.thingsboard.server.common.data.id.TenantId; import org.thingsboard.server.common.data.page.PageData; import org.thingsboard.server.common.data.page.PageLink; +import org.thingsboard.server.common.data.permission.GroupPermission; import org.thingsboard.server.common.data.permission.GroupPermissionInfo; import org.thingsboard.server.common.data.permission.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.role.RoleService; import org.thingsboard.server.dao.service.DaoSqlTest; @@ -46,6 +53,12 @@ public class EntityGroupControllerTest extends AbstractControllerTest { @Autowired private RoleService roleService; + @Autowired + private GroupPermissionService groupPermissionService; + + private static final String GROUP_MANAGER_PERMISSIONS = + "{\"DEVICE_GROUP\":[\"READ\",\"WRITE\"],\"USER_GROUP\":[\"READ\",\"WRITE\"],\"GROUP_PERMISSION\":[\"CREATE\"],\"ROLE\":[\"READ\"]}"; + private Tenant savedTenant; private User tenantAdmin; @@ -409,4 +422,159 @@ public class EntityGroupControllerTest extends AbstractControllerTest { Assert.assertNotNull(foundDashboard2); } + @Test + public void testShareEntityGroupWithGroupRole() throws Exception { + loginTenantAdmin(); + EntityGroup deviceGroup = createDeviceGroup("Device Group", tenantId); + Role groupRole = createRole(tenantId, null, "Read role", RoleType.GROUP, "[\"READ\"]"); + + shareWithRoles(deviceGroup, customerId, groupRole.getId()) + .andExpect(status().isOk()); + + assertThat(findSharedRoleIds(deviceGroup)).containsExactly(groupRole.getId()); + } + + @Test + public void testShareEntityGroupRejectsGenericRole() throws Exception { + loginTenantAdmin(); + EntityGroup deviceGroup = createDeviceGroup("Device Group", tenantId); + Role genericRole = createRole(tenantId, null, "Generic role", RoleType.GENERIC, "{\"DEVICE\":[\"READ\"]}"); + + shareWithRoles(deviceGroup, customerId, genericRole.getId()) + .andExpect(status().isBadRequest()); + + assertThat(findSharedRoleIds(deviceGroup)).isEmpty(); + } + + @Test + public void testShareEntityGroupRequiresReadableRole() throws Exception { + createDifferentTenant(); + Role otherTenantRole = createRole(differentTenantId, null, "Read role", RoleType.GROUP, "[\"READ\"]"); + + loginTenantAdmin(); + EntityGroup deviceGroup = createDeviceGroup("Device Group", tenantId); + + shareWithRoles(deviceGroup, customerId, otherTenantRole.getId()) + .andExpect(status().isForbidden()); + + assertThat(findSharedRoleIds(deviceGroup)).isEmpty(); + } + + @Test + public void testShareEntityGroupSavesNothingWhenAnyRoleRejected() throws Exception { + loginTenantAdmin(); + EntityGroup deviceGroup = createDeviceGroup("Device Group", tenantId); + Role groupRole = createRole(tenantId, null, "Read role", RoleType.GROUP, "[\"READ\"]"); + Role genericRole = createRole(tenantId, null, "Generic role", RoleType.GENERIC, "{\"DEVICE\":[\"READ\"]}"); + + shareWithRoles(deviceGroup, customerId, groupRole.getId(), genericRole.getId()) + .andExpect(status().isBadRequest()); + + assertThat(findSharedRoleIds(deviceGroup)).isEmpty(); + } + + @Test + public void testShareEntityGroupRequiresRoleOperationsHeldByUser() throws Exception { + loginTenantAdmin(); + User manager = createGroupManager(createCustomerUserGroup(), GROUP_MANAGER_PERMISSIONS); + EntityGroup deviceGroup = createDeviceGroup("Customer Device Group", customerId); + Role readRole = createRole(tenantId, customerId, "Read role", RoleType.GROUP, "[\"READ\"]"); + Role rpcRole = createRole(tenantId, customerId, "Read and RPC role", RoleType.GROUP, "[\"READ\",\"RPC_CALL\"]"); + + login(manager.getEmail(), "manager"); + shareWithRoles(deviceGroup, customerId, rpcRole.getId()) + .andExpect(status().isForbidden()); + assertThat(findSharedRoleIds(deviceGroup)).isEmpty(); + + shareWithRoles(deviceGroup, customerId, readRole.getId()) + .andExpect(status().isOk()); + assertThat(findSharedRoleIds(deviceGroup)).containsExactly(readRole.getId()); + } + + @Test + public void testShareEntityGroupAllowsRoleOperationsHeldOnEntities() throws Exception { + loginTenantAdmin(); + User manager = createGroupManager(createCustomerUserGroup(), + "{\"DEVICE_GROUP\":[\"READ\",\"WRITE\"],\"DEVICE\":[\"RPC_CALL\"],\"USER_GROUP\":[\"READ\",\"WRITE\"],\"GROUP_PERMISSION\":[\"CREATE\"],\"ROLE\":[\"READ\"]}"); + EntityGroup deviceGroup = createDeviceGroup("Customer Device Group", customerId); + Role rpcRole = createRole(tenantId, customerId, "Read and RPC role", RoleType.GROUP, "[\"READ\",\"RPC_CALL\"]"); + + login(manager.getEmail(), "manager"); + shareWithRoles(deviceGroup, customerId, rpcRole.getId()) + .andExpect(status().isOk()); + assertThat(findSharedRoleIds(deviceGroup)).containsExactly(rpcRole.getId()); + } + + @Test + public void testShareEntityGroupAllowsRoleOperationsHeldOnSharedGroup() throws Exception { + loginTenantAdmin(); + EntityGroup managers = createCustomerUserGroup(); + User manager = createGroupManager(managers, GROUP_MANAGER_PERMISSIONS); + EntityGroup deviceGroup = createDeviceGroup("Customer Device Group", customerId); + Role groupRpcRole = createRole(tenantId, customerId, "RPC role", RoleType.GROUP, "[\"RPC_CALL\"]"); + GroupPermission groupRpcPermission = new GroupPermission(); + groupRpcPermission.setRoleId(groupRpcRole.getId()); + groupRpcPermission.setUserGroupId(managers.getId()); + groupRpcPermission.setEntityGroupId(deviceGroup.getId()); + groupRpcPermission.setEntityGroupType(deviceGroup.getType()); + doPost("/api/groupPermission", groupRpcPermission, GroupPermission.class); + Role rpcRole = createRole(tenantId, customerId, "Read and RPC role", RoleType.GROUP, "[\"READ\",\"RPC_CALL\"]"); + + login(manager.getEmail(), "manager"); + shareWithRoles(deviceGroup, customerId, rpcRole.getId()) + .andExpect(status().isOk()); + assertThat(findSharedRoleIds(deviceGroup)).contains(rpcRole.getId()); + } + + private EntityGroup createCustomerUserGroup() throws Exception { + EntityGroup userGroup = new EntityGroup(); + userGroup.setType(EntityType.USER); + userGroup.setName("Group managers"); + userGroup.setOwnerId(customerId); + return doPost("/api/entityGroup", userGroup, EntityGroup.class); + } + + private User createGroupManager(EntityGroup userGroup, String permissions) throws Exception { + Role managerRole = createRole(tenantId, customerId, "Group manager", RoleType.GENERIC, permissions); + GroupPermission managerPermission = new GroupPermission(); + managerPermission.setRoleId(managerRole.getId()); + managerPermission.setUserGroupId(userGroup.getId()); + doPost("/api/groupPermission", managerPermission, GroupPermission.class); + + User manager = new User(); + manager.setAuthority(Authority.CUSTOMER_USER); + manager.setTenantId(tenantId); + manager.setCustomerId(customerId); + manager.setEmail("groupmanager@thingsboard.org"); + return createUser(manager, "manager", userGroup.getId()); + } + + private EntityGroup createDeviceGroup(String name, EntityId ownerId) throws Exception { + EntityGroup entityGroup = new EntityGroup(); + entityGroup.setType(EntityType.DEVICE); + entityGroup.setName(name); + entityGroup.setOwnerId(ownerId); + return doPost("/api/entityGroup", entityGroup, EntityGroup.class); + } + + private Role createRole(TenantId roleTenantId, CustomerId roleCustomerId, String name, RoleType type, String permissions) { + Role role = new Role(); + role.setTenantId(roleTenantId); + role.setCustomerId(roleCustomerId); + role.setType(type); + role.setName(name); + role.setPermissions(JacksonUtil.toJsonNode(permissions)); + return roleService.saveRole(roleTenantId, role); + } + + private ResultActions shareWithRoles(EntityGroup entityGroup, CustomerId targetCustomerId, RoleId... roleIds) throws Exception { + var shareGroupRequest = new ShareGroupRequest(targetCustomerId, true, null, false, List.of(roleIds)); + return doPost("/api/entityGroup/{entityGroupId}/share", shareGroupRequest, entityGroup.getId().toString()); + } + + private List findSharedRoleIds(EntityGroup entityGroup) { + return groupPermissionService.findGroupPermissionByTenantIdAndEntityGroupId(tenantId, entityGroup.getId(), new PageLink(100)) + .getData().stream().map(GroupPermission::getRoleId).collect(Collectors.toList()); + } + }