diff --git a/application/src/main/java/org/thingsboard/server/controller/AdminController.java b/application/src/main/java/org/thingsboard/server/controller/AdminController.java index 8f6ff14d60..7b33cf7308 100644 --- a/application/src/main/java/org/thingsboard/server/controller/AdminController.java +++ b/application/src/main/java/org/thingsboard/server/controller/AdminController.java @@ -75,7 +75,9 @@ import org.thingsboard.server.service.security.model.SecurityUser; import org.thingsboard.server.service.security.model.token.JwtTokenFactory; import org.thingsboard.server.service.security.system.SystemSecurityService; import org.thingsboard.server.service.sync.vc.EntitiesVersionControlService; +import org.thingsboard.server.service.sync.vc.autocommit.DefaultTbAutoCommitSettingsService; import org.thingsboard.server.service.sync.vc.autocommit.TbAutoCommitSettingsService; +import org.thingsboard.server.service.sync.vc.repository.DefaultTbRepositorySettingsService; import org.thingsboard.server.service.system.SystemInfoService; import org.thingsboard.server.service.update.UpdateService; @@ -166,6 +168,10 @@ public class AdminController extends BaseController { } else { accessControlService.checkPermission(getCurrentUser(), Resource.WHITE_LABELING, Operation.WRITE); } + String key = adminSettings.getKey(); + if (DefaultTbRepositorySettingsService.SETTINGS_KEY.equals(key) || DefaultTbAutoCommitSettingsService.SETTINGS_KEY.equals(key)) { + throw new ThingsboardException("Settings with key '" + key + "' can be saved only through the version control API", ThingsboardErrorCode.BAD_REQUEST_PARAMS); + } adminSettings = checkNotNull(adminSettingsService.saveAdminSettings(tenantId, adminSettings)); if (adminSettings.getKey().equals(MAIL_SETTINGS_KEY)) { ((ObjectNode) adminSettings.getJsonValue()).remove("refreshToken"); diff --git a/application/src/main/java/org/thingsboard/server/controller/ApiKeyController.java b/application/src/main/java/org/thingsboard/server/controller/ApiKeyController.java index 6bc50d1253..77d91794fe 100644 --- a/application/src/main/java/org/thingsboard/server/controller/ApiKeyController.java +++ b/application/src/main/java/org/thingsboard/server/controller/ApiKeyController.java @@ -116,6 +116,10 @@ public class ApiKeyController extends BaseController { UserId userId = new UserId(toUUID(userIdStr)); accessControlService.checkPermission(securityUser, Resource.API_KEY, Operation.READ); User user = checkUserId(userId, Operation.READ); + ApiKeyInfo keyOwner = new ApiKeyInfo(); + keyOwner.setTenantId(user.getTenantId()); + keyOwner.setUserId(userId); + accessControlService.checkPermission(securityUser, Resource.API_KEY, Operation.READ, null, keyOwner); return apiKeyService.findApiKeysByUserId(user.getTenantId(), userId, pageLink); } 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 e597cd192f..ac2750ee56 100644 --- a/application/src/main/java/org/thingsboard/server/controller/BaseController.java +++ b/application/src/main/java/org/thingsboard/server/controller/BaseController.java @@ -148,6 +148,8 @@ import org.thingsboard.server.common.data.menu.CustomMenuInfo; import org.thingsboard.server.common.data.mobile.app.MobileApp; import org.thingsboard.server.common.data.mobile.bundle.MobileAppBundle; import org.thingsboard.server.common.data.notification.targets.NotificationTarget; +import org.thingsboard.server.common.data.notification.template.NotificationTemplate; +import org.thingsboard.server.common.data.notification.template.NotificationTemplateConfig; import org.thingsboard.server.common.data.oauth2.OAuth2Client; import org.thingsboard.server.common.data.page.PageData; import org.thingsboard.server.common.data.page.PageLink; @@ -894,6 +896,49 @@ public abstract class BaseController { } } + protected void checkReportUser(UserId userId) throws ThingsboardException { + if (!getCurrentUser().getId().equals(userId)) { + checkUserId(userId, Operation.IMPERSONATE); + } + } + + protected UserId resolveReportUser(UserId userId, boolean useCurrentUserCredentials) throws ThingsboardException { + SecurityUser currentUser = getCurrentUser(); + if (useCurrentUserCredentials && !currentUser.getId().equals(userId) && !canImpersonate(userId)) { + return currentUser.getId(); + } + checkReportUser(userId); + return userId; + } + + private boolean canImpersonate(UserId userId) throws ThingsboardException { + SecurityUser currentUser = getCurrentUser(); + User user = userService.findUserById(currentUser.getTenantId(), userId); + return user != null && currentUser.getTenantId().equals(user.getTenantId()) && + accessControlService.hasPermission(currentUser, Resource.USER, Operation.IMPERSONATE, userId, user); + } + + protected void checkTemplateReportUser(NotificationTemplate notificationTemplate) throws ThingsboardException { + NotificationTemplateConfig configuration = notificationTemplate != null ? notificationTemplate.getConfiguration() : null; + if (configuration != null && configuration.isAttachReport() && configuration.getUserId() != null) { + checkReportUser(configuration.getUserId()); + } + } + + protected void checkMsgReportUser(JsonNode msg) throws ThingsboardException { + if (msg == null) { + return; + } + checkReportUserIfPresent(msg.path("reportConfig").path("userId")); + checkReportUserIfPresent(msg.path("userId").path("id")); + } + + private void checkReportUserIfPresent(JsonNode reportUserId) throws ThingsboardException { + if (reportUserId.isTextual() && StringUtils.isNotBlank(reportUserId.asText())) { + checkReportUser(new UserId(toUUID(reportUserId.asText()))); + } + } + UserInfo checkUserInfoId(UserId userId, Operation operation) throws ThingsboardException { try { validateId(userId, id -> "Incorrect userId " + id); @@ -1097,7 +1142,11 @@ public abstract class BaseController { for (EntityId referencedEntityId : calculatedFieldConfig.getReferencedEntities()) { EntityType refEntityType = referencedEntityId.getEntityType(); switch (refEntityType) { - case TENANT -> {} + case TENANT -> { + if (!getTenantId().equals(referencedEntityId)) { + throw permissionDenied(); + } + } case CUSTOMER, ASSET, DEVICE -> checkEntityId(referencedEntityId, Operation.READ); default -> throw new IllegalArgumentException("Unsupported referenced entity type: '" + refEntityType + "'."); } @@ -1246,7 +1295,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/DashboardReportController.java b/application/src/main/java/org/thingsboard/server/controller/DashboardReportController.java index 918c5dd8db..0aeae3a97d 100644 --- a/application/src/main/java/org/thingsboard/server/controller/DashboardReportController.java +++ b/application/src/main/java/org/thingsboard/server/controller/DashboardReportController.java @@ -29,6 +29,7 @@ import org.thingsboard.server.common.data.id.DashboardId; import org.thingsboard.server.common.data.id.TenantId; import org.thingsboard.server.common.data.id.UserId; import org.thingsboard.server.common.data.permission.Operation; +import org.thingsboard.server.common.data.security.Authority; import org.thingsboard.server.config.annotations.ApiOperation; import org.thingsboard.server.dao.subscription.PlatformFeature; import org.thingsboard.server.queue.util.TbCoreComponent; @@ -61,6 +62,7 @@ public class DashboardReportController extends BaseController { private final SystemSecurityService systemSecurityService; public static final String DASHBOARD_ID = "dashboardId"; + public static final String USER_ID = "userId"; @ApiOperation(value = "Download dashboard report (downloadDashboardReport)", notes = "Generate and download a report from the specified dashboard. " + @@ -125,6 +127,14 @@ public class DashboardReportController extends BaseController { DashboardId dashboardId = new DashboardId(toUUID(strDashboardId)); checkDashboardInfoId(dashboardId, Operation.READ); + String strUserId = reportConfig.getUserId(); + checkParameter(USER_ID, strUserId); + UserId reportUserId = resolveReportUser(new UserId(toUUID(strUserId)), reportConfig.isUseCurrentUserCredentials()); + reportConfig.setUserId(reportUserId.toString()); + + if (Authority.CUSTOMER_USER.equals(getCurrentUser().getAuthority())) { + reportsServerEndpointUrl = null; + } dashboardReportService.generateReport(getTenantId(), reportConfig, reportsServerEndpointUrl, onSuccess(result), result::setErrorResult); } catch (Exception e) { result.setErrorResult(e); 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 cdf2f171c8..40499b2d2f 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; @@ -210,9 +211,8 @@ public class EntityGroupController extends AutoCommitController { @RequestBody EntityGroup entityGroup) throws Exception { SecurityUser currentUser = getCurrentUser(); checkEntityGroupType(entityGroup.getType()); - Operation operation = entityGroup.getId() == null ? Operation.CREATE : Operation.WRITE; EntityId parentEntityId = entityGroup.getOwnerId(); - if (operation == Operation.CREATE) { + if (entityGroup.getId() == null) { if (parentEntityId == null || parentEntityId.isNullUid()) { parentEntityId = currentUser.getOwnerId(); } else { @@ -221,14 +221,12 @@ public class EntityGroupController extends AutoCommitController { "Invalid entity group ownerId!", ThingsboardErrorCode.PERMISSION_DENIED); } } + EntityGroupInfo entityGroupInfo = new EntityGroupInfo(entityGroup, ownersCacheService.fetchOwnersHierarchy(getTenantId(), parentEntityId)); + accessControlService.checkEntityGroupInfoPermission(currentUser, Operation.CREATE, entityGroupInfo); } else { - validateEntityId(parentEntityId, id -> "Incorrect entity group ownerId " + id); + parentEntityId = checkEntityGroupId(entityGroup.getId(), Operation.WRITE).getOwnerId(); } - EntityGroupInfo entityGroupInfo = new EntityGroupInfo(entityGroup, ownersCacheService.fetchOwnersHierarchy(getTenantId(), parentEntityId)); - - accessControlService.checkEntityGroupInfoPermission(currentUser, operation, entityGroupInfo); - return tbEntityGroupService.save(getTenantId(), parentEntityId, entityGroup, getCurrentUser()); } @@ -967,7 +965,11 @@ public class EntityGroupController extends AutoCommitController { for (String strEntityGroupId : strEntityGroupIds) { entityGroupIds.add(new EntityGroupId(toUUID(strEntityGroupId))); } - return checkNotNull(entityGroupService.findEntityGroupEntityInfosByIds(tenantId, entityGroupIds, new PageLink(Integer.MAX_VALUE)).getData()); + List entityGroups = checkNotNull( + entityGroupService.findEntityGroupInfosByIds(tenantId, entityGroupIds, new PageLink(Integer.MAX_VALUE)).getData()); + return filterEntityGroupsByReadPermission(entityGroups).stream() + .map(entityGroup -> new EntityInfo(entityGroup.getId(), entityGroup.getName())) + .toList(); } @ApiOperation(value = "Get Owners (getOwners)", @@ -1145,7 +1147,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") @@ -1165,21 +1168,25 @@ public class EntityGroupController extends AutoCommitController { EntityGroupInfo userGroup; if (shareGroupRequest.isAllUserGroup()) { - Optional userGroupOptional = entityGroupService.findEntityGroupInfoByTypeAndName(getTenantId(), shareGroupRequest.getOwnerId(), - EntityType.USER, EntityGroup.GROUP_ALL_NAME); + Optional userGroupOptional = findAllUserGroup(shareGroupRequest.getOwnerId()); if (userGroupOptional.isPresent()) { userGroup = userGroupOptional.get(); } else { throw new ThingsboardException("Requested item wasn't found!", ThingsboardErrorCode.ITEM_NOT_FOUND); } } else { - userGroup = entityGroupService.findEntityGroupInfoById(getTenantId(), shareGroupRequest.getUserGroupId()); + userGroup = checkNotNull(entityGroupService.findEntityGroupInfoByTenantIdAndId(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()) { @@ -1187,15 +1194,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)); @@ -1246,7 +1253,7 @@ public class EntityGroupController extends AutoCommitController { checkParameter("userGroupId", strUserGroupId); checkParameter("roleId", strRoleId); EntityGroupId userGroupId = new EntityGroupId(toUUID(strUserGroupId)); - EntityGroup userGroup = entityGroupService.findEntityGroupById(getTenantId(), userGroupId); + EntityGroup userGroup = entityGroupService.findEntityGroupInfoByTenantIdAndId(getTenantId(), userGroupId); if (userGroup == null) { throw new ThingsboardException("User group with requested id: " + userGroupId + " wasn't found!", ThingsboardErrorCode.ITEM_NOT_FOUND); } @@ -1299,7 +1306,7 @@ public class EntityGroupController extends AutoCommitController { private EntityGroup resolveEntityGroup(UUID entityGroupUuid) throws ThingsboardException { EntityGroupId entityGroupId = new EntityGroupId(entityGroupUuid); - EntityGroup entityGroup = entityGroupService.findEntityGroupById(getTenantId(), entityGroupId); + EntityGroup entityGroup = entityGroupService.findEntityGroupInfoByTenantIdAndId(getTenantId(), entityGroupId); if (entityGroup == null) { throw new ThingsboardException("Entity group with requested id: " + entityGroupId + " wasn't found!", ThingsboardErrorCode.ITEM_NOT_FOUND); } @@ -1309,15 +1316,14 @@ public class EntityGroupController extends AutoCommitController { private EntityGroupInfo resolveUserGroup(ShareGroupRequest shareGroupRequest) throws ThingsboardException { EntityGroupInfo userGroup; if (shareGroupRequest.isAllUserGroup()) { - Optional userGroupOptional = entityGroupService.findEntityGroupInfoByTypeAndName(getTenantId(), shareGroupRequest.getOwnerId(), - EntityType.USER, EntityGroup.GROUP_ALL_NAME); + Optional userGroupOptional = findAllUserGroup(shareGroupRequest.getOwnerId()); if (userGroupOptional.isPresent()) { userGroup = userGroupOptional.get(); } else { throw new ThingsboardException("Requested item wasn't found!", ThingsboardErrorCode.ITEM_NOT_FOUND); } } else { - userGroup = entityGroupService.findEntityGroupInfoById(getTenantId(), shareGroupRequest.getUserGroupId()); + userGroup = entityGroupService.findEntityGroupInfoByTenantIdAndId(getTenantId(), shareGroupRequest.getUserGroupId()); } if (userGroup == null) { throw new ThingsboardException("Specified user group wasn't found!", ThingsboardErrorCode.ITEM_NOT_FOUND); @@ -1325,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()) { @@ -1504,9 +1516,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/main/java/org/thingsboard/server/controller/EntityViewController.java b/application/src/main/java/org/thingsboard/server/controller/EntityViewController.java index 4fe1ff0eb7..583afbaaa8 100644 --- a/application/src/main/java/org/thingsboard/server/controller/EntityViewController.java +++ b/application/src/main/java/org/thingsboard/server/controller/EntityViewController.java @@ -48,6 +48,7 @@ import org.thingsboard.server.service.security.model.SecurityUser; import java.util.ArrayList; import java.util.List; +import java.util.Objects; import java.util.Set; import java.util.UUID; import java.util.concurrent.ExecutionException; @@ -132,6 +133,11 @@ public class EntityViewController extends BaseController { SecurityUser user = getCurrentUser(); return saveGroupEntity(entityView, strEntityGroupId, strEntityGroupIds, (entityView1, entityGroups) -> { try { + EntityView existingEntityView = entityView1.getId() == null ? null : + entityViewService.findEntityViewById(user.getTenantId(), entityView1.getId()); + if (existingEntityView == null || !hasSameSourceData(existingEntityView, entityView1)) { + checkEntityId(entityView1.getEntityId(), Operation.READ); + } return tbEntityViewService.save(entityView1, entityGroups, new NameConflictStrategy(nameConflictPolicy, uniquifySeparator, uniquifyStrategy), user); } catch (Exception e) { throw handleException(e); @@ -451,4 +457,11 @@ public class EntityViewController extends BaseController { return checkNotNull(entityViewTypes.get()); } + private static boolean hasSameSourceData(EntityView existing, EntityView entityView) { + return Objects.equals(existing.getEntityId(), entityView.getEntityId()) + && Objects.equals(existing.getKeys(), entityView.getKeys()) + && existing.getStartTimeMs() == entityView.getStartTimeMs() + && existing.getEndTimeMs() == entityView.getEndTimeMs(); + } + } 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..71d2097da7 100644 --- a/application/src/main/java/org/thingsboard/server/controller/GroupPermissionController.java +++ b/application/src/main/java/org/thingsboard/server/controller/GroupPermissionController.java @@ -19,6 +19,7 @@ import org.thingsboard.server.common.data.EntityType; import org.thingsboard.server.common.data.audit.ActionType; import org.thingsboard.server.common.data.exception.ThingsboardErrorCode; import org.thingsboard.server.common.data.exception.ThingsboardException; +import org.thingsboard.server.common.data.group.EntityGroupInfo; import org.thingsboard.server.common.data.id.EntityGroupId; import org.thingsboard.server.common.data.id.EntityId; import org.thingsboard.server.common.data.id.GroupPermissionId; @@ -116,6 +117,7 @@ public class GroupPermissionController extends BaseController { .checkPermission(getCurrentUser(), Resource.GROUP_PERMISSION, Operation.CREATE, null, groupPermission); } else { oldGroupPermission = checkGroupPermissionId(groupPermission.getId(), Operation.WRITE); + checkGroupPermissionManageable(oldGroupPermission); } if (groupPermission.isPublic()) { @@ -168,17 +170,7 @@ public class GroupPermissionController extends BaseController { try { GroupPermissionId groupPermissionId = new GroupPermissionId(toUUID(strGroupPermissionId)); GroupPermission groupPermission = checkGroupPermissionId(groupPermissionId, Operation.DELETE); - if (groupPermission.isPublic()) { - throw permissionDenied(); - } - - checkRoleId(groupPermission.getRoleId(), Operation.READ); - if (groupPermission.getUserGroupId() != null && !groupPermission.getUserGroupId().isNullUid()) { - checkEntityGroupId(groupPermission.getUserGroupId(), Operation.WRITE); - } - if (groupPermission.getEntityGroupId() != null && !groupPermission.getEntityGroupId().isNullUid()) { - checkEntityGroupId(groupPermission.getEntityGroupId(), Operation.WRITE); - } + checkGroupPermissionManageable(groupPermission); groupPermissionService.deleteGroupPermission(getTenantId(), groupPermissionId); userPermissionsService.onGroupPermissionDeleted(groupPermission); @@ -218,7 +210,8 @@ public class GroupPermissionController extends BaseController { @RequestBody List permissions) throws ThingsboardException, ExecutionException, InterruptedException { TenantId tenantId = getCurrentUser().getTenantId(); accessControlService.checkPermission(getCurrentUser(), Resource.GROUP_PERMISSION, Operation.READ); - List permissionInfoList = groupPermissionService.loadUserGroupPermissionInfoListAsync(tenantId, permissions).get(); + List readablePermissions = permissions.stream().filter(this::isReadableEntityGroup).toList(); + List permissionInfoList = groupPermissionService.loadUserGroupPermissionInfoListAsync(tenantId, readablePermissions).get(); return applyPermissionInfo(permissionInfoList); } @@ -255,6 +248,32 @@ public class GroupPermissionController extends BaseController { return groupPermissions; } + private void checkGroupPermissionManageable(GroupPermission groupPermission) throws ThingsboardException { + if (groupPermission.isPublic()) { + throw permissionDenied(); + } + checkRoleId(groupPermission.getRoleId(), Operation.READ); + if (groupPermission.getUserGroupId() != null && !groupPermission.getUserGroupId().isNullUid()) { + checkEntityGroupId(groupPermission.getUserGroupId(), Operation.WRITE); + } + if (groupPermission.getEntityGroupId() != null && !groupPermission.getEntityGroupId().isNullUid()) { + checkEntityGroupId(groupPermission.getEntityGroupId(), Operation.WRITE); + } + } + + 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/NotificationController.java b/application/src/main/java/org/thingsboard/server/controller/NotificationController.java index 75533b0e79..7c43c82422 100644 --- a/application/src/main/java/org/thingsboard/server/controller/NotificationController.java +++ b/application/src/main/java/org/thingsboard/server/controller/NotificationController.java @@ -274,6 +274,9 @@ public class NotificationController extends BaseController { } notificationRequest.setTenantId(user.getTenantId()); checkEntity(notificationRequest.getId(), notificationRequest, NOTIFICATION); + checkTemplateReportUser(notificationRequest.getTemplateId() != null ? + notificationTemplateService.findNotificationTemplateById(user.getTenantId(), notificationRequest.getTemplateId()) : + notificationRequest.getTemplate()); List targets = notificationRequest.getTargets().stream() .map(NotificationTargetId::new) .toList(); diff --git a/application/src/main/java/org/thingsboard/server/controller/NotificationRuleController.java b/application/src/main/java/org/thingsboard/server/controller/NotificationRuleController.java index 81194b517b..ae4f824aa2 100644 --- a/application/src/main/java/org/thingsboard/server/controller/NotificationRuleController.java +++ b/application/src/main/java/org/thingsboard/server/controller/NotificationRuleController.java @@ -20,17 +20,21 @@ import org.springframework.web.bind.annotation.RestController; import org.thingsboard.server.common.data.EntityType; import org.thingsboard.server.common.data.exception.ThingsboardException; import org.thingsboard.server.common.data.id.NotificationRuleId; +import org.thingsboard.server.common.data.id.NotificationTargetId; import org.thingsboard.server.common.data.notification.rule.NotificationRule; import org.thingsboard.server.common.data.notification.rule.NotificationRuleInfo; import org.thingsboard.server.common.data.notification.rule.trigger.config.NotificationRuleTriggerType; +import org.thingsboard.server.common.data.notification.template.NotificationTemplate; import org.thingsboard.server.common.data.page.PageData; import org.thingsboard.server.common.data.page.PageLink; import org.thingsboard.server.common.data.permission.Operation; import org.thingsboard.server.config.annotations.ApiOperation; import org.thingsboard.server.dao.notification.NotificationRuleService; +import org.thingsboard.server.dao.notification.NotificationTemplateService; import org.thingsboard.server.queue.util.TbCoreComponent; import org.thingsboard.server.service.security.model.SecurityUser; +import java.util.List; import java.util.UUID; import static org.thingsboard.server.common.data.permission.Resource.NOTIFICATION; @@ -52,6 +56,7 @@ import static org.thingsboard.server.controller.ControllerConstants.SYSTEM_OR_TE public class NotificationRuleController extends BaseController { private final NotificationRuleService notificationRuleService; + private final NotificationTemplateService notificationTemplateService; @ApiOperation(value = "Save notification rule (saveNotificationRule)", notes = "Creates or updates notification rule. " + NEW_LINE + @@ -106,11 +111,23 @@ public class NotificationRuleController extends BaseController { @AuthenticationPrincipal SecurityUser user) throws Exception { notificationRule.setTenantId(user.getTenantId()); checkEntity(notificationRule.getId(), notificationRule, NOTIFICATION); + if (notificationRule.getTemplateId() != null) { + checkTemplateReportUser(notificationTemplateService.findNotificationTemplateById(user.getTenantId(), notificationRule.getTemplateId())); + } NotificationRuleTriggerType triggerType = notificationRule.getTriggerType(); if ((user.isTenantAdmin() && !triggerType.isTenantLevel()) || (user.isSystemAdmin() && triggerType.isTenantLevel())) { throw new IllegalArgumentException("Trigger type " + triggerType + " is not available"); } + NotificationTemplate template = notificationTemplateService.findNotificationTemplateById(user.getTenantId(), notificationRule.getTemplateId()); + if (template == null || !(template.getTenantId().equals(user.getTenantId()) || template.getTenantId().isSysTenantId())) { + throw new IllegalArgumentException("Notification template not found"); + } + for (List targets : notificationRule.getRecipientsConfig().getTargetsTable().values()) { + for (UUID targetId : targets) { + checkNotificationTargetId(new NotificationTargetId(targetId), Operation.READ); + } + } return doSaveAndLog(EntityType.NOTIFICATION_RULE, notificationRule, notificationRuleService::saveNotificationRule); } diff --git a/application/src/main/java/org/thingsboard/server/controller/NotificationTemplateController.java b/application/src/main/java/org/thingsboard/server/controller/NotificationTemplateController.java index 8f1ead6449..309fe60cb5 100644 --- a/application/src/main/java/org/thingsboard/server/controller/NotificationTemplateController.java +++ b/application/src/main/java/org/thingsboard/server/controller/NotificationTemplateController.java @@ -106,6 +106,7 @@ public class NotificationTemplateController extends BaseController { public NotificationTemplate saveNotificationTemplate(@RequestBody @Valid NotificationTemplate notificationTemplate) throws Exception { notificationTemplate.setTenantId(getTenantId()); checkEntity(notificationTemplate.getId(), notificationTemplate, NOTIFICATION); + checkTemplateReportUser(notificationTemplate); return doSaveAndLog(EntityType.NOTIFICATION_TEMPLATE, notificationTemplate, notificationTemplateService::saveNotificationTemplate); } diff --git a/application/src/main/java/org/thingsboard/server/controller/ReportController.java b/application/src/main/java/org/thingsboard/server/controller/ReportController.java index 12278a78d0..f7c9d4c3a3 100644 --- a/application/src/main/java/org/thingsboard/server/controller/ReportController.java +++ b/application/src/main/java/org/thingsboard/server/controller/ReportController.java @@ -248,9 +248,10 @@ public class ReportController extends BaseController { public ResponseEntity testReportAndDownload(@RequestBody ReportRequest reportRequest) throws Exception { checkFeatureAllowed(PlatformFeature.REPORTING); SecurityUser currentUser = getCurrentUser(); - UserId userId = StringUtils.isNotEmpty(reportRequest.getUserId()) ? new UserId(UUID.fromString(reportRequest.getUserId())) : getCurrentUser().getId(); - EntityId userOwnerId = ownersCacheService.getOwner(currentUser.getTenantId(), userId); + UserId userId = StringUtils.isNotEmpty(reportRequest.getUserId()) ? new UserId(toUUID(reportRequest.getUserId())) : currentUser.getId(); + checkReportUser(userId); checkUserOwnerPermission(currentUser, userId); + EntityId userOwnerId = ownersCacheService.getOwner(currentUser.getTenantId(), userId); AccessJwtToken accessToken = systemSecurityService.createUserAccessToken(currentUser.getTenantId(), userId); ReportTemplateConfig configuration = reportRequest.getReportTemplateConfig(); if (configuration == null) { @@ -301,7 +302,8 @@ public class ReportController extends BaseController { SecurityUser currentUser = getCurrentUser(); UserId userId; if (StringUtils.isNotEmpty(reportRequest.getUserId())) { - userId = new UserId(UUID.fromString(reportRequest.getUserId())); + userId = new UserId(toUUID(reportRequest.getUserId())); + checkReportUser(userId); checkUserOwnerPermission(currentUser, userId); } else { userId = currentUser.getId(); diff --git a/application/src/main/java/org/thingsboard/server/controller/RuleEngineController.java b/application/src/main/java/org/thingsboard/server/controller/RuleEngineController.java index 2c662da1cb..e8608d1898 100644 --- a/application/src/main/java/org/thingsboard/server/controller/RuleEngineController.java +++ b/application/src/main/java/org/thingsboard/server/controller/RuleEngineController.java @@ -158,8 +158,7 @@ public class RuleEngineController extends BaseController { } else { entityId = EntityIdFactory.getByTypeAndId(entityType, entityIdStr); } - //Check that this is a valid JSON - JacksonUtil.toJsonNode(requestBody); + checkMsgReportUser(JacksonUtil.toJsonNode(requestBody)); final DeferredResult response = new DeferredResult<>(); accessValidator.validate(currentUser, Operation.WRITE, entityId, new HttpValidationCallback(response, new FutureCallback>() { @Override diff --git a/application/src/main/java/org/thingsboard/server/controller/SchedulerEventController.java b/application/src/main/java/org/thingsboard/server/controller/SchedulerEventController.java index 8cc02b2eb8..bb2624509d 100644 --- a/application/src/main/java/org/thingsboard/server/controller/SchedulerEventController.java +++ b/application/src/main/java/org/thingsboard/server/controller/SchedulerEventController.java @@ -2,6 +2,7 @@ // SPDX-License-Identifier: BUSL-1.1 package org.thingsboard.server.controller; +import com.fasterxml.jackson.databind.node.ObjectNode; import io.swagger.v3.oas.annotations.Hidden; import io.swagger.v3.oas.annotations.Parameter; import io.swagger.v3.oas.annotations.media.ArraySchema; @@ -21,7 +22,9 @@ import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseStatus; import org.springframework.web.bind.annotation.RestController; import org.thingsboard.common.util.JacksonUtil; +import org.thingsboard.server.common.data.StringUtils; import org.thingsboard.server.common.data.edge.Edge; +import org.thingsboard.server.common.data.exception.ThingsboardErrorCode; import org.thingsboard.server.common.data.exception.ThingsboardException; import org.thingsboard.server.common.data.id.CustomerId; import org.thingsboard.server.common.data.id.EdgeId; @@ -161,11 +164,26 @@ public class SchedulerEventController extends BaseController { private void checkEventConfigPermissions(SchedulerEvent schedulerEvent) throws ThingsboardException { if (GENERATE_REPORT.equals(schedulerEvent.getType())) { SecurityUser currentUser = getCurrentUser(); - ReportConfig reportConfig = checkNotNull(JacksonUtil.treeToValue(schedulerEvent.getConfiguration(), ReportConfig.class), - "Report scheduler event configuration should be specified!"); + ReportConfig reportConfig = JacksonUtil.treeToValue(schedulerEvent.getConfiguration(), ReportConfig.class); + if (reportConfig == null) { + throw new ThingsboardException("Report scheduler event configuration should be specified!", ThingsboardErrorCode.BAD_REQUEST_PARAMS); + } checkReportTemplateId(reportConfig.getReportTemplateId(), Operation.READ); - UserId reportUserId = checkNotNull(reportConfig.getUserId(), "Report user must be specified!"); + UserId reportUserId = reportConfig.getUserId(); + if (reportUserId == null) { + throw new ThingsboardException("Report user must be specified!", ThingsboardErrorCode.BAD_REQUEST_PARAMS); + } + checkReportUser(reportUserId); checkUserOwnerPermission(currentUser, reportUserId); + } else if (schedulerEvent.getConfiguration() != null) { + if (schedulerEvent.getConfiguration().path("msgBody").path("reportConfig") instanceof ObjectNode reportConfig + && reportConfig.path("useCurrentUserCredentials").asBoolean(false) + && reportConfig.path("userId").isTextual() + && StringUtils.isNotBlank(reportConfig.get("userId").asText())) { + UserId reportUserId = resolveReportUser(new UserId(toUUID(reportConfig.get("userId").asText())), true); + reportConfig.put("userId", reportUserId.toString()); + } + checkMsgReportUser(schedulerEvent.getConfiguration().path("msgBody")); } } diff --git a/application/src/main/java/org/thingsboard/server/controller/SelfRegistrationController.java b/application/src/main/java/org/thingsboard/server/controller/SelfRegistrationController.java index 3122c978d1..945bb50108 100644 --- a/application/src/main/java/org/thingsboard/server/controller/SelfRegistrationController.java +++ b/application/src/main/java/org/thingsboard/server/controller/SelfRegistrationController.java @@ -64,6 +64,9 @@ public class SelfRegistrationController extends BaseController { if (selfRegistrationParams.getNotificationRecipient() != null) { checkNotificationTargetId(selfRegistrationParams.getNotificationRecipient(), Operation.READ); } + if (selfRegistrationParams.getDomainId() != null) { + checkDomainId(selfRegistrationParams.getDomainId(), Operation.READ); + } if (Authority.TENANT_ADMIN.equals(authority)) { savedSelfRegistrationParams = whiteLabelingService.saveTenantSelfRegistrationParams(getTenantId(), selfRegistrationParams); JsonNode privacyPolicyNode = whiteLabelingService.getTenantPrivacyPolicy(securityUser.getTenantId()); 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 305385a8e3..7a3cf1eec2 100644 --- a/application/src/main/java/org/thingsboard/server/controller/SignUpController.java +++ b/application/src/main/java/org/thingsboard/server/controller/SignUpController.java @@ -79,7 +79,6 @@ import org.thingsboard.server.service.security.model.SecurityUser; import org.thingsboard.server.service.security.model.UserPrincipal; import org.thingsboard.server.service.security.model.token.JwtTokenFactory; import org.thingsboard.server.service.security.system.SystemSecurityService; -import org.thingsboard.server.utils.MiscUtils; import java.io.ByteArrayInputStream; import java.io.IOException; @@ -209,7 +208,7 @@ public class SignUpController extends BaseController { UserCredentials savedUserCredentials = saveUserCredentials(savedUser, signUpRequest); try { - sendEmailVerification(tenantId, request, savedUserCredentials, email, null, signUpRequest.getPkgName(), signUpRequest.getPlatform()); + sendEmailVerification(tenantId, request, savedUser, savedUserCredentials, email, signUpRequest.getPkgName(), signUpRequest.getPlatform()); } catch (ThingsboardException e) { customerService.deleteCustomer(tenantId, savedCustomer.getId()); throw e; @@ -227,11 +226,9 @@ public class SignUpController extends BaseController { return SignUpResult.SUCCESS; } - private void sendEmailVerification(TenantId tenantId, HttpServletRequest request, UserCredentials userCredentials, - String targetEmail, String baseUrl, String pkgName, PlatformType platformType) throws ThingsboardException { - if (baseUrl == null) { - baseUrl = MiscUtils.constructBaseUrl(request); - } + private void sendEmailVerification(TenantId tenantId, HttpServletRequest request, User user, UserCredentials userCredentials, + String targetEmail, String pkgName, PlatformType platformType) throws ThingsboardException { + String baseUrl = systemSecurityService.getBaseUrl(user.getAuthority(), user.getTenantId(), user.getCustomerId(), request); String activationLink = String.format("%s/api/noauth/activateEmail?emailCode=%s", baseUrl, userCredentials.getActivateToken()); if (!StringUtils.isEmpty(pkgName)) { checkNotNull(platformType); @@ -265,7 +262,7 @@ public class SignUpController extends BaseController { } @ApiOperation(value = "Resend Activation Email (resendEmailActivation)", - notes = "Request to resend the activation email for the user. Checks that user was not activated yet.") + notes = "Request to resend the activation email for a user who signed up through this domain or mobile application and has not verified the email yet.") @PostMapping(value = "/noauth/resendEmailActivation") public void resendEmailActivation( @Parameter(description = "Email of the user.", required = true, example = "john.doe@company.com") @@ -285,19 +282,17 @@ public class SignUpController extends BaseController { } User existingUser = userService.findUserByEmail(TenantId.SYS_TENANT_ID, email); - if (existingUser != null) { - UserCredentials credentials = userService.findUserCredentialsByUserId(existingUser.getTenantId(), existingUser.getId()); - if (credentials.isEnabled()) { - throw new DataValidationException("User with email '" + existingUser.getEmail() + "' " - + " is already active!"); - } else { - credentials = userService.checkUserActivationToken(tenantId, credentials); - sendEmailVerification(tenantId, request, credentials, email, null, pkgName, platform); - } - } else { + if (existingUser == null || !tenantId.equals(existingUser.getTenantId())) { throw new DataValidationException("User with email '" + email + "' " + " is not registered!"); } + UserCredentials credentials = userService.findUserCredentialsByUserId(tenantId, existingUser.getId()); + if (credentials.isEnabled() || credentials.getActivateToken() == null || credentials.getPassword() == null) { + throw new DataValidationException("User with email '" + existingUser.getEmail() + "' " + + " is already active!"); + } + credentials = userService.checkUserActivationToken(tenantId, credentials); + sendEmailVerification(tenantId, request, existingUser, credentials, email, pkgName, platform); } @ApiOperation(value = "Activate User using code from Email (activateEmail)", @@ -395,16 +390,19 @@ public class SignUpController extends BaseController { if (userCredentials.getPassword() == null) { throw new ThingsboardException("Unable to activate user!", ThingsboardErrorCode.PERMISSION_DENIED); } + User user = userService.findUserById(TenantId.SYS_TENANT_ID, userCredentials.getUserId()); + if (user == null || !tenantId.equals(user.getTenantId())) { + throw new ThingsboardException("Invalid email code!", ThingsboardErrorCode.BAD_REQUEST_PARAMS); + } String encodedPassword = userCredentials.getPassword(); UserCredentials credentials = userService.activateUserCredentials(TenantId.SYS_TENANT_ID, emailCode, encodedPassword); - User user = userService.findUserById(TenantId.SYS_TENANT_ID, credentials.getUserId()); long acceptedTs = System.currentTimeMillis(); user.setPrivacyPolicyAccepted(acceptedTs); user.setTermsOfUseAccepted(acceptedTs); user = userService.saveUser(tenantId, user); UserPrincipal principal = new UserPrincipal(UserPrincipal.Type.USER_NAME, user.getEmail()); SecurityUser securityUser = new SecurityUser(user, credentials.isEnabled(), principal, getMergedUserPermissions(user, false)); - String baseUrl = MiscUtils.constructBaseUrl(request); + String baseUrl = systemSecurityService.getBaseUrl(user.getAuthority(), user.getTenantId(), user.getCustomerId(), request); String loginUrl; if (!StringUtils.isEmpty(pkgName)) { loginUrl = UriComponentsBuilder.fromUriString(baseUrl).path("/api/noauth/login") @@ -574,10 +572,11 @@ public class SignUpController extends BaseController { List permissions = selfRegistrationParams.getPermissions(); for (GroupPermission permission : permissions) { + permission.setId(null); permission.setTenantId(tenantId); permission.setUserGroupId(usersEntityGroup.getId()); if (permission.getEntityGroupId() != null) { - EntityGroup entityGroup = entityGroupService.findEntityGroupById(tenantId, permission.getEntityGroupId()); + EntityGroup entityGroup = entityGroupService.findEntityGroupInfoByTenantIdAndId(tenantId, permission.getEntityGroupId()); if (entityGroup != null) { permission.setEntityGroupType(entityGroup.getType()); groupPermissionService.saveGroupPermission(tenantId, permission); diff --git a/application/src/main/java/org/thingsboard/server/controller/UserController.java b/application/src/main/java/org/thingsboard/server/controller/UserController.java index e27dc20357..25dff3c9d4 100644 --- a/application/src/main/java/org/thingsboard/server/controller/UserController.java +++ b/application/src/main/java/org/thingsboard/server/controller/UserController.java @@ -292,7 +292,7 @@ public class UserController extends BaseController { HttpServletRequest request) throws ThingsboardException { SecurityUser securityUser = getCurrentUser(); User user = checkNotNull(userService.findUserByEmail(securityUser.getTenantId(), email)); - accessControlService.checkPermission(securityUser, Resource.USER, Operation.READ, user.getId(), user); + accessControlService.checkPermission(securityUser, Resource.USER, Operation.WRITE, user.getId(), user); UserActivationLink activationLink = tbUserService.getActivationLink(securityUser.getTenantId(), securityUser.getCustomerId(), securityUser.getAuthority(), user.getId(), request); try { @@ -323,7 +323,7 @@ public class UserController extends BaseController { HttpServletRequest request) throws ThingsboardException { checkParameter(USER_ID, strUserId); UserId userId = new UserId(toUUID(strUserId)); - checkUserId(userId, Operation.READ); + checkUserId(userId, Operation.WRITE); SecurityUser securityUser = getCurrentUser(); return tbUserService.getActivationLink(securityUser.getTenantId(), securityUser.getCustomerId(), securityUser.getAuthority(), userId, request); } diff --git a/application/src/main/java/org/thingsboard/server/service/edge/rpc/processor/telemetry/BaseTelemetryProcessor.java b/application/src/main/java/org/thingsboard/server/service/edge/rpc/processor/telemetry/BaseTelemetryProcessor.java index 04d7939917..0f51d5525d 100644 --- a/application/src/main/java/org/thingsboard/server/service/edge/rpc/processor/telemetry/BaseTelemetryProcessor.java +++ b/application/src/main/java/org/thingsboard/server/service/edge/rpc/processor/telemetry/BaseTelemetryProcessor.java @@ -193,7 +193,7 @@ public abstract class BaseTelemetryProcessor extends BaseEdgeProcessor { } } case ENTITY_GROUP -> { - EntityGroup entityGroup = edgeCtx.getEntityGroupService().findEntityGroupById(tenantId, new EntityGroupId(entityId.getId())); + EntityGroup entityGroup = edgeCtx.getEntityGroupService().findEntityGroupInfoByTenantIdAndId(tenantId, new EntityGroupId(entityId.getId())); if (entityGroup != null) { metaData.putValue("entityGroupName", entityGroup.getName()); metaData.putValue("entityGroupType", entityGroup.getType().name()); diff --git a/application/src/main/java/org/thingsboard/server/service/install/update/EntityViewGroupAllUpdater.java b/application/src/main/java/org/thingsboard/server/service/install/update/EntityViewGroupAllUpdater.java index 88b58152ed..212c59aa5d 100644 --- a/application/src/main/java/org/thingsboard/server/service/install/update/EntityViewGroupAllUpdater.java +++ b/application/src/main/java/org/thingsboard/server/service/install/update/EntityViewGroupAllUpdater.java @@ -31,7 +31,7 @@ class EntityViewGroupAllUpdater extends EntityGroupAllPaginatedUpdater { + if (zoneGroupConfiguration.getRefEntityId() != null && zoneGroupConfiguration.getRefEntityId().getEntityType() == EntityType.TENANT) { + zoneGroupConfiguration.setRefEntityId(tenantId); + } + }); + } else if (calculatedField.getConfiguration() instanceof ArgumentsBasedCalculatedFieldConfiguration argBasedConfig) { + argBasedConfig.getArguments().values().forEach(argument -> { + if (argument.getRefEntityId() != null && argument.getRefEntityId().getEntityType() == EntityType.TENANT) { + argument.setRefEntityId(tenantId); + } + }); + } + } + private void updateRuleChain(TenantId tenantId, RuleChainInstalledItemDescriptor descriptor, byte[] fileData) throws Exception { JsonNode json = JacksonUtil.toJsonNode(new String(fileData)); RuleChainMetaData metadata; @@ -680,6 +705,8 @@ public class DefaultIotHubService implements IotHubService { UUID itemId = UUID.fromString(versionInfo.get("itemId").asText()); String version = versionInfo.get("version").asText(); + validateDevicePackageEntities(tenantId, descriptor); + IotHubInstalledItem installedItem = new IotHubInstalledItem(); installedItem.setTenantId(tenantId); installedItem.setItemId(itemId); @@ -801,8 +828,8 @@ public class DefaultIotHubService implements IotHubService { return; } try { - Integration integration = integrationService.findIntegrationById(tenantId, new IntegrationId(entityId.getId())); - if (integration == null || !(integration.getConfiguration() != null + // Only an integration of this tenant: the id comes from the stored descriptor + if (!(findDevicePackageEntity(tenantId, entityId) instanceof Integration integration) || !(integration.getConfiguration() != null && integration.getConfiguration().get("metadata") instanceof ObjectNode metadata) || keys.stream().noneMatch(metadata::has)) { return; @@ -889,7 +916,9 @@ public class DefaultIotHubService implements IotHubService { } private InstalledItemKeptEntities.KeptEntity keptEntity(TenantId tenantId, EntityId entityId) { - return new InstalledItemKeptEntities.KeptEntity(entityId, entityService.fetchEntityName(tenantId, entityId).orElse(null)); + String name = findDevicePackageEntity(tenantId, entityId) != null + ? entityService.fetchEntityName(tenantId, entityId).orElse(null) : null; + return new InstalledItemKeptEntities.KeptEntity(entityId, name); } /** The default rule chains and dashboard of a device profile, which TB doesn't delete while it refers to them; none for another entity. */ @@ -948,36 +977,56 @@ public class DefaultIotHubService implements IotHubService { return usedBy; } - private void deleteDevicePackageEntity(TenantId tenantId, EntityId entityId, SecurityUser user) throws ThingsboardException { - switch (entityId.getEntityType()) { - case DEVICE -> { - var device = deviceService.findDeviceById(tenantId, new DeviceId(entityId.getId())); - if (device != null) tbDeviceService.delete(device, user); - } - case DEVICE_PROFILE -> { - var profile = deviceProfileService.findDeviceProfileById(tenantId, new DeviceProfileId(entityId.getId())); - if (profile != null) tbDeviceProfileService.delete(profile, user); - } - case DASHBOARD -> { - var dashboard = dashboardService.findDashboardById(tenantId, new DashboardId(entityId.getId())); - if (dashboard != null) tbDashboardService.delete(dashboard, user); - } - case RULE_CHAIN -> { - var ruleChain = ruleChainService.findRuleChainById(tenantId, new RuleChainId(entityId.getId())); - if (ruleChain != null) tbRuleChainService.delete(ruleChain, user); - } - case INTEGRATION -> { - IntegrationId integrationId = new IntegrationId(entityId.getId()); - var integration = integrationService.findIntegrationById(tenantId, integrationId); - if (integration != null) { - integrationService.deleteIntegration(tenantId, integrationId); - } - } - case CONVERTER -> { - var converter = converterService.findConverterById(tenantId, new ConverterId(entityId.getId())); - if (converter != null) tbConverterService.delete(converter, user); + private void validateDevicePackageEntities(TenantId tenantId, DeviceInstalledItemDescriptor descriptor) { + if (descriptor == null) { + throw new IllegalArgumentException("Device package descriptor is required"); + } + List entityIds = new ArrayList<>(); + if (descriptor.getCreatedEntityIds() != null) { + entityIds.addAll(descriptor.getCreatedEntityIds()); + } + if (descriptor.getDashboardId() != null) { + entityIds.add(descriptor.getDashboardId()); + } + if (descriptor.getUsedExistingEntityIds() != null) { + entityIds.addAll(descriptor.getUsedExistingEntityIds()); + } + for (EntityId entityId : entityIds) { + if (entityId == null || findDevicePackageEntity(tenantId, entityId) == null) { + throw new IllegalArgumentException("Device package entity not found: " + entityId); } - default -> log.warn("[{}] Unsupported entity type for device package delete: {}", tenantId, entityId.getEntityType()); + } + } + + private HasTenantId findDevicePackageEntity(TenantId tenantId, EntityId entityId) { + HasTenantId entity = switch (entityId.getEntityType()) { + case DEVICE -> deviceService.findDeviceById(tenantId, new DeviceId(entityId.getId())); + case DEVICE_PROFILE -> deviceProfileService.findDeviceProfileById(tenantId, new DeviceProfileId(entityId.getId())); + case DASHBOARD -> dashboardService.findDashboardById(tenantId, new DashboardId(entityId.getId())); + case RULE_CHAIN -> ruleChainService.findRuleChainById(tenantId, new RuleChainId(entityId.getId())); + case INTEGRATION -> integrationService.findIntegrationById(tenantId, new IntegrationId(entityId.getId())); + case CONVERTER -> converterService.findConverterById(tenantId, new ConverterId(entityId.getId())); + default -> null; + }; + return entity != null && tenantId.equals(entity.getTenantId()) ? entity : null; + } + + private void deleteDevicePackageEntity(TenantId tenantId, EntityId entityId, SecurityUser user) throws ThingsboardException { + HasTenantId entity = findDevicePackageEntity(tenantId, entityId); + if (entity instanceof Device device) { + tbDeviceService.delete(device, user); + } else if (entity instanceof DeviceProfile profile) { + tbDeviceProfileService.delete(profile, user); + } else if (entity instanceof Dashboard dashboard) { + tbDashboardService.delete(dashboard, user); + } else if (entity instanceof RuleChain ruleChain) { + tbRuleChainService.delete(ruleChain, user); + } else if (entity instanceof Integration integration) { + integrationService.deleteIntegration(tenantId, integration.getId()); + } else if (entity instanceof Converter converter) { + tbConverterService.delete(converter, user); + } else { + log.warn("[{}] Skipped device package entity {}: not found", tenantId, entityId); } } diff --git a/application/src/main/java/org/thingsboard/server/service/notification/DefaultNotificationCenter.java b/application/src/main/java/org/thingsboard/server/service/notification/DefaultNotificationCenter.java index 496afd8323..9625fa596e 100644 --- a/application/src/main/java/org/thingsboard/server/service/notification/DefaultNotificationCenter.java +++ b/application/src/main/java/org/thingsboard/server/service/notification/DefaultNotificationCenter.java @@ -114,6 +114,9 @@ public class DefaultNotificationCenter extends AbstractSubscriptionService imple NotificationTemplate notificationTemplate; if (request.getTemplateId() != null) { notificationTemplate = notificationTemplateService.findNotificationTemplateById(tenantId, request.getTemplateId()); + if (notificationTemplate != null && !isTenantOrSystem(tenantId, notificationTemplate.getTenantId())) { + notificationTemplate = null; + } } else { notificationTemplate = request.getTemplate(); } @@ -126,7 +129,7 @@ public class DefaultNotificationCenter extends AbstractSubscriptionService imple List targets = new ArrayList<>(); for (UUID targetId : request.getTargets()) { NotificationTarget target = notificationTargetService.findNotificationTargetById(tenantId, new NotificationTargetId(targetId)); - if (target != null) { + if (target != null && tenantId.equals(target.getTenantId())) { targets.add(target); } else { log.debug("Unknown notification target {} in request {}", targetId, request); @@ -516,6 +519,10 @@ public class DefaultNotificationCenter extends AbstractSubscriptionService imple return "notification"; } + private static boolean isTenantOrSystem(TenantId tenantId, TenantId ownerId) { + return tenantId.equals(ownerId) || ownerId.isSysTenantId(); + } + @Autowired public void setChannels(List channels, NotificationCenter webNotificationChannel) { this.channels = channels.stream().collect(Collectors.toMap(NotificationChannel::getDeliveryMethod, c -> c)); diff --git a/application/src/main/java/org/thingsboard/server/service/resource/DefaultTbResourceService.java b/application/src/main/java/org/thingsboard/server/service/resource/DefaultTbResourceService.java index 63c840e7e1..3d7e67456c 100644 --- a/application/src/main/java/org/thingsboard/server/service/resource/DefaultTbResourceService.java +++ b/application/src/main/java/org/thingsboard/server/service/resource/DefaultTbResourceService.java @@ -26,6 +26,7 @@ import org.thingsboard.server.common.data.permission.Resource; import org.thingsboard.server.common.data.widget.WidgetTypeDetails; import org.thingsboard.server.dao.resource.ImageService; import org.thingsboard.server.dao.resource.ResourceService; +import org.thingsboard.server.exception.DataValidationException; import org.thingsboard.server.queue.util.TbCoreComponent; import org.thingsboard.server.service.entitiy.AbstractTbEntityService; import org.thingsboard.server.service.security.model.SecurityUser; @@ -57,6 +58,22 @@ public class DefaultTbResourceService extends AbstractTbEntityService implements @Override public TbResourceInfo save(TbResource resource, SecurityUser user) throws ThingsboardException { + if (resource.getId() != null) { + TbResourceInfo existing = checkNotNull(resourceService.findResourceInfoById(resource.getTenantId(), resource.getId())); + if ((resource.getResourceType() != null && resource.getResourceType() != existing.getResourceType()) || + (resource.getResourceSubType() != null && resource.getResourceSubType() != existing.getResourceSubType())) { + throw new DataValidationException("Resource type can't be changed"); + } + resource.setTenantId(existing.getTenantId()); + resource.setCustomerId(existing.getCustomerId()); + resource.setResourceType(existing.getResourceType()); + resource.setResourceSubType(existing.getResourceSubType()); + resource.setResourceKey(existing.getResourceKey()); + resource.setCreatedTime(existing.getCreatedTime()); + if (resource.getData() == null) { + resource.setEtag(existing.getEtag()); + } + } if (resource.getResourceType() == ResourceType.IMAGE) { throw new IllegalArgumentException("Image resource type is not supported"); } diff --git a/application/src/main/java/org/thingsboard/server/service/scheduler/DefaultSchedulerService.java b/application/src/main/java/org/thingsboard/server/service/scheduler/DefaultSchedulerService.java index 7cd5cc685c..9859d9052b 100644 --- a/application/src/main/java/org/thingsboard/server/service/scheduler/DefaultSchedulerService.java +++ b/application/src/main/java/org/thingsboard/server/service/scheduler/DefaultSchedulerService.java @@ -274,7 +274,7 @@ public class DefaultSchedulerService extends AbstractPartitionBasedService entityGroupFuture = entityGroupService.findEntityGroupInfoByIdAsync(currentUser.getTenantId(), new EntityGroupId(entityId.getId())); + ListenableFuture entityGroupFuture = entityGroupService.findEntityGroupInfoByTenantIdAndIdAsync(currentUser.getTenantId(), new EntityGroupId(entityId.getId())); Futures.addCallback(entityGroupFuture, getCallback(callback, entityGroup -> { if (entityGroup == null) { return ValidationResult.entityNotFound("Entity group with requested id wasn't found!"); diff --git a/application/src/main/java/org/thingsboard/server/service/security/auth/oauth2/CustomOAuth2ClientMapper.java b/application/src/main/java/org/thingsboard/server/service/security/auth/oauth2/CustomOAuth2ClientMapper.java index cabe46baa9..4730ebb2b0 100644 --- a/application/src/main/java/org/thingsboard/server/service/security/auth/oauth2/CustomOAuth2ClientMapper.java +++ b/application/src/main/java/org/thingsboard/server/service/security/auth/oauth2/CustomOAuth2ClientMapper.java @@ -29,7 +29,7 @@ public class CustomOAuth2ClientMapper extends AbstractOAuth2ClientMapper impleme private static final String PROVIDER_ACCESS_TOKEN = "provider-access-token"; - private RestTemplateBuilder restTemplateBuilder = new RestTemplateBuilder(); + private final RestTemplateBuilder restTemplateBuilder = new RestTemplateBuilder(); @Override public SecurityUser getOrCreateUserByClientPrincipal(HttpServletRequest request, OAuth2AuthenticationToken token, String providerAccessToken, OAuth2Client auth2Client) { @@ -38,15 +38,16 @@ public class CustomOAuth2ClientMapper extends AbstractOAuth2ClientMapper impleme return getOrCreateSecurityUserFromOAuth2User(oauth2User, auth2Client); } - private synchronized OAuth2User getOAuth2User(OAuth2AuthenticationToken token, String providerAccessToken, OAuth2CustomMapperConfig custom) { + private OAuth2User getOAuth2User(OAuth2AuthenticationToken token, String providerAccessToken, OAuth2CustomMapperConfig custom) { + RestTemplateBuilder builder = restTemplateBuilder; if (!StringUtils.isEmpty(custom.getUsername()) && !StringUtils.isEmpty(custom.getPassword())) { - restTemplateBuilder = restTemplateBuilder.basicAuthentication(custom.getUsername(), custom.getPassword()); + builder = builder.basicAuthentication(custom.getUsername(), custom.getPassword()); } if (custom.isSendToken() && !StringUtils.isEmpty(providerAccessToken)) { - restTemplateBuilder = restTemplateBuilder.defaultHeader(PROVIDER_ACCESS_TOKEN, providerAccessToken); + builder = builder.defaultHeader(PROVIDER_ACCESS_TOKEN, providerAccessToken); } - RestTemplate restTemplate = restTemplateBuilder.build(); + RestTemplate restTemplate = builder.build(); String request; try { request = JacksonUtil.getObjectMapperWithJavaTimeModule().writeValueAsString(token.getPrincipal()); diff --git a/application/src/main/java/org/thingsboard/server/service/security/permission/CustomerUserPermissions.java b/application/src/main/java/org/thingsboard/server/service/security/permission/CustomerUserPermissions.java index 632dae9836..56fdba5d93 100644 --- a/application/src/main/java/org/thingsboard/server/service/security/permission/CustomerUserPermissions.java +++ b/application/src/main/java/org/thingsboard/server/service/security/permission/CustomerUserPermissions.java @@ -25,6 +25,7 @@ import org.thingsboard.server.common.data.id.HasId; import org.thingsboard.server.common.data.id.ReportTemplateId; import org.thingsboard.server.common.data.id.TbResourceId; import org.thingsboard.server.common.data.menu.CustomMenuInfo; +import org.thingsboard.server.common.data.pat.ApiKeyInfo; import org.thingsboard.server.common.data.permission.GroupPermission; import org.thingsboard.server.common.data.permission.Operation; import org.thingsboard.server.common.data.permission.Resource; @@ -525,6 +526,9 @@ public class CustomerUserPermissions extends AbstractPermissions { if (!user.getTenantId().equals(entity.getTenantId())) { return false; } + if (!(entity instanceof ApiKeyInfo apiKeyInfo) || !user.getId().equals(apiKeyInfo.getUserId())) { + return false; + } // This entity does not have groups, so we are checking only generic level permissions return user.getUserPermissions().hasGenericPermission(Resource.API_KEY, operation); } diff --git a/application/src/main/java/org/thingsboard/server/service/security/system/DefaultSystemSecurityService.java b/application/src/main/java/org/thingsboard/server/service/security/system/DefaultSystemSecurityService.java index 5a582026fd..ff2185e91b 100644 --- a/application/src/main/java/org/thingsboard/server/service/security/system/DefaultSystemSecurityService.java +++ b/application/src/main/java/org/thingsboard/server/service/security/system/DefaultSystemSecurityService.java @@ -332,7 +332,7 @@ public class DefaultSystemSecurityService implements SystemSecurityService { @Override public AccessJwtToken createUserAccessToken(TenantId tenantId, UserId userId) throws ThingsboardException { User user = userService.findUserById(tenantId, userId); - if (user == null) { + if (user == null || !user.getTenantId().equals(tenantId)) { throw new ThingsboardException("Configured user [id: " + userId + "] was not found in system. Please use other user credentials.", ThingsboardErrorCode.BAD_REQUEST_PARAMS); } UserCredentials credentials = userService.findUserCredentialsByUserId(tenantId, userId); diff --git a/application/src/main/java/org/thingsboard/server/utils/MiscUtils.java b/application/src/main/java/org/thingsboard/server/utils/MiscUtils.java index 7bb4775f16..bec30a395e 100644 --- a/application/src/main/java/org/thingsboard/server/utils/MiscUtils.java +++ b/application/src/main/java/org/thingsboard/server/utils/MiscUtils.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.utils; import com.google.common.hash.HashFunction; @@ -43,13 +44,20 @@ public class MiscUtils { getPort(request)); } - public static String getScheme(HttpServletRequest request){ - String scheme = request.getScheme(); + public static String getScheme(HttpServletRequest request) { String forwardedProto = request.getHeader("x-forwarded-proto"); - if (forwardedProto != null) { - scheme = forwardedProto; + if (isHttpScheme(forwardedProto)) { + return forwardedProto.toLowerCase(); + } + String scheme = request.getScheme(); + if (forwardedProto == null && isHttpScheme(scheme)) { + return scheme.toLowerCase(); } - return scheme; + return request.isSecure() ? "https" : "http"; + } + + private static boolean isHttpScheme(String scheme) { + return "http".equalsIgnoreCase(scheme) || "https".equalsIgnoreCase(scheme); } public static String getDomainName(HttpServletRequest request){ diff --git a/application/src/test/java/org/thingsboard/server/controller/AdminControllerTest.java b/application/src/test/java/org/thingsboard/server/controller/AdminControllerTest.java index b571440e70..76683aea2f 100644 --- a/application/src/test/java/org/thingsboard/server/controller/AdminControllerTest.java +++ b/application/src/test/java/org/thingsboard/server/controller/AdminControllerTest.java @@ -10,6 +10,7 @@ import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.RandomStringUtils; import org.junit.Test; import org.mockito.Mockito; +import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.bean.override.mockito.MockitoBean; import org.thingsboard.common.util.JacksonUtil; import org.thingsboard.server.common.data.AdminSettings; @@ -17,9 +18,11 @@ import org.thingsboard.server.common.data.id.TenantId; import org.thingsboard.server.common.data.security.model.JwtSettings; import org.thingsboard.server.dao.secret.SecretConfigurationService; import org.thingsboard.server.dao.service.DaoSqlTest; +import org.thingsboard.server.dao.settings.AdminSettingsService; import java.nio.charset.StandardCharsets; import java.util.Base64; +import java.util.Map; import static org.assertj.core.api.Assertions.assertThat; import static org.hamcrest.Matchers.containsString; @@ -44,6 +47,9 @@ public class AdminControllerTest extends AbstractControllerTest { @MockitoBean private SecretConfigurationService secretConfigurationService; + @Autowired + private AdminSettingsService adminSettingsService; + @Test public void testFindAdminSettingsByKey() throws Exception { loginSysAdmin(); @@ -111,6 +117,30 @@ public class AdminControllerTest extends AbstractControllerTest { .andExpect(statusReason(containsString("is prohibited"))); } + @Test + public void testSaveAdminSettingsRefusesVersionControlKeys() throws Exception { + loginTenantAdmin(); + checkVersionControlKeysRefused(tenantId); + + loginSysAdmin(); + checkVersionControlKeysRefused(TenantId.SYS_TENANT_ID); + } + + private void checkVersionControlKeysRefused(TenantId settingsTenantId) throws Exception { + Map values = Map.of( + "entitiesVersionControl", "{\"repositoryUri\":\"repo1\",\"defaultBranch\":\"main\"}", + "autoCommitSettings", "{}"); + for (Map.Entry entry : values.entrySet()) { + AdminSettings settings = new AdminSettings(); + settings.setKey(entry.getKey()); + settings.setJsonValue(JacksonUtil.toJsonNode(entry.getValue())); + doPost("/api/admin/settings", settings) + .andExpect(status().isBadRequest()) + .andExpect(statusReason(containsString("version control API"))); + assertThat(adminSettingsService.findAdminSettingsByTenantIdAndKey(settingsTenantId, entry.getKey())).isNull(); + } + } + @Test public void testMailOAuth2AuthorizationStoresOnlyInAppPrevUri() throws Exception { loginSysAdmin(); diff --git a/application/src/test/java/org/thingsboard/server/controller/AlarmRuleControllerTest.java b/application/src/test/java/org/thingsboard/server/controller/AlarmRuleControllerTest.java index cec0df49ee..e0f675d3e8 100644 --- a/application/src/test/java/org/thingsboard/server/controller/AlarmRuleControllerTest.java +++ b/application/src/test/java/org/thingsboard/server/controller/AlarmRuleControllerTest.java @@ -98,6 +98,32 @@ public class AlarmRuleControllerTest extends AbstractControllerTest { .andExpect(status().isOk()); } + @Test + public void testSaveAlarmRuleWithOtherTenantReference() throws Exception { + Device testDevice = createDevice("Test device", "1234567890"); + AlarmRuleDefinition alarmRule = createTestAlarmRule(testDevice.getId(), "High Temperature"); + alarmRule.getConfiguration().getArguments().get("temperature").setRefEntityId(tenantId); + + doPost("/api/alarm/rule", alarmRule).andExpect(status().isForbidden()); + + PageData alarmRules = doGetTypedWithPageLink( + "/api/alarm/rules/" + EntityType.DEVICE + "/" + testDevice.getUuidId() + "?", + new TypeReference<>() {}, new PageLink(10)); + assertThat(alarmRules.getData()).isEmpty(); + } + + @Test + public void testSaveAlarmRuleWithOwnTenantReference() throws Exception { + Device testDevice = createDevice("Test device", "1234567890"); + AlarmRuleDefinition alarmRule = createTestAlarmRule(testDevice.getId(), "High Temperature"); + alarmRule.getConfiguration().getArguments().get("temperature").setRefEntityId(savedTenant.getId()); + + AlarmRuleDefinition saved = saveAlarmRule(alarmRule); + + assertThat(saved.getId()).isNotNull(); + assertThat(saved.getConfiguration().getArguments().get("temperature").getRefEntityId()).isEqualTo(savedTenant.getId()); + } + @Test public void testGetAlarmRuleById() throws Exception { Device testDevice = createDevice("Test device", "1234567890"); diff --git a/application/src/test/java/org/thingsboard/server/controller/ApiKeyControllerTest.java b/application/src/test/java/org/thingsboard/server/controller/ApiKeyControllerTest.java index b0cca491a3..b19cb3131b 100644 --- a/application/src/test/java/org/thingsboard/server/controller/ApiKeyControllerTest.java +++ b/application/src/test/java/org/thingsboard/server/controller/ApiKeyControllerTest.java @@ -234,6 +234,57 @@ public class ApiKeyControllerTest extends AbstractControllerTest { doDelete("/api/apiKey/" + savedApiKey.getId().getId()).andExpect(status().isOk()); } + @Test + public void testCustomerUserListsOwnApiKeys() throws Exception { + loginCustomerAdminUser(); + ApiKeyInfo apiKeyInfo = constructApiKeyInfo("Test API key description", true); + apiKeyInfo.setUserId(customerAdminUserId); + doPost("/api/apiKey", apiKeyInfo, ApiKey.class); + + PageData pageData = doGetTypedWithPageLink("/api/apiKeys/" + customerAdminUserId + "?", new TypeReference<>() {}, new PageLink(10, 0)); + Assert.assertEquals(1, pageData.getData().size()); + Assert.assertEquals(customerAdminUserId, pageData.getData().get(0).getUserId()); + } + + @Test + public void testTenantAdminListsCustomerUserApiKeys() throws Exception { + ApiKeyInfo apiKeyInfo = constructApiKeyInfo("Test API key description", true); + apiKeyInfo.setUserId(customerUserId); + doPost("/api/apiKey", apiKeyInfo, ApiKey.class); + + PageData pageData = doGetTypedWithPageLink("/api/apiKeys/" + customerUserId + "?", new TypeReference<>() {}, new PageLink(10, 0)); + Assert.assertEquals(1, pageData.getData().size()); + Assert.assertEquals(customerUserId, pageData.getData().get(0).getUserId()); + } + + @Test + public void testCustomerUserCannotListOtherUserApiKeys() throws Exception { + loginCustomerAdminUser(); + doGet("/api/user/" + customerUserId).andExpect(status().isOk()); + doGet("/api/apiKeys/" + customerUserId + "?pageSize=10&page=0").andExpect(status().isForbidden()); + } + + @Test + public void testCustomerUserCannotReadOtherUserApiKeyRelations() throws Exception { + ApiKeyInfo apiKeyInfo = constructApiKeyInfo("Test API key description", true); + apiKeyInfo.setUserId(customerUserId); + ApiKey apiKey = doPost("/api/apiKey", apiKeyInfo, ApiKey.class); + + loginCustomerAdminUser(); + doGet("/api/relations?fromId=" + apiKey.getId().getId() + "&fromType=API_KEY").andExpect(status().isForbidden()); + } + + @Test + public void testCustomerUserCannotDeleteTenantAdminApiKey() throws Exception { + ApiKey apiKey = doPost("/api/apiKey", constructApiKeyInfo("Test API key description", true), ApiKey.class); + + loginCustomerAdminUser(); + doDelete("/api/apiKey/" + apiKey.getId().getId()).andExpect(status().isForbidden()); + + loginTenantAdmin(); + doDelete("/api/apiKey/" + apiKey.getId().getId()).andExpect(status().isOk()); + } + private ApiKeyInfo constructApiKeyInfo(String description, boolean enabled) { ApiKeyInfo apiKeyInfo = new ApiKeyInfo(); apiKeyInfo.setDescription(description); diff --git a/application/src/test/java/org/thingsboard/server/controller/AuthControllerTest.java b/application/src/test/java/org/thingsboard/server/controller/AuthControllerTest.java index 7fd2d8e9be..78d22aec65 100644 --- a/application/src/test/java/org/thingsboard/server/controller/AuthControllerTest.java +++ b/application/src/test/java/org/thingsboard/server/controller/AuthControllerTest.java @@ -16,7 +16,11 @@ import org.thingsboard.server.common.data.StringUtils; import org.thingsboard.server.common.data.User; import org.thingsboard.server.common.data.UserActivationLink; import org.thingsboard.server.common.data.UserInfo; +import org.thingsboard.server.common.data.exception.ThingsboardErrorCode; +import org.thingsboard.server.common.data.exception.ThingsboardException; import org.thingsboard.server.common.data.id.UserId; +import org.thingsboard.server.common.data.permission.Operation; +import org.thingsboard.server.common.data.permission.Resource; import org.thingsboard.server.common.data.security.Authority; import org.thingsboard.server.common.data.security.UserCredentials; import org.thingsboard.server.common.data.security.model.SecuritySettings; @@ -24,6 +28,7 @@ import org.thingsboard.server.dao.service.DaoSqlTest; import org.thingsboard.server.dao.user.UserCredentialsDao; import org.thingsboard.server.service.security.auth.rest.LoginRequest; import org.thingsboard.server.service.security.model.ChangePasswordRequest; +import org.thingsboard.server.service.security.permission.AccessControlService; import java.util.concurrent.TimeUnit; import java.util.function.Consumer; @@ -33,6 +38,8 @@ import static org.assertj.core.api.Assertions.within; import static org.hamcrest.Matchers.is; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.doThrow; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.header; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; @@ -43,6 +50,9 @@ public class AuthControllerTest extends AbstractControllerTest { @MockitoSpyBean private UserCredentialsDao userCredentialsDao; + @MockitoSpyBean + private AccessControlService accessControlService; + @After public void tearDown() throws Exception { loginSysAdmin(); @@ -287,6 +297,26 @@ public class AuthControllerTest extends AbstractControllerTest { assertThat(getUser(user.getId()).getAdditionalInfo().get("userActivated").asBoolean()).isTrue(); } + @Test + public void testActivationLinkRequiresWritePermissionOnUser() throws Exception { + loginTenantAdmin(); + User user = new User(); + user.setAuthority(Authority.TENANT_ADMIN); + user.setEmail("pending-user@thingsboard.org"); + user = doPost("/api/user", user, User.class); + + doThrow(new ThingsboardException("You don't have permission to perform this operation!", ThingsboardErrorCode.PERMISSION_DENIED)) + .when(accessControlService).checkPermission(any(), eq(Resource.USER), eq(Operation.WRITE), eq(user.getId()), any()); + + doGet("/api/user/" + user.getId() + "/activationLinkInfo").andExpect(status().isForbidden()); + doGet("/api/user/" + user.getId() + "/activationLink").andExpect(status().isForbidden()); + doPost("/api/user/sendActivationMail?email=" + user.getEmail()).andExpect(status().isForbidden()); + + Mockito.reset(accessControlService); + assertThat(getActivationLinkInfo(user).value()).isNotBlank(); + doPost("/api/user/sendActivationMail?email=" + user.getEmail()).andExpect(status().isOk()); + } + @Test public void testGetPageWithoutRedirect() throws Exception { doGet("/login").andExpect(status().isOk()); diff --git a/application/src/test/java/org/thingsboard/server/controller/CalculatedFieldControllerTest.java b/application/src/test/java/org/thingsboard/server/controller/CalculatedFieldControllerTest.java index 55d3930fec..34ba0d1cf8 100644 --- a/application/src/test/java/org/thingsboard/server/controller/CalculatedFieldControllerTest.java +++ b/application/src/test/java/org/thingsboard/server/controller/CalculatedFieldControllerTest.java @@ -2,6 +2,7 @@ // SPDX-License-Identifier: Apache-2.0 package org.thingsboard.server.controller; +import com.fasterxml.jackson.core.type.TypeReference; import org.junit.After; import org.junit.Before; import org.junit.Test; @@ -41,6 +42,7 @@ import org.thingsboard.server.common.data.security.Authority; import org.thingsboard.server.dao.service.DaoSqlTest; import java.util.Comparator; +import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.concurrent.TimeUnit; @@ -298,6 +300,48 @@ public class CalculatedFieldControllerTest extends AbstractControllerTest { doGet("/api/calculatedField/" + savedCalculatedField.getId().getId()).andExpect(status().isNotFound()); } + @Test + public void testSaveCalculatedFieldWithOtherTenantReference() throws Exception { + Device testDevice = createDevice("Test device", "1234567890"); + CalculatedField calculatedField = getSimpleCalculatedField(testDevice.getId(), Map.of("T", getArgument(tenantId))); + + doPost("/api/calculatedField", calculatedField).andExpect(status().isForbidden()); + + PageData calculatedFields = doGetTyped("/api/DEVICE/" + testDevice.getId().getId() + "/calculatedFields?pageSize=10&page=0", + new TypeReference<>() {}); + assertThat(calculatedFields.getData()).isEmpty(); + } + + @Test + public void testSaveCalculatedFieldWithOwnTenantReference() throws Exception { + Device testDevice = createDevice("Test device", "1234567890"); + CalculatedField calculatedField = getSimpleCalculatedField(testDevice.getId(), Map.of("T", getArgument(savedTenant.getId()))); + + CalculatedField savedCalculatedField = doPost("/api/calculatedField", calculatedField, CalculatedField.class); + + assertThat(savedCalculatedField.getId()).isNotNull(); + assertThat(savedCalculatedField.getConfiguration().getReferencedEntities()).containsExactly(savedTenant.getId()); + } + + @Test + public void testSaveCalculatedFieldChecksEveryReference() throws Exception { + loginTenantAdmin(); + Device otherTenantDevice = createDevice("Other device", "0987654321"); + login("tenant2@thingsboard.org", "testPassword1"); + + Device testDevice = createDevice("Test device", "1234567890"); + Map arguments = new LinkedHashMap<>(); + arguments.put("T", getArgument(savedTenant.getId())); + arguments.put("H", getArgument(otherTenantDevice.getId())); + CalculatedField calculatedField = getSimpleCalculatedField(testDevice.getId(), arguments); + + doPost("/api/calculatedField", calculatedField).andExpect(status().isNotFound()); + } + + private CalculatedField getSimpleCalculatedField(EntityId entityId, Map arguments) { + return getCalculatedField(entityId, CalculatedFieldType.SIMPLE, getSimpleCalculatedFieldConfig(arguments)); + } + private CalculatedField getSimpleCalculatedField(EntityId entityId) { return getCalculatedField(entityId, CalculatedFieldType.SIMPLE); } @@ -385,14 +429,13 @@ public class CalculatedFieldControllerTest extends AbstractControllerTest { } private CalculatedFieldConfiguration getSimpleCalculatedFieldConfig() { - SimpleCalculatedFieldConfiguration config = new SimpleCalculatedFieldConfiguration(); + return getSimpleCalculatedFieldConfig(Map.of("T", getArgument(null))); + } - Argument argument = new Argument(); - argument.setRefEntityId(null); - ReferencedEntityKey refEntityKey = new ReferencedEntityKey("temperature", ArgumentType.TS_LATEST, null); - argument.setRefEntityKey(refEntityKey); + private CalculatedFieldConfiguration getSimpleCalculatedFieldConfig(Map arguments) { + SimpleCalculatedFieldConfiguration config = new SimpleCalculatedFieldConfiguration(); - config.setArguments(Map.of("T", argument)); + config.setArguments(arguments); config.setExpression("T - (100 - H) / 5"); @@ -404,4 +447,11 @@ public class CalculatedFieldControllerTest extends AbstractControllerTest { return config; } + private Argument getArgument(EntityId refEntityId) { + Argument argument = new Argument(); + argument.setRefEntityId(refEntityId); + argument.setRefEntityKey(new ReferencedEntityKey("temperature", ArgumentType.TS_LATEST, null)); + return argument; + } + } 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 6a5e024094..083b94e183 100644 --- a/application/src/test/java/org/thingsboard/server/controller/CustomMenuControllerTest.java +++ b/application/src/test/java/org/thingsboard/server/controller/CustomMenuControllerTest.java @@ -657,6 +657,120 @@ public class CustomMenuControllerTest extends AbstractControllerTest { assertThat(currentMenu.get("items")).isEmpty(); } + @Test + public void testCustomerUserMenuIgnoresMenuOfOtherTenant() throws Exception { + loginDifferentTenant(); + CustomMenu otherTenantMenu = new CustomMenu(); + otherTenantMenu.setName(RandomStringUtils.randomAlphabetic(10)); + otherTenantMenu.setScope(CMScope.CUSTOMER); + otherTenantMenu.setAssigneeType(CMAssigneeType.NO_ASSIGN); + otherTenantMenu = doPost("/api/customMenu", otherTenantMenu, CustomMenu.class); + idsToRemove.add(otherTenantMenu.getUuidId()); + CustomMenuConfig otherTenantMenuConfig = putRandomMenuConfig(otherTenantMenu.getId()); + String otherTenantMenuUrl = ((CustomMenuItem) otherTenantMenuConfig.getItems().get(2)).getUrl(); + + loginTenantAdmin(); + Customer customer = doGet("/api/customer/" + customerId.getId(), Customer.class); + customer.setCustomMenuId(otherTenantMenu.getId()); + doPost("/api/customer", customer).andExpect(status().isOk()); + + loginCustomerUser(); + JsonNode customerUserMenu = doGet("/api/customMenu", JsonNode.class); + assertThat(customerUserMenu.toString()).doesNotContain(otherTenantMenuUrl); + } + + @Test + public void testTenantUserMenuIgnoresMenuOfOtherTenant() throws Exception { + loginDifferentTenant(); + CustomMenu otherTenantMenu = new CustomMenu(); + otherTenantMenu.setName(RandomStringUtils.randomAlphabetic(10)); + otherTenantMenu.setScope(CMScope.TENANT); + otherTenantMenu.setAssigneeType(CMAssigneeType.NO_ASSIGN); + otherTenantMenu = doPost("/api/customMenu", otherTenantMenu, CustomMenu.class); + idsToRemove.add(otherTenantMenu.getUuidId()); + CustomMenuConfig otherTenantMenuConfig = putRandomMenuConfig(otherTenantMenu.getId()); + String otherTenantMenuUrl = ((CustomMenuItem) otherTenantMenuConfig.getItems().get(2)).getUrl(); + + loginTenantAdmin(); + User tenantAdmin = doGet("/api/user/" + tenantAdminUserId.getId(), User.class); + tenantAdmin.setCustomMenuId(otherTenantMenu.getId()); + doPost("/api/user", tenantAdmin).andExpect(status().isOk()); + assertThat(doGet("/api/user/" + tenantAdminUserId.getId(), User.class).getCustomMenuId()).isEqualTo(otherTenantMenu.getId()); + + JsonNode tenantAdminMenu = doGet("/api/customMenu", JsonNode.class); + assertThat(tenantAdminMenu.toString()).doesNotContain(otherTenantMenuUrl); + } + + @Test + public void testCustomMenuAssigneeListContainsOnlyCustomersOfMenuTenant() throws Exception { + loginTenantAdmin(); + CustomMenu customerMenu = new CustomMenu(); + customerMenu.setName(RandomStringUtils.randomAlphabetic(10)); + customerMenu.setScope(CMScope.CUSTOMER); + customerMenu.setAssigneeType(CMAssigneeType.CUSTOMERS); + customerMenu = doPost("/api/customMenu?assignToList=" + customerId, customerMenu, CustomMenu.class); + + loginDifferentTenant(); + Customer otherTenantCustomer = new Customer(); + otherTenantCustomer.setTitle("Other Tenant Customer"); + otherTenantCustomer.setCustomMenuId(customerMenu.getId()); + otherTenantCustomer = doPost("/api/customer", otherTenantCustomer, Customer.class); + + loginTenantAdmin(); + List assigneeList = doGetTyped("/api/customMenu/" + customerMenu.getId() + "/assigneeList", new TypeReference<>() {}); + assertThat(assigneeList).extracting(EntityInfo::getId).containsExactly(customerId); + doDelete("/api/customMenu/" + customerMenu.getId() + "?force=true").andExpect(status().isOk()); + + loginDifferentTenant(); + Customer otherTenantCustomerAfterDelete = doGet("/api/customer/" + otherTenantCustomer.getId(), Customer.class); + assertThat(otherTenantCustomerAfterDelete.getCustomMenuId()).isEqualTo(customerMenu.getId()); + } + + @Test + public void testCustomMenuAssigneeListContainsOnlyUsersOfMenuTenant() throws Exception { + loginTenantAdmin(); + CustomMenu userMenu = new CustomMenu(); + userMenu.setName(RandomStringUtils.randomAlphabetic(10)); + userMenu.setScope(CMScope.TENANT); + userMenu.setAssigneeType(CMAssigneeType.USERS); + userMenu = doPost("/api/customMenu?assignToList=" + tenantAdminUserId, userMenu, CustomMenu.class); + + loginDifferentTenant(); + User otherTenantUser = new User(); + otherTenantUser.setAuthority(Authority.TENANT_ADMIN); + otherTenantUser.setTenantId(differentTenantId); + otherTenantUser.setEmail("othertenantuser@thingsboard.org"); + otherTenantUser.setCustomMenuId(userMenu.getId()); + otherTenantUser = doPost("/api/user", otherTenantUser, User.class); + assertThat(otherTenantUser.getCustomMenuId()).isEqualTo(userMenu.getId()); + + loginTenantAdmin(); + List assigneeList = doGetTyped("/api/customMenu/" + userMenu.getId() + "/assigneeList", new TypeReference<>() {}); + assertThat(assigneeList).extracting(EntityInfo::getId).containsExactly(tenantAdminUserId); + doDelete("/api/customMenu/" + userMenu.getId() + "?force=true").andExpect(status().isOk()); + + loginDifferentTenant(); + User otherTenantUserAfterDelete = doGet("/api/user/" + otherTenantUser.getId(), User.class); + assertThat(otherTenantUserAfterDelete.getCustomMenuId()).isEqualTo(userMenu.getId()); + } + + @Test + public void testTenantUserGetsAssignedSystemMenu() throws Exception { + loginSysAdmin(); + CustomMenu systemMenu = new CustomMenu(); + systemMenu.setName(RandomStringUtils.randomAlphabetic(10)); + systemMenu.setScope(CMScope.TENANT); + systemMenu.setAssigneeType(CMAssigneeType.NO_ASSIGN); + systemMenu = doPost("/api/customMenu", systemMenu, CustomMenu.class); + idsToRemove.add(systemMenu.getUuidId()); + CustomMenuConfig systemMenuConfig = putRandomMenuConfig(systemMenu.getId()); + doPut("/api/customMenu/" + systemMenu.getId() + "/assign/USERS", List.of(tenantAdminUserId.getId())); + + loginTenantAdmin(); + JsonNode tenantAdminMenu = doGet("/api/customMenu", JsonNode.class); + assertCustomMenuConfig(tenantAdminMenu, systemMenuConfig); + } + private MvcResult getUserCustomMenu() throws Exception { return getUserCustomMenu(null); } diff --git a/application/src/test/java/org/thingsboard/server/controller/DashboardReportControllerTest.java b/application/src/test/java/org/thingsboard/server/controller/DashboardReportControllerTest.java new file mode 100644 index 0000000000..a54efa04ab --- /dev/null +++ b/application/src/test/java/org/thingsboard/server/controller/DashboardReportControllerTest.java @@ -0,0 +1,195 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +package org.thingsboard.server.controller; + +import org.junit.Before; +import org.junit.Test; +import org.springframework.test.context.bean.override.mockito.MockitoSpyBean; +import org.springframework.test.web.servlet.ResultActions; +import org.thingsboard.common.util.JacksonUtil; +import org.thingsboard.rule.engine.api.DashboardReportService; +import org.thingsboard.server.common.data.Dashboard; +import org.thingsboard.server.common.data.EntityType; +import org.thingsboard.server.common.data.User; +import org.thingsboard.server.common.data.dashboardreport.DashboardReportConfig; +import org.thingsboard.server.common.data.dashboardreport.DashboardReportData; +import org.thingsboard.server.common.data.group.EntityGroup; +import org.thingsboard.server.common.data.id.UserId; +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.dao.service.DaoSqlTest; + +import java.util.concurrent.TimeUnit; +import java.util.function.Consumer; + +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.argThat; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.ArgumentMatchers.isNull; +import static org.mockito.Mockito.doAnswer; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +@DaoSqlTest +public class DashboardReportControllerTest extends AbstractControllerTest { + + private static final String DASHBOARD_VIEWER_EMAIL = "dashboard.viewer@thingsboard.org"; + private static final String DASHBOARD_VIEWER_PASSWORD = "viewer"; + private static final String REPORTS_SERVER_URL = "http://localhost:8383"; + private static final String REPORT_BASE_URL = "http://localhost:8081"; + + @MockitoSpyBean + private DashboardReportService dashboardReportService; + + private Dashboard dashboard; + + @Before + public void beforeTest() throws Exception { + loginSubCustomerAdminUser(); + Dashboard dashboard = new Dashboard(); + dashboard.setTitle("Sub-customer dashboard"); + this.dashboard = doPost("/api/dashboard", dashboard, Dashboard.class); + + doAnswer(invocation -> { + Consumer onSuccess = invocation.getArgument(3); + DashboardReportData reportData = new DashboardReportData(); + reportData.setData(new byte[]{1}); + reportData.setName("report.pdf"); + reportData.setContentType("application/pdf"); + onSuccess.accept(reportData); + return null; + }).when(dashboardReportService).generateReport(any(), any(), any(), any(), any()); + } + + @Test + public void testDownloadTestReportRequiresPermissionOverReportUser() throws Exception { + loginDifferentTenant(); + UserId otherTenantUserId = savedDifferentTenantUser.getId(); + loginDifferentCustomer(); + + loginCustomerAdminUser(); + doPostTestReport(tenantAdminUserId.toString()).andExpect(status().isForbidden()); + doPostTestReport(differentCustomerUserId.toString()).andExpect(status().isForbidden()); + doPostTestReport(otherTenantUserId.toString()).andExpect(status().isForbidden()); + + loginSubCustomerAdminUser(); + doPostTestReport(customerAdminUserId.toString()).andExpect(status().isForbidden()); + + loginTenantAdmin(); + doPostTestReport(otherTenantUserId.toString()).andExpect(status().isForbidden()); + + createDashboardViewer(); + login(DASHBOARD_VIEWER_EMAIL, DASHBOARD_VIEWER_PASSWORD); + doPostTestReport(customerAdminUserId.toString()).andExpect(status().isForbidden()); + doPostTestReport(customerUserId.toString()).andExpect(status().isForbidden()); + + verify(dashboardReportService, never()).generateReport(any(), any(), any(), any(), any()); + } + + @Test + public void testDownloadTestReportAllowedForOwnUser() throws Exception { + loginCustomerAdminUser(); + doPostTestReport(customerAdminUserId.toString()).andExpect(status().isOk()); + verifyReportGenerated(customerAdminUserId); + + UserId dashboardViewerId = createDashboardViewer(); + login(DASHBOARD_VIEWER_EMAIL, DASHBOARD_VIEWER_PASSWORD); + doPostTestReport(dashboardViewerId.toString()).andExpect(status().isOk()); + verifyReportGenerated(dashboardViewerId); + } + + @Test + public void testDownloadTestReportAllowedForOwnedUser() throws Exception { + loginTenantAdmin(); + doPostTestReport(customerUserId.toString()).andExpect(status().isOk()); + verifyReportGenerated(customerUserId); + + loginCustomerAdminUser(); + doPostTestReport(subCustomerAdminUserId.toString()).andExpect(status().isOk()); + verifyReportGenerated(subCustomerAdminUserId); + doPostTestReport(customerUserId.toString()).andExpect(status().isOk()); + } + + @Test + public void testDownloadTestReportWithCurrentUserCredentialsUsesCurrentUserWhenReportUserNotAccessible() throws Exception { + loginCustomerAdminUser(); + doPostTestReport(tenantAdminUserId.toString(), null, true).andExpect(status().isOk()); + verifyReportGenerated(customerAdminUserId); + } + + @Test + public void testDownloadTestReportRequiresUserId() throws Exception { + loginCustomerAdminUser(); + doPostTestReport(null).andExpect(status().isBadRequest()); + doPostTestReport("not-a-uuid").andExpect(status().isBadRequest()); + verify(dashboardReportService, never()).generateReport(any(), any(), any(), any(), any()); + } + + @Test + public void testDownloadTestReportUsesSystemReportServerForCustomerUser() throws Exception { + loginCustomerAdminUser(); + doPostTestReport(customerAdminUserId.toString(), REPORTS_SERVER_URL).andExpect(status().isOk()); + verify(dashboardReportService).generateReport(eq(tenantId), any(), isNull(), any(), any()); + + loginTenantAdmin(); + doPostTestReport(tenantAdminUserId.toString(), REPORTS_SERVER_URL).andExpect(status().isOk()); + verify(dashboardReportService).generateReport(eq(tenantId), any(), eq(REPORTS_SERVER_URL), any(), any()); + } + + private UserId createDashboardViewer() throws Exception { + loginTenantAdmin(); + Role role = new Role(); + role.setTenantId(tenantId); + role.setCustomerId(customerId); + role.setType(RoleType.GENERIC); + role.setName("Dashboard viewer"); + role.setPermissions(JacksonUtil.toJsonNode("{\"DASHBOARD\":[\"READ\"]}")); + role = doPost("/api/role", role, Role.class); + + EntityGroup userGroup = new EntityGroup(); + userGroup.setName("Dashboard viewers"); + userGroup.setType(EntityType.USER); + userGroup.setOwnerId(customerId); + userGroup = doPost("/api/entityGroup", userGroup, EntityGroup.class); + doPost("/api/groupPermission", new GroupPermission(tenantId, userGroup.getId(), role.getId(), null, null, false), GroupPermission.class); + + User user = new User(); + user.setAuthority(Authority.CUSTOMER_USER); + user.setTenantId(tenantId); + user.setCustomerId(customerId); + user.setEmail(DASHBOARD_VIEWER_EMAIL); + return createUser(user, DASHBOARD_VIEWER_PASSWORD, userGroup.getId()).getId(); + } + + private ResultActions doPostTestReport(String userId) throws Exception { + return doPostTestReport(userId, null); + } + + private ResultActions doPostTestReport(String userId, String reportsServerEndpointUrl) throws Exception { + return doPostTestReport(userId, reportsServerEndpointUrl, false); + } + + private ResultActions doPostTestReport(String userId, String reportsServerEndpointUrl, boolean useCurrentUserCredentials) throws Exception { + DashboardReportConfig reportConfig = new DashboardReportConfig(); + reportConfig.setBaseUrl(REPORT_BASE_URL); + reportConfig.setDashboardId(dashboard.getId().toString()); + reportConfig.setTimezone("UTC"); + reportConfig.setNamePattern("report"); + reportConfig.setType("pdf"); + reportConfig.setUserId(userId); + reportConfig.setUseCurrentUserCredentials(useCurrentUserCredentials); + String url = "/api/report/test"; + if (reportsServerEndpointUrl != null) { + url += "?reportsServerEndpointUrl=" + reportsServerEndpointUrl; + } + return doPostAsync(url, reportConfig, TimeUnit.SECONDS.toMillis(30)); + } + + private void verifyReportGenerated(UserId userId) throws Exception { + verify(dashboardReportService).generateReport(eq(tenantId), argThat(config -> userId.toString().equals(config.getUserId())), any(), any(), any()); + } + +} diff --git a/application/src/test/java/org/thingsboard/server/controller/DevelopmentNoticeCaptureStampTest.java b/application/src/test/java/org/thingsboard/server/controller/DevelopmentNoticeCaptureStampTest.java index 6a0631fd98..bf401d10fe 100644 --- a/application/src/test/java/org/thingsboard/server/controller/DevelopmentNoticeCaptureStampTest.java +++ b/application/src/test/java/org/thingsboard/server/controller/DevelopmentNoticeCaptureStampTest.java @@ -62,7 +62,7 @@ public class DevelopmentNoticeCaptureStampTest { .as("no subscribing call to %s in the capture path to order against", STAMP_METHOD) .isTrue(); - int captured = capture.indexOf("html2canvas("); + int captured = capture.indexOf("domToCanvas("); int serialised = capture.indexOf("toDataURL"); assertThat(captured).as("no capture call found to order against").isNotNegative(); assertThat(serialised).as("no serialisation call found to order against").isNotNegative(); 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 55fcc19539..7806255698 100644 --- a/application/src/test/java/org/thingsboard/server/controller/EntityGroupControllerTest.java +++ b/application/src/test/java/org/thingsboard/server/controller/EntityGroupControllerTest.java @@ -9,34 +9,47 @@ 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; 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; 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.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; 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; import java.util.ArrayList; import java.util.Collections; import java.util.List; +import java.util.UUID; import java.util.stream.Collectors; import static org.assertj.core.api.Assertions.assertThat; import static org.hamcrest.Matchers.containsString; +import static org.hamcrest.Matchers.is; +import static org.hamcrest.Matchers.not; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; @DaoSqlTest @@ -45,6 +58,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; @@ -89,6 +108,300 @@ public class EntityGroupControllerTest extends AbstractControllerTest { Assert.assertEquals(savedEntityGroup.getName(), foundEntityGroup.getName()); } + @Test + public void testShouldNotChangeEntityGroupOwnerAsGroupOwner() throws Exception { + loginTenantAdmin(); + EntityGroup entityGroup = new EntityGroup(); + entityGroup.setName("Device Group"); + entityGroup.setType(EntityType.DEVICE); + EntityGroup savedEntityGroup = doPost("/api/entityGroup", entityGroup, EntityGroup.class); + + savedEntityGroup.setOwnerId(customerId); + doPost("/api/entityGroup", savedEntityGroup) + .andExpect(status().isBadRequest()) + .andExpect(statusReason(containsString("Entity group owner can't be changed!"))); + + assertThat(entityGroupService.findEntityGroupById(tenantId, savedEntityGroup.getId()).getOwnerId()).isEqualTo(tenantId); + } + + @Test + public void testShouldNotChangeEntityGroupType() throws Exception { + loginTenantAdmin(); + EntityGroup entityGroup = new EntityGroup(); + entityGroup.setName("Device Group"); + entityGroup.setType(EntityType.DEVICE); + EntityGroup savedEntityGroup = doPost("/api/entityGroup", entityGroup, EntityGroup.class); + + savedEntityGroup.setType(EntityType.USER); + doPost("/api/entityGroup", savedEntityGroup) + .andExpect(status().isBadRequest()) + .andExpect(statusReason(containsString("Entity group type can't be changed!"))); + + assertThat(entityGroupService.findEntityGroupById(tenantId, savedEntityGroup.getId()).getType()).isEqualTo(EntityType.DEVICE); + } + + @Test + public void testShouldNotMoveTenantEntityGroupToCustomerAsCustomerAdmin() throws Exception { + EntityGroup tenantAdministratorsGroup = entityGroupService.findEntityGroupByTypeAndName(tenantId, tenantId, + EntityType.USER, EntityGroup.GROUP_TENANT_ADMINS_NAME).get(); + + loginCustomerAdminUser(); + EntityGroup movedEntityGroup = new EntityGroup(tenantAdministratorsGroup); + movedEntityGroup.setOwnerId(customerId); + doPost("/api/entityGroup", movedEntityGroup) + .andExpect(status().isForbidden()); + + assertThat(entityGroupService.findEntityGroupById(tenantId, tenantAdministratorsGroup.getId()).getOwnerId()).isEqualTo(tenantId); + } + + @Test + public void testShouldNotMoveEntityGroupSharedWithWriteAccess() throws Exception { + loginTenantAdmin(); + EntityGroup entityGroup = new EntityGroup(); + entityGroup.setName("Shared Device Group"); + entityGroup.setType(EntityType.DEVICE); + EntityGroup savedEntityGroup = doPost("/api/entityGroup", entityGroup, EntityGroup.class); + var shareGroupRequest = new ShareGroupRequest(customerId, true, null, false, Collections.emptyList()); + doPost("/api/entityGroup/{entityGroupId}/share", shareGroupRequest, savedEntityGroup.getId().toString()) + .andExpect(status().isOk()); + + loginCustomerAdminUser(); + EntityGroup sharedEntityGroup = doGet("/api/entityGroup/" + savedEntityGroup.getId().getId(), EntityGroup.class); + sharedEntityGroup.setOwnerId(customerId); + doPost("/api/entityGroup", sharedEntityGroup) + .andExpect(status().isForbidden()); + + assertThat(entityGroupService.findEntityGroupById(tenantId, savedEntityGroup.getId()).getOwnerId()).isEqualTo(tenantId); + } + + @Test + public void testShouldNotMoveOtherTenantEntityGroup() throws Exception { + loginDifferentTenant(); + EntityGroup entityGroup = new EntityGroup(); + entityGroup.setName("Other Tenant Device Group"); + entityGroup.setType(EntityType.DEVICE); + EntityGroup otherTenantEntityGroup = doPost("/api/entityGroup", entityGroup, EntityGroup.class); + + loginCustomerAdminUser(); + otherTenantEntityGroup.setOwnerId(customerId); + doPost("/api/entityGroup", otherTenantEntityGroup) + .andExpect(status().isNotFound()); + + assertThat(entityGroupService.findEntityGroupById(differentTenantId, otherTenantEntityGroup.getId()).getOwnerId()).isEqualTo(differentTenantId); + } + + @Test + public void testGetEntityGroupInfosByIdsReturnsOnlyOwnTenantGroups() throws Exception { + loginTenantAdmin(); + EntityGroup ownGroup = new EntityGroup(); + ownGroup.setName("Own Device Group"); + ownGroup.setType(EntityType.DEVICE); + ownGroup = doPost("/api/entityGroup", ownGroup, EntityGroup.class); + + loginDifferentTenant(); + EntityGroup otherTenantGroup = new EntityGroup(); + otherTenantGroup.setName("Other Tenant Device Group"); + otherTenantGroup.setType(EntityType.DEVICE); + otherTenantGroup = doPost("/api/entityGroup", otherTenantGroup, EntityGroup.class); + + loginTenantAdmin(); + List entityInfos = doGetTyped("/api/entityGroupInfos?entityGroupIds=" + ownGroup.getId().getId() + "," + otherTenantGroup.getId().getId(), + new TypeReference<>() {}); + assertThat(entityInfos).extracting(EntityInfo::getId).containsExactly(ownGroup.getId()); + } + + @Test + public void testGetEntityGroupInfosByIdsReturnsOnlyReadableGroups() throws Exception { + loginTenantAdmin(); + EntityGroup tenantGroup = new EntityGroup(); + tenantGroup.setName("Tenant Device Group"); + tenantGroup.setType(EntityType.DEVICE); + tenantGroup = doPost("/api/entityGroup", tenantGroup, EntityGroup.class); + + loginCustomerAdminUser(); + EntityGroup customerGroup = new EntityGroup(); + customerGroup.setName("Customer Device Group"); + customerGroup.setType(EntityType.DEVICE); + customerGroup.setOwnerId(customerId); + customerGroup = doPost("/api/entityGroup", customerGroup, EntityGroup.class); + + List entityInfos = doGetTyped("/api/entityGroupInfos?entityGroupIds=" + customerGroup.getId().getId() + "," + tenantGroup.getId().getId(), + new TypeReference<>() {}); + assertThat(entityInfos).extracting(EntityInfo::getId).containsExactly(customerGroup.getId()); + } + + @Test + public void testShareGroupWithUserGroupOfOtherTenantReturnsNotFound() throws Exception { + loginDifferentTenant(); + EntityGroup otherTenantUserGroup = new EntityGroup(); + otherTenantUserGroup.setName("Other Tenant User Group"); + otherTenantUserGroup.setType(EntityType.USER); + otherTenantUserGroup = doPost("/api/entityGroup", otherTenantUserGroup, EntityGroup.class); + + loginTenantAdmin(); + EntityGroup deviceGroup = new EntityGroup(); + deviceGroup.setName("Shared Device Group"); + deviceGroup.setType(EntityType.DEVICE); + deviceGroup = doPost("/api/entityGroup", deviceGroup, EntityGroup.class); + + ShareGroupRequest shareGroupRequest = new ShareGroupRequest(tenantId, false, otherTenantUserGroup.getId(), true, null); + doPost("/api/entityGroup/" + deviceGroup.getId().getId() + "/share", shareGroupRequest) + .andExpect(status().isNotFound()) + .andExpect(statusReason(not(containsString(otherTenantUserGroup.getName())))); + } + + @Test + public void testShareGroupV2WithUserGroupOfOtherTenantReturnsNotFound() throws Exception { + loginDifferentTenant(); + EntityGroup otherTenantUserGroup = new EntityGroup(); + otherTenantUserGroup.setName("Other Tenant User Group"); + otherTenantUserGroup.setType(EntityType.USER); + otherTenantUserGroup = doPost("/api/entityGroup", otherTenantUserGroup, EntityGroup.class); + + loginTenantAdmin(); + EntityGroup deviceGroup = new EntityGroup(); + deviceGroup.setName("Shared Device Group"); + deviceGroup.setType(EntityType.DEVICE); + deviceGroup = doPost("/api/entityGroup", deviceGroup, EntityGroup.class); + + ShareGroupRequest shareGroupRequest = new ShareGroupRequest(tenantId, false, otherTenantUserGroup.getId(), true, null); + doPost("/api/v2/entityGroup/" + deviceGroup.getId().getId() + "/share", shareGroupRequest) + .andExpect(status().isNotFound()) + .andExpect(statusReason(not(containsString(otherTenantUserGroup.getName())))); + } + + @Test + public void testShareGroupWithAllUsersGroupOfOtherTenantReturnsNotFound() throws Exception { + loginDifferentTenant(); + loginTenantAdmin(); + EntityGroup deviceGroup = createDeviceGroup("Shared Device Group", tenantId); + + ShareGroupRequest unknownOwnerRequest = new ShareGroupRequest(TenantId.fromUUID(UUID.randomUUID()), true, null, true, null); + doPost("/api/entityGroup/{entityGroupId}/share", unknownOwnerRequest, deviceGroup.getId().toString()) + .andExpect(status().isNotFound()) + .andExpect(statusReason(is(msgErrorNotFound))); + ShareGroupRequest otherTenantRequest = new ShareGroupRequest(differentTenantId, true, null, true, null); + doPost("/api/entityGroup/{entityGroupId}/share", otherTenantRequest, deviceGroup.getId().toString()) + .andExpect(status().isNotFound()) + .andExpect(statusReason(is(msgErrorNotFound))); + assertThat(findSharedUserGroupIds(deviceGroup)).isEmpty(); + } + + @Test + public void testShareGroupWithAllUsersGroupOfOwnCustomerSharesWithThatGroup() throws Exception { + loginTenantAdmin(); + EntityGroup deviceGroup = createDeviceGroup("Shared Device Group", tenantId); + EntityGroup customerAllUsersGroup = entityGroupService.findEntityGroupByTypeAndName(tenantId, customerId, + EntityType.USER, EntityGroup.GROUP_ALL_NAME).get(); + + ShareGroupRequest shareGroupRequest = new ShareGroupRequest(customerId, true, null, true, null); + doPost("/api/entityGroup/{entityGroupId}/share", shareGroupRequest, deviceGroup.getId().toString()) + .andExpect(status().isOk()); + assertThat(findSharedUserGroupIds(deviceGroup)).containsExactly(customerAllUsersGroup.getId()); + } + + @Test + public void testShareGroupV2WithAllUsersGroupOfOtherTenantReturnsNotFound() throws Exception { + loginDifferentTenant(); + loginTenantAdmin(); + EntityGroup deviceGroup = createDeviceGroup("Shared Device Group", tenantId); + + ShareGroupRequest unknownOwnerRequest = new ShareGroupRequest(TenantId.fromUUID(UUID.randomUUID()), true, null, true, null); + doPost("/api/v2/entityGroup/{entityGroupId}/share", unknownOwnerRequest, deviceGroup.getId().toString()) + .andExpect(status().isNotFound()) + .andExpect(statusReason(is(msgErrorNotFound))); + ShareGroupRequest otherTenantRequest = new ShareGroupRequest(differentTenantId, true, null, true, null); + doPost("/api/v2/entityGroup/{entityGroupId}/share", otherTenantRequest, deviceGroup.getId().toString()) + .andExpect(status().isNotFound()) + .andExpect(statusReason(is(msgErrorNotFound))); + assertThat(findSharedUserGroupIds(deviceGroup)).isEmpty(); + } + + @Test + public void testShareGroupV2WithAllUsersGroupOfOwnCustomerSharesWithThatGroup() throws Exception { + loginTenantAdmin(); + EntityGroup deviceGroup = createDeviceGroup("Shared Device Group", tenantId); + EntityGroup customerAllUsersGroup = entityGroupService.findEntityGroupByTypeAndName(tenantId, customerId, + EntityType.USER, EntityGroup.GROUP_ALL_NAME).get(); + + ShareGroupRequest shareGroupRequest = new ShareGroupRequest(customerId, true, null, true, null); + doPost("/api/v2/entityGroup/{entityGroupId}/share", shareGroupRequest, deviceGroup.getId().toString()) + .andExpect(status().isOk()); + assertThat(findSharedUserGroupIds(deviceGroup)).containsExactly(customerAllUsersGroup.getId()); + } + + @Test + public void testShareGroupToChildOwnerUserGroupWithGroupsOfOtherTenantReturnsNotFound() throws Exception { + loginDifferentTenant(); + EntityGroup otherTenantUserGroup = new EntityGroup(); + otherTenantUserGroup.setName("Other Tenant User Group"); + otherTenantUserGroup.setType(EntityType.USER); + otherTenantUserGroup = doPost("/api/entityGroup", otherTenantUserGroup, EntityGroup.class); + EntityGroup otherTenantDeviceGroup = new EntityGroup(); + otherTenantDeviceGroup.setName("Other Tenant Device Group"); + otherTenantDeviceGroup.setType(EntityType.DEVICE); + otherTenantDeviceGroup = doPost("/api/entityGroup", otherTenantDeviceGroup, EntityGroup.class); + + loginTenantAdmin(); + EntityGroup deviceGroup = new EntityGroup(); + deviceGroup.setName("Shared Device Group"); + deviceGroup.setType(EntityType.DEVICE); + deviceGroup = doPost("/api/entityGroup", deviceGroup, EntityGroup.class); + EntityGroup userGroup = new EntityGroup(); + userGroup.setName("Own User Group"); + userGroup.setType(EntityType.USER); + userGroup = doPost("/api/entityGroup", userGroup, EntityGroup.class); + Role role = new Role(); + role.setName("Read Group Role"); + role.setType(RoleType.GROUP); + role.setPermissions(JacksonUtil.valueToTree(List.of(Operation.READ))); + role = doPost("/api/role", role, Role.class); + + doPost("/api/entityGroup/" + deviceGroup.getId().getId() + "/" + otherTenantUserGroup.getId().getId() + "/" + role.getId().getId() + "/share") + .andExpect(status().isNotFound()); + doPost("/api/entityGroup/" + otherTenantDeviceGroup.getId().getId() + "/" + userGroup.getId().getId() + "/" + role.getId().getId() + "/share") + .andExpect(status().isNotFound()); + } + + @Test + public void testGetAttributesOfEntityGroupOfOtherTenantReturnsNotFound() throws Exception { + loginDifferentTenant(); + EntityGroup otherTenantGroup = new EntityGroup(); + otherTenantGroup.setName("Other Tenant Asset Group"); + otherTenantGroup.setType(EntityType.ASSET); + otherTenantGroup = doPost("/api/entityGroup", otherTenantGroup, EntityGroup.class); + + loginTenantAdmin(); + doGetAsync("/api/plugins/telemetry/ENTITY_GROUP/" + otherTenantGroup.getId().getId() + "/values/attributes") + .andExpect(status().isNotFound()); + } + + @Test + public void testGetEntityGroupOfOtherTenantReturnsNotFound() throws Exception { + loginDifferentTenant(); + EntityGroup otherTenantGroup = new EntityGroup(); + otherTenantGroup.setName("Other Tenant Asset Group"); + otherTenantGroup.setType(EntityType.ASSET); + otherTenantGroup = doPost("/api/entityGroup", otherTenantGroup, EntityGroup.class); + + loginTenantAdmin(); + doGet("/api/entityGroup/" + otherTenantGroup.getId().getId()) + .andExpect(status().isNotFound()) + .andExpect(statusReason(not(containsString(otherTenantGroup.getName())))); + } + + @Test + public void testShouldNotUpdateNonExistingEntityGroup() throws Exception { + loginTenantAdmin(); + EntityGroup entityGroup = new EntityGroup(); + entityGroup.setId(new EntityGroupId(UUID.randomUUID())); + entityGroup.setName("Non-existing Device Group"); + entityGroup.setType(EntityType.DEVICE); + entityGroup.setOwnerId(tenantId); + doPost("/api/entityGroup", entityGroup) + .andExpect(status().isNotFound()); + } + @Test public void testSaveEntityGroupWithSameName() throws Exception { EntityGroup entityGroup = new EntityGroup(); @@ -314,4 +627,164 @@ 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()); + } + + private List findSharedUserGroupIds(EntityGroup entityGroup) { + return groupPermissionService.findGroupPermissionByTenantIdAndEntityGroupId(tenantId, entityGroup.getId(), new PageLink(100)) + .getData().stream().map(GroupPermission::getUserGroupId).collect(Collectors.toList()); + } + } diff --git a/application/src/test/java/org/thingsboard/server/controller/EntityViewControllerTest.java b/application/src/test/java/org/thingsboard/server/controller/EntityViewControllerTest.java index 12561a35d2..48c508f43f 100644 --- a/application/src/test/java/org/thingsboard/server/controller/EntityViewControllerTest.java +++ b/application/src/test/java/org/thingsboard/server/controller/EntityViewControllerTest.java @@ -353,6 +353,94 @@ public class EntityViewControllerTest extends AbstractControllerTest { deleteDifferentTenant(); } + @Test + public void testSaveEntityViewWithEntityOfOtherTenant() throws Exception { + loginDifferentTenant(); + + String name = "Entity view of other tenant device"; + EntityView entityView = createEntityView(name, 0, 0); + doPost("/api/entityView", entityView) + .andExpect(status().is4xxClientError()); + + doGet("/api/tenant/entityViews?entityViewName=" + name) + .andExpect(status().isNotFound()); + + deleteDifferentTenant(); + } + + @Test + public void testUpdateEntityViewByCustomerUserToEntityNotAssignedToCustomer() throws Exception { + EntityView savedView = getNewSavedEntityView("Customer entity view"); + doPost("/api/owner/CUSTOMER/" + customerId.getId() + "/ENTITY_VIEW/" + savedView.getId().getId()).andExpect(status().isOk()); + doPost("/api/owner/CUSTOMER/" + customerId.getId() + "/DEVICE/" + testDevice.getId().getId()).andExpect(status().isOk()); + + Device otherDevice = new Device(); + otherDevice.setName("Device not assigned to customer"); + otherDevice.setType("default"); + otherDevice = doPost("/api/device", otherDevice, Device.class); + + loginCustomerAdminUser(); + + EntityView customerView = doGet("/api/entityView/" + savedView.getId().getId(), EntityView.class); + customerView.setEntityId(otherDevice.getId()); + doPost("/api/entityView", customerView) + .andExpect(status().isForbidden()); + + EntityView foundView = doGet("/api/entityView/" + savedView.getId().getId(), EntityView.class); + assertEquals(testDevice.getId(), foundView.getEntityId()); + } + + @Test + public void testUpdateEntityViewByCustomerUserKeepingEntity() throws Exception { + EntityView savedView = getNewSavedEntityView("Customer entity view"); + doPost("/api/owner/CUSTOMER/" + customerId.getId() + "/ENTITY_VIEW/" + savedView.getId().getId()).andExpect(status().isOk()); + + loginCustomerAdminUser(); + + EntityView customerView = doGet("/api/entityView/" + savedView.getId().getId(), EntityView.class); + customerView.setName("Customer entity view renamed"); + EntityView updatedView = doPost("/api/entityView", customerView, EntityView.class); + + assertEquals("Customer entity view renamed", updatedView.getName()); + assertEquals(testDevice.getId(), updatedView.getEntityId()); + } + + @Test + public void testUpdateEntityViewKeysByCustomerUserWithEntityNotAssignedToCustomer() throws Exception { + EntityView savedView = getNewSavedEntityView("Customer entity view"); + doPost("/api/owner/CUSTOMER/" + customerId.getId() + "/ENTITY_VIEW/" + savedView.getId().getId()).andExpect(status().isOk()); + + loginCustomerAdminUser(); + + EntityView customerView = doGet("/api/entityView/" + savedView.getId().getId(), EntityView.class); + customerView.setKeys(new TelemetryEntityView(List.of("tsKey1"), new AttributesEntityView())); + doPost("/api/entityView", customerView) + .andExpect(status().isForbidden()); + + customerView = doGet("/api/entityView/" + savedView.getId().getId(), EntityView.class); + customerView.setStartTimeMs(1L); + doPost("/api/entityView", customerView) + .andExpect(status().isForbidden()); + + EntityView foundView = doGet("/api/entityView/" + savedView.getId().getId(), EntityView.class); + assertEquals(telemetry, foundView.getKeys()); + assertEquals(0L, foundView.getStartTimeMs()); + } + + @Test + public void testFindEntityViewByOldNameAfterRename() throws Exception { + String oldName = "Entity view old name"; + EntityView savedView = getNewSavedEntityView(oldName); + doGet("/api/tenant/entityViews?entityViewName=" + oldName) + .andExpect(status().isOk()); + + savedView.setName("Entity view new name"); + doPost("/api/entityView", savedView, EntityView.class); + + doGet("/api/tenant/entityViews?entityViewName=" + oldName) + .andExpect(status().isNotFound()); + } + @Test public void testDeleteEntityView() throws Exception { Customer customer = doPost("/api/customer", getNewCustomer("My customer"), Customer.class); @@ -380,6 +468,7 @@ public class EntityViewControllerTest extends AbstractControllerTest { public void testSaveEntityViewWithEmptyName() throws Exception { EntityView entityView = new EntityView(); entityView.setType("default"); + entityView.setEntityId(testDevice.getId()); Mockito.reset(tbClusterService, auditLogService); 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 44bf41b0ef..dd16575a86 100644 --- a/application/src/test/java/org/thingsboard/server/controller/GroupPermissionControllerTest.java +++ b/application/src/test/java/org/thingsboard/server/controller/GroupPermissionControllerTest.java @@ -8,18 +8,22 @@ 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.thingsboard.server.common.data.Customer; import org.thingsboard.server.common.data.EntityType; 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,222 @@ public class GroupPermissionControllerTest extends AbstractControllerTest { checkPermissionOwners(loadedGroupPermissionsInfo, List.of(subCustomerId)); } + @Test + public void testLoadUserGroupPermissionInfosReturnsOnlyOwnTenantData() throws Exception { + loginDifferentTenant(); + Role otherTenantRole = doPost("/api/role", newRole("Other Tenant Role", RoleType.GROUP), Role.class); + EntityGroup otherTenantGroup = new EntityGroup(); + otherTenantGroup.setType(EntityType.DEVICE); + otherTenantGroup.setName("Other Tenant Device Group"); + otherTenantGroup = doPost("/api/entityGroup", otherTenantGroup, EntityGroup.class); + + loginTenantAdmin(); + Role ownRole = doPost("/api/role", newRole("Own Role", RoleType.GROUP), Role.class); + + GroupPermission otherTenantRolePermission = new GroupPermission(); + otherTenantRolePermission.setRoleId(otherTenantRole.getId()); + GroupPermission otherTenantGroupPermission = new GroupPermission(); + otherTenantGroupPermission.setRoleId(ownRole.getId()); + otherTenantGroupPermission.setEntityGroupId(otherTenantGroup.getId()); + + List infos = doPostWithTypedResponse("/api/userGroup/groupPermissions/info", + List.of(otherTenantRolePermission, otherTenantGroupPermission), new TypeReference<>() {}); + assertThat(infos).isEmpty(); + } + + @Test + public void testLoadUserGroupPermissionInfosReturnsOnlyReadableGroups() throws Exception { + loginTenantAdmin(); + Role role = doPost("/api/role", newRole("Group Role", RoleType.GROUP), Role.class); + EntityGroup tenantGroup = new EntityGroup(); + tenantGroup.setType(EntityType.DEVICE); + tenantGroup.setName("Tenant Device Group"); + tenantGroup = doPost("/api/entityGroup", tenantGroup, EntityGroup.class); + + loginCustomerAdminUser(); + EntityGroup customerGroup = new EntityGroup(); + customerGroup.setType(EntityType.DEVICE); + customerGroup.setName("Customer Device Group"); + customerGroup.setOwnerId(customerId); + customerGroup = doPost("/api/entityGroup", customerGroup, EntityGroup.class); + + GroupPermission tenantGroupPermission = new GroupPermission(); + tenantGroupPermission.setRoleId(role.getId()); + tenantGroupPermission.setEntityGroupId(tenantGroup.getId()); + GroupPermission customerGroupPermission = new GroupPermission(); + customerGroupPermission.setRoleId(role.getId()); + customerGroupPermission.setEntityGroupId(customerGroup.getId()); + + List infos = doPostWithTypedResponse("/api/userGroup/groupPermissions/info", + List.of(tenantGroupPermission, customerGroupPermission), new TypeReference<>() {}); + assertThat(infos).extracting(GroupPermissionInfo::getEntityGroupId).containsExactly(customerGroup.getId()); + } + + @Test + public void testLoadUserGroupPermissionInfosKeepsSystemRoles() throws Exception { + loginTenantAdmin(); + EntityGroup tenantAdminsGroup = findGroupByOwnerIdTypeAndName(tenantId, EntityType.USER, EntityGroup.GROUP_TENANT_ADMINS_NAME); + List storedInfos = doGetTyped("/api/userGroup/" + tenantAdminsGroup.getId() + "/groupPermissions", + new TypeReference<>() {}); + assertThat(storedInfos).isNotEmpty(); + assertThat(storedInfos).allSatisfy(info -> assertThat(info.getRole().getTenantId().isSysTenantId()).isTrue()); + + List permissions = storedInfos.stream().map(GroupPermission::new).toList(); + List infos = doPostWithTypedResponse("/api/userGroup/groupPermissions/info", permissions, new TypeReference<>() {}); + assertThat(infos).hasSameSizeAs(permissions); + assertThat(infos).allSatisfy(info -> assertThat(info.getRole()).isNotNull()); + } + + @Test + public void testShareGroupWithRoleOfOtherTenantIsRejected() throws Exception { + loginDifferentTenant(); + Role otherTenantRole = doPost("/api/role", newRole("Other Tenant Role", RoleType.GROUP), Role.class); + + loginTenantAdmin(); + EntityGroup deviceGroup = new EntityGroup(); + deviceGroup.setType(EntityType.DEVICE); + deviceGroup.setName("Shared Device Group"); + deviceGroup = doPost("/api/entityGroup", deviceGroup, EntityGroup.class); + + ShareGroupRequest shareGroupRequest = new ShareGroupRequest(tenantId, true, null, false, List.of(otherTenantRole.getId())); + doPost("/api/entityGroup/{entityGroupId}/share", shareGroupRequest, deviceGroup.getId().toString()) + .andExpect(status().isForbidden()); + + assertThat(groupPermissionService.findGroupPermissionByTenantIdAndRoleId(tenantId, otherTenantRole.getId(), new PageLink(10)).getData()).isEmpty(); + } + + private Role newRole(String roleName, RoleType roleType) { + Role role = new Role(); + role.setName(roleName); + role.setType(roleType); + return role; + } + + @Test + public void testCustomerAdminCannotUpdateTenantGroupPermission() throws Exception { + loginTenantAdmin(); + EntityGroup tenantUserGroup = saveUserGroup("Tenant users"); + Role tenantRole = doPost("/api/role", createRole("Tenant role", RoleType.GENERIC), Role.class); + GroupPermission groupPermission = new GroupPermission(); + groupPermission.setRoleId(tenantRole.getId()); + groupPermission.setUserGroupId(tenantUserGroup.getId()); + groupPermission = doPost("/api/groupPermission", groupPermission, GroupPermission.class); + + loginCustomerAdminUser(); + Role customerRole = doPost("/api/role", createRole("Customer role", RoleType.GENERIC), Role.class); + GroupPermission update = new GroupPermission(groupPermission); + update.setUserGroupId(findCustomerAdminsGroup(customerId).getId()); + update.setRoleId(customerRole.getId()); + doPost("/api/groupPermission", update).andExpect(status().isForbidden()); + + loginTenantAdmin(); + GroupPermission stored = doGet("/api/groupPermission/" + groupPermission.getUuidId(), GroupPermission.class); + assertEquals(tenantUserGroup.getId(), stored.getUserGroupId()); + assertEquals(tenantRole.getId(), stored.getRoleId()); + } + + @Test + public void testCustomerAdminCannotMoveGroupPermissionFromTenantUserGroup() throws Exception { + loginCustomerAdminUser(); + Role customerRole = doPost("/api/role", createRole("Customer role", RoleType.GENERIC), Role.class); + EntityGroup customerUserGroup = saveUserGroup("Customer users"); + + loginTenantAdmin(); + EntityGroup tenantUserGroup = saveUserGroup("Tenant users"); + GroupPermission groupPermission = new GroupPermission(); + groupPermission.setRoleId(customerRole.getId()); + groupPermission.setUserGroupId(tenantUserGroup.getId()); + groupPermission = doPost("/api/groupPermission", groupPermission, GroupPermission.class); + + loginCustomerAdminUser(); + GroupPermission update = new GroupPermission(groupPermission); + update.setUserGroupId(customerUserGroup.getId()); + doPost("/api/groupPermission", update).andExpect(status().isForbidden()); + + loginTenantAdmin(); + GroupPermission stored = doGet("/api/groupPermission/" + groupPermission.getUuidId(), GroupPermission.class); + assertEquals(tenantUserGroup.getId(), stored.getUserGroupId()); + } + + @Test + public void testCustomerAdminCannotUpdateGroupPermissionOfTenantEntityGroup() throws Exception { + loginCustomerAdminUser(); + Role customerRole = doPost("/api/role", createRole("Customer group role", RoleType.GROUP), Role.class); + EntityGroup customerUserGroup = saveUserGroup("Customer users"); + EntityGroup customerDeviceGroup = saveDeviceGroup("Customer devices"); + + loginTenantAdmin(); + EntityGroup tenantDeviceGroup = saveDeviceGroup("Tenant devices"); + GroupPermission groupPermission = new GroupPermission(); + groupPermission.setRoleId(customerRole.getId()); + groupPermission.setUserGroupId(customerUserGroup.getId()); + groupPermission.setEntityGroupId(tenantDeviceGroup.getId()); + groupPermission = doPost("/api/groupPermission", groupPermission, GroupPermission.class); + + loginCustomerAdminUser(); + GroupPermission update = new GroupPermission(groupPermission); + update.setEntityGroupId(customerDeviceGroup.getId()); + doPost("/api/groupPermission", update).andExpect(status().isForbidden()); + + loginTenantAdmin(); + GroupPermission stored = doGet("/api/groupPermission/" + groupPermission.getUuidId(), GroupPermission.class); + assertEquals(tenantDeviceGroup.getId(), stored.getEntityGroupId()); + } + + @Test + public void testPublicGroupPermissionIsNotUpdatable() throws Exception { + loginTenantAdmin(); + EntityGroup deviceGroup = saveDeviceGroup("Public devices"); + doPost("/api/entityGroup/" + deviceGroup.getUuidId() + "/makePublic").andExpect(status().isOk()); + List permissions = doGetTyped("/api/entityGroup/" + deviceGroup.getUuidId() + "/groupPermissions", + new TypeReference<>() {}); + assertEquals(1, permissions.size()); + GroupPermission publicPermission = doGet("/api/groupPermission/" + permissions.get(0).getUuidId(), GroupPermission.class); + assertTrue(publicPermission.isPublic()); + + EntityGroup userGroup = saveUserGroup("Other users"); + GroupPermission update = new GroupPermission(publicPermission); + update.setPublic(false); + update.setUserGroupId(userGroup.getId()); + doPost("/api/groupPermission", update).andExpect(status().isForbidden()); + + GroupPermission stored = doGet("/api/groupPermission/" + publicPermission.getUuidId(), GroupPermission.class); + assertTrue(stored.isPublic()); + assertEquals(publicPermission.getUserGroupId(), stored.getUserGroupId()); + } + + @Test + public void testCustomerAdminUpdatesOwnGroupPermission() throws Exception { + loginCustomerAdminUser(); + EntityGroup firstUserGroup = saveUserGroup("First customer users"); + EntityGroup secondUserGroup = saveUserGroup("Second customer users"); + Role role = doPost("/api/role", createRole("Customer role", RoleType.GENERIC), Role.class); + GroupPermission groupPermission = new GroupPermission(); + groupPermission.setRoleId(role.getId()); + groupPermission.setUserGroupId(firstUserGroup.getId()); + groupPermission = doPost("/api/groupPermission", groupPermission, GroupPermission.class); + + groupPermission.setUserGroupId(secondUserGroup.getId()); + doPost("/api/groupPermission", groupPermission).andExpect(status().isOk()); + + GroupPermission stored = doGet("/api/groupPermission/" + groupPermission.getUuidId(), GroupPermission.class); + assertEquals(secondUserGroup.getId(), stored.getUserGroupId()); + } + + private EntityGroup saveUserGroup(String name) throws Exception { + EntityGroup userGroup = new EntityGroup(); + userGroup.setType(EntityType.USER); + userGroup.setName(name); + return doPost("/api/entityGroup", userGroup, EntityGroup.class); + } + + private EntityGroup saveDeviceGroup(String name) throws Exception { + EntityGroup deviceGroup = new EntityGroup(); + deviceGroup.setType(EntityType.DEVICE); + deviceGroup.setName(name); + return doPost("/api/entityGroup", deviceGroup, EntityGroup.class); + } + 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/ReportControllerTest.java b/application/src/test/java/org/thingsboard/server/controller/ReportControllerTest.java index c5f9695396..1de79b3f5d 100644 --- a/application/src/test/java/org/thingsboard/server/controller/ReportControllerTest.java +++ b/application/src/test/java/org/thingsboard/server/controller/ReportControllerTest.java @@ -25,6 +25,7 @@ import org.thingsboard.server.common.data.alarm.Alarm; import org.thingsboard.server.common.data.alarm.AlarmSeverity; import org.thingsboard.server.common.data.asset.Asset; import org.thingsboard.server.common.data.id.ReportTemplateId; +import org.thingsboard.server.common.data.id.UserId; import org.thingsboard.server.common.data.job.Job; import org.thingsboard.server.common.data.job.JobStatus; import org.thingsboard.server.common.data.job.JobType; @@ -101,6 +102,8 @@ import java.util.stream.Collectors; import static org.assertj.core.api.Assertions.assertThat; import static org.awaitility.Awaitility.await; import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; @@ -826,6 +829,35 @@ public class ReportControllerTest extends AbstractControllerTest { doPost("/api/v2/report/test", request).andExpect(status().isOk()); } + @Test + public void testTestReportRequiresPermissionOverReportUser() throws Exception { + loginDifferentTenant(); + UserId otherTenantUserId = savedDifferentTenantUser.getId(); + loginTenantAdmin(); + + ReportRequest request = new ReportRequest(); + request.setReportTemplateConfig(buildReportTemplate(TbReportFormat.CSV).getConfiguration()); + request.setUserId(otherTenantUserId.toString()); + doPost("/api/v2/report/test", request).andExpect(status().isForbidden()); + + verify(tbReportService, never()).generateTestReport(any()); + } + + @Test + public void testRequestReportRequiresPermissionOverReportUser() throws Exception { + loginDifferentTenant(); + UserId otherTenantUserId = savedDifferentTenantUser.getId(); + loginTenantAdmin(); + + ReportTemplate reportTemplate = doPost("/api/reportTemplate", buildReportTemplate(TbReportFormat.CSV), ReportTemplate.class); + ReportRequest request = new ReportRequest(); + request.setReportTemplateId(reportTemplate.getId()); + request.setUserId(otherTenantUserId.toString()); + doPost("/api/v2/report/request", request).andExpect(status().isForbidden()); + + assertThat(findJobs(List.of(JobType.REPORT), List.of(reportTemplate.getId().getId()))).isEmpty(); + } + private TimeseriesTableComponent buildTimeseriesTableComponent(String devicesAliasId) { return buildTimeseriesTableComponent(devicesAliasId, buildCurrentDateTimeWindow()); } diff --git a/application/src/test/java/org/thingsboard/server/controller/RuleEngineControllerTest.java b/application/src/test/java/org/thingsboard/server/controller/RuleEngineControllerTest.java index c468f3fd55..273b7b9910 100644 --- a/application/src/test/java/org/thingsboard/server/controller/RuleEngineControllerTest.java +++ b/application/src/test/java/org/thingsboard/server/controller/RuleEngineControllerTest.java @@ -16,6 +16,7 @@ import org.thingsboard.server.common.data.id.CustomerId; import org.thingsboard.server.common.data.id.DeviceId; import org.thingsboard.server.common.data.id.EntityId; import org.thingsboard.server.common.data.id.TenantId; +import org.thingsboard.server.common.data.id.UserId; import org.thingsboard.server.common.data.msg.TbMsgType; import org.thingsboard.server.common.msg.TbMsg; import org.thingsboard.server.common.msg.TbMsgMetaData; @@ -242,6 +243,32 @@ public class RuleEngineControllerTest extends AbstractControllerTest { verifyNoInteractions(ruleEngineCallService); } + @Test + public void testHandleRuleEngineRequestRequiresPermissionOverReportUser() throws Exception { + loginCustomerAdminUser(); + + doPost("/api/rule-engine/", (Object) reportRequestBody(tenantAdminUserId)) + .andExpect(status().isForbidden()); + doPost("/api/rule-engine/", (Object) reportConfigRequestBody(tenantAdminUserId)) + .andExpect(status().isForbidden()); + verifyNoInteractions(ruleEngineCallService); + + TbMsg responseMsg = TbMsg.newMsg() + .type(TbMsgType.REST_API_REQUEST) + .originator(customerAdminUserId) + .copyMetaData(TbMsgMetaData.EMPTY) + .data(RESPONSE_BODY) + .build(); + mockRestApiCallToRuleEngine(responseMsg); + + String ownReportRequestBody = reportRequestBody(customerAdminUserId); + doPostAsyncWithTypedResponse("/api/rule-engine/", ownReportRequestBody, new TypeReference() { + }, status().isOk()); + ArgumentCaptor requestMsgCaptor = ArgumentCaptor.forClass(TbMsg.class); + verify(ruleEngineCallService).processRestApiCallToRuleEngine(eq(tenantId), any(UUID.class), requestMsgCaptor.capture(), eq(false), any(Consumer.class)); + assertThat(requestMsgCaptor.getValue().getData()).isEqualTo(ownReportRequestBody); + } + @Test public void testHandleRuleEngineRequestUnauthorized() throws Exception { doPost("/api/rule-engine/", (Object) REQUEST_BODY) @@ -249,6 +276,14 @@ public class RuleEngineControllerTest extends AbstractControllerTest { .andExpect(statusReason(containsString("Authentication failed"))); } + private String reportRequestBody(UserId userId) { + return "{\"reportConfig\":{\"userId\":\"" + userId.getId() + "\"}}"; + } + + private String reportConfigRequestBody(UserId userId) { + return "{\"userId\":{\"id\":\"" + userId.getId() + "\"}}"; + } + private void mockRestApiCallToRuleEngine(TbMsg responseMsg) { doAnswer(invocation -> { Consumer consumer = invocation.getArgument(4); diff --git a/application/src/test/java/org/thingsboard/server/controller/SchedulerEventControllerTest.java b/application/src/test/java/org/thingsboard/server/controller/SchedulerEventControllerTest.java index 00c25ef349..4d52fd804d 100644 --- a/application/src/test/java/org/thingsboard/server/controller/SchedulerEventControllerTest.java +++ b/application/src/test/java/org/thingsboard/server/controller/SchedulerEventControllerTest.java @@ -276,6 +276,48 @@ public class SchedulerEventControllerTest extends AbstractControllerTest { assertThat(reportInfos.getData()).hasSize(0); } + @Test + public void testSaveReportEventRequiresPermissionOverReportUser() throws Exception { + ReportTemplate template = doPost("/api/reportTemplate", buildTemplate("CSV report template", ReportTemplateType.REPORT, TbReportFormat.CSV), ReportTemplate.class); + + loginCustomerAdminUser(); + doPost("/api/schedulerEvent", createReportSchedulerEvent(template.getId(), tenantAdminUserId)).andExpect(status().isForbidden()); + doPost("/api/schedulerEvent", createDashboardReportSchedulerEvent(tenantAdminUserId)).andExpect(status().isForbidden()); + doPost("/api/schedulerEvent", createReportConfigMsgSchedulerEvent(tenantAdminUserId)).andExpect(status().isForbidden()); + assertThat(findSchedulerEvents(null, null)).isEmpty(); + + SchedulerEvent reportEvent = createReportSchedulerEvent(template.getId(), customerAdminUserId); + ((ObjectNode) reportEvent.getSchedule()).put("startTime", System.currentTimeMillis() + TimeUnit.DAYS.toMillis(1)); + assertThat(saveSchedulerEvent(reportEvent).getId()).isNotNull(); + assertThat(saveSchedulerEvent(createDashboardReportSchedulerEvent(customerAdminUserId)).getId()).isNotNull(); + + loginTenantAdmin(); + assertThat(saveSchedulerEvent(createDashboardReportSchedulerEvent(customerUserId)).getId()).isNotNull(); + } + + @Test + public void testSaveDashboardReportEventWithCurrentUserCredentialsUsesSaverWhenReportUserNotAccessible() throws Exception { + loginCustomerAdminUser(); + SchedulerEvent saved = saveSchedulerEvent(createDashboardReportSchedulerEvent(tenantAdminUserId, true)); + assertThat(saved.getConfiguration().get("msgBody").get("reportConfig").get("userId").asText()).isEqualTo(customerAdminUserId.toString()); + } + + @Test + public void testSaveDashboardReportEventWithCurrentUserCredentialsKeepsAccessibleReportUser() throws Exception { + SchedulerEvent saved = saveSchedulerEvent(createDashboardReportSchedulerEvent(customerAdminUserId, true)); + assertThat(saved.getConfiguration().get("msgBody").get("reportConfig").get("userId").asText()).isEqualTo(customerAdminUserId.toString()); + } + + @Test + public void testSaveReportEventRequiresReportUser() throws Exception { + ReportTemplate template = doPost("/api/reportTemplate", buildTemplate("CSV report template", ReportTemplateType.REPORT, TbReportFormat.CSV), ReportTemplate.class); + doPost("/api/schedulerEvent", createReportSchedulerEvent(template.getId(), null)).andExpect(status().isBadRequest()); + + SchedulerEvent noConfigurationEvent = createReportSchedulerEvent(template.getId(), tenantAdminUserId); + noConfigurationEvent.setConfiguration(null); + doPost("/api/schedulerEvent", noConfigurationEvent).andExpect(status().isBadRequest()); + } + private ReportTemplate buildTemplate(String templateName, ReportTemplateType report, TbReportFormat format) { ReportTemplate template = new ReportTemplate(); template.setName(templateName); @@ -310,6 +352,39 @@ public class SchedulerEventControllerTest extends AbstractControllerTest { return schedulerEvent; } + private SchedulerEvent createDashboardReportSchedulerEvent(UserId userId) { + return createDashboardReportSchedulerEvent(userId, false); + } + + private SchedulerEvent createDashboardReportSchedulerEvent(UserId userId, boolean useCurrentUserCredentials) { + SchedulerEvent schedulerEvent = createSchedulerEvent(); + schedulerEvent.setType("generateDashboardReport"); + ObjectNode reportConfig = JacksonUtil.newObjectNode(); + reportConfig.put("namePattern", "report-%d{yyyy-MM-dd_HH:mm:ss}"); + reportConfig.put("type", "pdf"); + reportConfig.put("useCurrentUserCredentials", useCurrentUserCredentials); + reportConfig.put("userId", userId.toString()); + ObjectNode msgBody = JacksonUtil.newObjectNode(); + msgBody.set("reportConfig", reportConfig); + msgBody.put("sendEmail", false); + ObjectNode configuration = JacksonUtil.newObjectNode(); + configuration.put("msgType", "generateDashboardReport"); + configuration.set("msgBody", msgBody); + schedulerEvent.setConfiguration(configuration); + return schedulerEvent; + } + + private SchedulerEvent createReportConfigMsgSchedulerEvent(UserId userId) { + SchedulerEvent schedulerEvent = createSchedulerEvent(); + ObjectNode msgBody = JacksonUtil.newObjectNode(); + msgBody.set("userId", JacksonUtil.valueToTree(userId)); + ObjectNode configuration = JacksonUtil.newObjectNode(); + configuration.put("msgType", "Custom Msg"); + configuration.set("msgBody", msgBody); + schedulerEvent.setConfiguration(configuration); + return schedulerEvent; + } + private SchedulerEvent saveSchedulerEvent(SchedulerEvent schedulerEvent) { return doPost("/api/schedulerEvent", schedulerEvent, SchedulerEvent.class); } 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 6b524855a8..333f291b66 100644 --- a/application/src/test/java/org/thingsboard/server/controller/SignUpControllerSqlTest.java +++ b/application/src/test/java/org/thingsboard/server/controller/SignUpControllerSqlTest.java @@ -4,16 +4,20 @@ package org.thingsboard.server.controller; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.node.ObjectNode; import org.apache.commons.lang3.RandomStringUtils; import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.mockito.ArgumentCaptor; +import org.mockito.Mockito; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.test.context.bean.override.mockito.MockitoSpyBean; +import org.thingsboard.common.util.JacksonUtil; +import org.thingsboard.server.common.data.AdminSettings; import org.thingsboard.server.common.data.Customer; import org.thingsboard.server.common.data.CustomerInfo; import org.thingsboard.server.common.data.Dashboard; @@ -26,6 +30,7 @@ import org.thingsboard.server.common.data.audit.ActionType; import org.thingsboard.server.common.data.domain.Domain; import org.thingsboard.server.common.data.group.EntityGroup; import org.thingsboard.server.common.data.id.DashboardId; +import org.thingsboard.server.common.data.id.TenantId; import org.thingsboard.server.common.data.menu.CMAssigneeType; import org.thingsboard.server.common.data.menu.CMScope; import org.thingsboard.server.common.data.menu.CustomMenu; @@ -37,6 +42,12 @@ 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.permission.GroupPermissionInfo; +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; import org.thingsboard.server.common.data.selfregistration.HomeDashboardParams; import org.thingsboard.server.common.data.selfregistration.MobileRedirectParams; @@ -47,8 +58,10 @@ import org.thingsboard.server.common.data.selfregistration.V2CaptchaParams; import org.thingsboard.server.common.data.selfregistration.WebSelfRegistrationParams; import org.thingsboard.server.common.data.signup.SignUpRequest; import org.thingsboard.server.common.data.signup.SignUpResult; +import org.thingsboard.server.common.data.wl.WhiteLabelingType; import org.thingsboard.server.dao.customer.CustomerService; import org.thingsboard.server.dao.group.EntityGroupService; +import org.thingsboard.server.dao.grouppermission.GroupPermissionService; import org.thingsboard.server.dao.menu.CustomMenuDao; import org.thingsboard.server.dao.service.DaoSqlTest; import org.thingsboard.server.dao.settings.AdminSettingsService; @@ -57,6 +70,7 @@ import org.thingsboard.server.dao.user.UserService; import org.thingsboard.server.dao.wl.WhiteLabelingService; import org.thingsboard.server.service.entitiy.TbLogEntityActionService; +import java.net.URI; import java.util.ArrayList; import java.util.Collections; import java.util.List; @@ -68,10 +82,14 @@ import java.util.concurrent.TimeUnit; import static org.assertj.core.api.Assertions.assertThat; import static org.awaitility.Awaitility.await; import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyLong; +import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.ArgumentMatchers.argThat; import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.never; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.header; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; @@ -87,6 +105,8 @@ public class SignUpControllerSqlTest extends AbstractControllerTest { public static final String CUSTOMER_TEST_EMAIL = "signup-customer@thingsboard.org"; public static final String CUSTOMER_TITLE_PREFIX = "Prefix-"; + public static final String CONFIGURED_BASE_URL = "https://configured.example.com"; + public static final String OTHER_HOST = "other.example.com"; private static List idsToRemove = new ArrayList<>(); private EntityGroup customerGroup; @@ -116,6 +136,9 @@ public class SignUpControllerSqlTest extends AbstractControllerTest { @Autowired protected WhiteLabelingService whiteLabelingService; + @Autowired + private GroupPermissionService groupPermissionService; + @Before public void beforeTest() throws Exception { loginTenantAdmin(); @@ -167,6 +190,41 @@ public class SignUpControllerSqlTest extends AbstractControllerTest { removeCreatedUser(user); } + @Test + public void testSelfRegisterUserCreatesNewGroupPermissions() throws Exception { + EntityGroup userGroup = new EntityGroup(); + userGroup.setType(EntityType.USER); + userGroup.setName("Existing permission users"); + userGroup = doPost("/api/entityGroup", userGroup, EntityGroup.class); + Role role = new Role(); + role.setName("Existing permission role"); + role.setType(RoleType.GENERIC); + role = doPost("/api/role", role, Role.class); + GroupPermission existingPermission = new GroupPermission(); + existingPermission.setUserGroupId(userGroup.getId()); + existingPermission.setRoleId(role.getId()); + existingPermission = doPost("/api/groupPermission", existingPermission, GroupPermission.class); + + GroupPermission selfRegistrationPermission = new GroupPermission(existingPermission); + createWebSelfRegistrationSettings(List.of(selfRegistrationPermission)); + String email = "signup-permissions@thingsboard.org"; + doSignUp(createWebSignUpRequest(email)); + + GroupPermission storedPermission = doGet("/api/groupPermission/" + existingPermission.getUuidId(), GroupPermission.class); + assertThat(storedPermission.getUserGroupId()).isEqualTo(userGroup.getId()); + + User user = userService.findUserByEmail(tenantId, email); + EntityGroup selfRegistrationGroup = entityGroupService.findEntityGroupByTypeAndName(tenantId, user.getCustomerId(), EntityType.USER, + "Self Registration Users").orElseThrow(); + List selfRegistrationPermissions = doGetTyped("/api/userGroup/" + selfRegistrationGroup.getUuidId() + "/groupPermissions", + new TypeReference<>() {}); + assertThat(selfRegistrationPermissions).hasSize(1); + assertThat(selfRegistrationPermissions.get(0).getId()).isNotEqualTo(existingPermission.getId()); + assertThat(selfRegistrationPermissions.get(0).getRoleId()).isEqualTo(role.getId()); + + removeCreatedUser(user); + } + @Test public void testSelfRegisterUserFromMobileApp() throws Exception { String appSecret = StringUtils.randomAlphanumeric(24); @@ -320,6 +378,223 @@ 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(); + doSignUp(createWebSignUpRequest(CUSTOMER_TEST_EMAIL)); + + Mockito.clearInvocations(mailService); + doPost("/api/noauth/resendEmailActivation?email=" + CUSTOMER_TEST_EMAIL).andExpect(status().isOk()); + + verify(mailService, times(1)).sendActivationEmail(eq(tenantId), anyString(), anyLong(), eq(CUSTOMER_TEST_EMAIL)); + + removeCreatedUser(userService.findUserByEmail(tenantId, CUSTOMER_TEST_EMAIL)); + } + + @Test + public void testResendEmailActivationSendsNothingForUserOfOtherTenant() throws Exception { + createWebSelfRegistrationSettings(); + createDifferentTenant(); + + User otherUser = new User(); + otherUser.setAuthority(Authority.TENANT_ADMIN); + otherUser.setTenantId(differentTenantId); + otherUser.setEmail("other.tenant.user@thingsboard.org"); + otherUser = doPost("/api/user?sendActivationMail=false", otherUser, User.class); + + UserCredentials credentials = userService.findUserCredentialsByUserId(differentTenantId, otherUser.getId()); + credentials.setPassword("abcdef123"); + credentials = userService.saveUserCredentials(differentTenantId, credentials); + + Mockito.clearInvocations(mailService); + doPost("/api/noauth/resendEmailActivation?email=" + otherUser.getEmail()).andExpect(status().isBadRequest()); + + verify(mailService, never()).sendActivationEmail(any(), anyString(), anyLong(), anyString()); + UserCredentials credentialsAfter = userService.findUserCredentialsByUserId(differentTenantId, otherUser.getId()); + assertThat(credentialsAfter.getActivateToken()).isEqualTo(credentials.getActivateToken()); + assertThat(credentialsAfter.getActivateTokenExpTime()).isEqualTo(credentials.getActivateTokenExpTime()); + + deleteDifferentTenant(); + } + + @Test + public void testResendEmailActivationSendsNothingForDisabledActivatedUser() throws Exception { + createWebSelfRegistrationSettings(); + doSignUp(createWebSignUpRequest(CUSTOMER_TEST_EMAIL)); + + User user = userService.findUserByEmail(tenantId, CUSTOMER_TEST_EMAIL); + UserCredentials credentials = userService.findUserCredentialsByUserId(tenantId, user.getId()); + userService.activateUserCredentials(tenantId, credentials.getActivateToken(), credentials.getPassword()); + userService.setUserCredentialsEnabled(tenantId, user.getId(), false); + + Mockito.clearInvocations(mailService); + doPost("/api/noauth/resendEmailActivation?email=" + CUSTOMER_TEST_EMAIL).andExpect(status().isBadRequest()); + + verify(mailService, never()).sendActivationEmail(any(), anyString(), anyLong(), anyString()); + assertThat(userService.findUserCredentialsByUserId(tenantId, user.getId()).getActivateToken()).isNull(); + + removeCreatedUser(user); + } + + @Test + public void testActivationEmailLinkUsesConfiguredBaseUrl() throws Exception { + createWebSelfRegistrationSettings(); + AdminSettings generalSettings = setGeneralBaseUrl(CONFIGURED_BASE_URL); + try { + Mockito.clearInvocations(mailService); + doSignUp(createWebSignUpRequest(CUSTOMER_TEST_EMAIL)); + + assertThat(captureActivationLink()).startsWith(CONFIGURED_BASE_URL + "/api/noauth/activateEmail?emailCode="); + } finally { + adminSettingsService.saveAdminSettings(TenantId.SYS_TENANT_ID, generalSettings); + } + removeCreatedUser(userService.findUserByEmail(tenantId, CUSTOMER_TEST_EMAIL)); + } + + @Test + public void testActivationEmailLinkUsesRequestBaseUrlWhenGeneralBaseUrlIsMissing() throws Exception { + createWebSelfRegistrationSettings(); + AdminSettings generalSettings = setGeneralBaseUrl(null); + try { + Mockito.clearInvocations(mailService); + doSignUp(createWebSignUpRequest(CUSTOMER_TEST_EMAIL)); + + assertThat(captureActivationLink()).startsWith("http://localhost:80/api/noauth/activateEmail?emailCode="); + } finally { + adminSettingsService.saveAdminSettings(TenantId.SYS_TENANT_ID, generalSettings); + } + removeCreatedUser(userService.findUserByEmail(tenantId, CUSTOMER_TEST_EMAIL)); + } + + @Test + public void testResendActivationEmailLinkUsesConfiguredBaseUrl() throws Exception { + String appSecret = StringUtils.randomAlphanumeric(24); + String mobilePkgName = "my.test.android.app"; + createMobileSelfRegistrationSettings(mobilePkgName, appSecret, PlatformType.ANDROID, createDashboard(), createDashboard()); + AdminSettings generalSettings = setGeneralBaseUrl(CONFIGURED_BASE_URL); + try { + doSignUp(createMobileSignUpRequest(CUSTOMER_TEST_EMAIL, mobilePkgName, appSecret, PlatformType.ANDROID)); + + Mockito.clearInvocations(mailService); + mockMvc.perform(post("/api/noauth/resendEmailActivation") + .param("email", CUSTOMER_TEST_EMAIL) + .param("pkgName", mobilePkgName) + .param("platform", PlatformType.ANDROID.name()) + .header("Host", OTHER_HOST)) + .andExpect(status().isOk()); + + assertThat(captureActivationLink()).startsWith(CONFIGURED_BASE_URL + "/api/noauth/activateEmail?emailCode="); + } finally { + adminSettingsService.saveAdminSettings(TenantId.SYS_TENANT_ID, generalSettings); + } + removeCreatedUser(userService.findUserByEmail(tenantId, CUSTOMER_TEST_EMAIL)); + } + + @Test + public void testAccountActivatedEmailLinkUsesConfiguredBaseUrl() throws Exception { + createWebSelfRegistrationSettings(); + AdminSettings generalSettings = setGeneralBaseUrl(CONFIGURED_BASE_URL); + User user; + try { + doSignUp(createWebSignUpRequest(CUSTOMER_TEST_EMAIL)); + user = userService.findUserByEmail(tenantId, CUSTOMER_TEST_EMAIL); + String activateToken = userService.findUserCredentialsByUserId(tenantId, user.getId()).getActivateToken(); + + Mockito.clearInvocations(mailService); + doPost("/api/noauth/activateByEmailCode?emailCode=" + activateToken).andExpect(status().isOk()); + + verify(mailService, times(1)).sendAccountActivatedEmail(eq(tenantId), eq(CONFIGURED_BASE_URL + "/login"), eq(CUSTOMER_TEST_EMAIL)); + } finally { + adminSettingsService.saveAdminSettings(TenantId.SYS_TENANT_ID, generalSettings); + } + removeCreatedUser(user); + } + + @Test + public void testActivationEmailLinkUsesHttpSchemeForNonHttpForwardedProto() throws Exception { + createWebSelfRegistrationSettings(); + + Mockito.clearInvocations(mailService); + mockMvc.perform(post("/api/noauth/signup") + .contentType(contentType) + .content(json(createWebSignUpRequest(CUSTOMER_TEST_EMAIL))) + .header("X-Forwarded-Proto", "ftp")) + .andExpect(status().isOk()); + + URI activationLink = URI.create(captureActivationLink()); + assertThat(activationLink.getScheme()).isEqualTo("http"); + assertThat(activationLink.getHost()).isEqualTo("localhost"); + + removeCreatedUser(userService.findUserByEmail(tenantId, CUSTOMER_TEST_EMAIL)); + } + + @Test + public void testActivationByEmailCodeOnOtherTenantSettingsIsRejected() throws Exception { + createWebSelfRegistrationSettings(); + doSignUp(createWebSignUpRequest(CUSTOMER_TEST_EMAIL)); + User user = userService.findUserByEmail(tenantId, CUSTOMER_TEST_EMAIL); + String activateToken = userService.findUserCredentialsByUserId(tenantId, user.getId()).getActivateToken(); + + createDifferentTenant(); + createWebSelfRegistrationParams(OTHER_HOST, Collections.emptyList()); + + mockMvc.perform(post("/api/noauth/activateByEmailCode") + .param("emailCode", activateToken) + .header("Host", OTHER_HOST)) + .andExpect(status().isBadRequest()); + + assertThat(userService.findUserCredentialsByUserId(tenantId, user.getId()).isEnabled()).isFalse(); + + deleteDifferentTenant(); + removeCreatedUser(user); + } + + @Test + public void testSaveSelfRegistrationParamsWithDomainOfOtherTenantIsForbidden() throws Exception { + String domainName = "signup-other-tenant.example.com"; + Domain savedDomain = doPost("/api/domain", constructDomain(domainName), Domain.class); + + loginDifferentTenant(); + WebSelfRegistrationParams selfRegistrationParams = new WebSelfRegistrationParams(); + selfRegistrationParams.setTitle("Please sign up"); + selfRegistrationParams.setPrivacyPolicy("Privacy policy"); + selfRegistrationParams.setTermsOfUse("Terms of use"); + selfRegistrationParams.setDomainId(savedDomain.getId()); + selfRegistrationParams.setPermissions(Collections.emptyList()); + + doPost("/api/selfRegistration/selfRegistrationParams", selfRegistrationParams) + .andExpect(status().isForbidden()); + + assertThat(whiteLabelingService.findWhiteLabelingByDomainAndType(domainName, WhiteLabelingType.SELF_REGISTRATION)).isNull(); + assertThat(whiteLabelingService.findWhiteLabelingByDomainAndType(domainName, WhiteLabelingType.PRIVACY_POLICY)).isNull(); + assertThat(whiteLabelingService.findWhiteLabelingByDomainAndType(domainName, WhiteLabelingType.TERMS_OF_USE)).isNull(); + } + protected SignUpRequest createWebSignUpRequest(String email) { var signUpRequest = new SignUpRequest(); signUpRequest.setFields(Map.of(SignUpFieldId.EMAIL, email, @@ -388,8 +663,39 @@ public class SignUpControllerSqlTest extends AbstractControllerTest { Assert.assertNull("Expected that created user is deleted but one found!", found); } + private String captureActivationLink() throws Exception { + ArgumentCaptor activationLink = ArgumentCaptor.forClass(String.class); + verify(mailService, times(1)).sendActivationEmail(eq(tenantId), activationLink.capture(), anyLong(), eq(CUSTOMER_TEST_EMAIL)); + return activationLink.getValue(); + } + + private AdminSettings setGeneralBaseUrl(String baseUrl) { + AdminSettings generalSettings = adminSettingsService.findAdminSettingsByKey(TenantId.SYS_TENANT_ID, "general"); + AdminSettings updatedSettings = new AdminSettings(generalSettings); + ObjectNode jsonValue = generalSettings.getJsonValue().deepCopy(); + if (baseUrl != null) { + jsonValue.put("baseUrl", baseUrl); + } else { + jsonValue.remove("baseUrl"); + } + jsonValue.put("prohibitDifferentUrl", true); + updatedSettings.setJsonValue(jsonValue); + adminSettingsService.saveAdminSettings(TenantId.SYS_TENANT_ID, updatedSettings); + return generalSettings; + } + private void createWebSelfRegistrationSettings() { - Domain domain = constructDomain("localhost"); + createWebSelfRegistrationSettings(Collections.emptyList()); + } + + private void createWebSelfRegistrationSettings(List permissions) { + createWebSelfRegistrationParams("localhost", permissions); + createNotificationTemplate(NotificationType.USER_ACTIVATED, "User activated", "User ${userEmail} was activated", NotificationDeliveryMethod.WEB); + createNotificationTemplate(NotificationType.USER_REGISTERED, "User registered", "User ${userEmail} was registered", NotificationDeliveryMethod.WEB); + } + + private void createWebSelfRegistrationParams(String domainName, List permissions) { + Domain domain = constructDomain(domainName); Domain savedDomain = doPost("/api/domain", domain, Domain.class); WebSelfRegistrationParams selfRegistrationParams = new WebSelfRegistrationParams(); @@ -402,13 +708,10 @@ 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); - - createNotificationTemplate(NotificationType.USER_ACTIVATED, "User activated", "User ${userEmail} was activated", NotificationDeliveryMethod.WEB); - createNotificationTemplate(NotificationType.USER_REGISTERED, "User registered", "User ${userEmail} was registered", NotificationDeliveryMethod.WEB); } private void createMobileSelfRegistrationSettings(String mobilePkgName, String appSecret, PlatformType platformType, diff --git a/application/src/test/java/org/thingsboard/server/controller/TbResourceControllerTest.java b/application/src/test/java/org/thingsboard/server/controller/TbResourceControllerTest.java index 1aae2d7fa5..fec9f9cb4d 100644 --- a/application/src/test/java/org/thingsboard/server/controller/TbResourceControllerTest.java +++ b/application/src/test/java/org/thingsboard/server/controller/TbResourceControllerTest.java @@ -22,6 +22,7 @@ import org.thingsboard.server.common.data.Customer; import org.thingsboard.server.common.data.Dashboard; import org.thingsboard.server.common.data.EntityInfo; import org.thingsboard.server.common.data.EntityType; +import org.thingsboard.server.common.data.ResourceSubType; import org.thingsboard.server.common.data.ResourceType; import org.thingsboard.server.common.data.StringUtils; import org.thingsboard.server.common.data.TbResource; @@ -32,6 +33,7 @@ import org.thingsboard.server.common.data.audit.ActionType; import org.thingsboard.server.common.data.group.EntityGroup; import org.thingsboard.server.common.data.group.EntityGroupInfo; import org.thingsboard.server.common.data.id.TbResourceId; +import org.thingsboard.server.common.data.id.TenantId; import org.thingsboard.server.common.data.lwm2m.LwM2mObject; import org.thingsboard.server.common.data.page.PageData; import org.thingsboard.server.common.data.page.PageLink; @@ -926,6 +928,160 @@ public class TbResourceControllerTest extends AbstractControllerTest { assertThat(download(savedResource.getId())).asBase64Encoded().isEqualTo(newData); } + @Test + public void testUpdateResourceInfoKeepsStoredTenant() throws Exception { + TbResourceInfo savedResource = saveJsModule(); + + TbResourceInfo resourceInfo = findResourceInfo(savedResource.getId()); + resourceInfo.setTenantId(null); + resourceInfo.setTitle("Updated title"); + Mockito.reset(tbClusterService, auditLogService); + TbResourceInfo updatedResource = doPut("/api/resource/" + savedResource.getUuidId() + "/info", resourceInfo, TbResourceInfo.class); + assertThat(updatedResource.getTenantId()).isEqualTo(savedTenant.getId()); + assertThat(updatedResource.getTitle()).isEqualTo("Updated title"); + testNotifyEntityAllOneTimeLogEntityActionEntityEqClass(updatedResource, updatedResource.getId(), updatedResource.getId(), + savedTenant.getId(), tenantAdmin.getCustomerId(), tenantAdmin.getId(), tenantAdmin.getEmail(), + ActionType.UPDATED, ActionType.UPDATED); + resourceInfo = findResourceInfo(savedResource.getId()); + assertThat(resourceInfo.getTenantId()).isEqualTo(savedTenant.getId()); + assertThat(resourceInfo.getTitle()).isEqualTo("Updated title"); + + resourceInfo.setTenantId(TenantId.SYS_TENANT_ID); + doPut("/api/resource/" + savedResource.getUuidId() + "/info", resourceInfo, TbResourceInfo.class); + assertThat(findResourceInfo(savedResource.getId()).getTenantId()).isEqualTo(savedTenant.getId()); + + loginDifferentTenant(); + login(tenantAdmin.getEmail(), "testPassword1"); + resourceInfo.setTenantId(savedDifferentTenant.getId()); + doPut("/api/resource/" + savedResource.getUuidId() + "/info", resourceInfo, TbResourceInfo.class); + assertThat(findResourceInfo(savedResource.getId()).getTenantId()).isEqualTo(savedTenant.getId()); + + deleteDifferentTenant(); + } + + @Test + public void testUpdateResourceInfoKeepsStoredKeyAndEtag() throws Exception { + TbResourceInfo savedResource = saveJsModule(); + + TbResourceInfo resourceInfo = findResourceInfo(savedResource.getId()); + resourceInfo.setTitle("Updated title"); + resourceInfo.setResourceKey("other-key"); + resourceInfo.setEtag("0"); + resourceInfo.setCreatedTime(1); + TbResourceInfo updatedResource = doPut("/api/resource/" + savedResource.getUuidId() + "/info", resourceInfo, TbResourceInfo.class); + assertThat(updatedResource.getTitle()).isEqualTo("Updated title"); + assertThat(updatedResource.getResourceKey()).isEqualTo(savedResource.getResourceKey()); + assertThat(updatedResource.getEtag()).isEqualTo(savedResource.getEtag()); + assertThat(updatedResource.getCreatedTime()).isEqualTo(savedResource.getCreatedTime()); + + resourceInfo = findResourceInfo(savedResource.getId()); + assertThat(resourceInfo.getResourceKey()).isEqualTo(savedResource.getResourceKey()); + assertThat(resourceInfo.getEtag()).isEqualTo(savedResource.getEtag()); + } + + @Test + public void testUpdateResourceInfoRefusesTypeChange() throws Exception { + TbResourceInfo savedResource = saveJsModule(); + + TbResourceInfo resourceInfo = findResourceInfo(savedResource.getId()); + resourceInfo.setResourceType(ResourceType.GENERAL); + doPut("/api/resource/" + savedResource.getUuidId() + "/info", resourceInfo) + .andExpect(status().isBadRequest()) + .andExpect(statusReason(containsString("can't be changed"))); + + resourceInfo = findResourceInfo(savedResource.getId()); + resourceInfo.setResourceSubType(ResourceSubType.MODULE); + doPut("/api/resource/" + savedResource.getUuidId() + "/info", resourceInfo) + .andExpect(status().isBadRequest()) + .andExpect(statusReason(containsString("can't be changed"))); + + resourceInfo = findResourceInfo(savedResource.getId()); + assertThat(resourceInfo.getResourceType()).isEqualTo(ResourceType.JS_MODULE); + assertThat(resourceInfo.getResourceSubType()).isEqualTo(ResourceSubType.EXTENSION); + + resourceInfo.setTitle("Updated title"); + ObjectNode request = (ObjectNode) JacksonUtil.valueToTree(resourceInfo); + request.putNull("resourceType"); + request.putNull("resourceSubType"); + TbResourceInfo updatedResource = doPut("/api/resource/" + savedResource.getUuidId() + "/info", request, TbResourceInfo.class); + assertThat(updatedResource.getTitle()).isEqualTo("Updated title"); + resourceInfo = findResourceInfo(savedResource.getId()); + assertThat(resourceInfo.getResourceType()).isEqualTo(ResourceType.JS_MODULE); + assertThat(resourceInfo.getResourceSubType()).isEqualTo(ResourceSubType.EXTENSION); + } + + @Test + public void testSaveResourceWithIdKeepsStoredTypeKeyAndEtag() throws Exception { + TbResourceInfo savedResource = saveJsModule(); + + TbResource resource = new TbResource(findResourceInfo(savedResource.getId())); + resource.setResourceType(ResourceType.GENERAL); + doPost("/api/resource", resource) + .andExpect(status().isBadRequest()) + .andExpect(statusReason(containsString("can't be changed"))); + + resource.setResourceType(ResourceType.JS_MODULE); + resource.setTitle("Updated title"); + resource.setResourceKey("other-key"); + resource.setEtag("0"); + TbResourceInfo updatedResource = doPost("/api/resource", resource, TbResourceInfo.class); + assertThat(updatedResource.getTitle()).isEqualTo("Updated title"); + assertThat(updatedResource.getResourceKey()).isEqualTo(savedResource.getResourceKey()); + assertThat(updatedResource.getEtag()).isEqualTo(savedResource.getEtag()); + + TbResourceInfo resourceInfo = findResourceInfo(savedResource.getId()); + assertThat(resourceInfo.getResourceType()).isEqualTo(ResourceType.JS_MODULE); + assertThat(resourceInfo.getResourceKey()).isEqualTo(savedResource.getResourceKey()); + assertThat(resourceInfo.getEtag()).isEqualTo(savedResource.getEtag()); + } + + @Test + public void testSysAdminUpdateResourceInfoKeepsSystemTenant() throws Exception { + loginSysAdmin(); + TbResourceInfo savedResource = saveJsModule(); + assertThat(savedResource.getTenantId()).isEqualTo(TenantId.SYS_TENANT_ID); + + TbResourceInfo resourceInfo = findResourceInfo(savedResource.getId()); + resourceInfo.setTenantId(savedTenant.getId()); + TbResourceInfo updatedResource = doPut("/api/resource/" + savedResource.getUuidId() + "/info", resourceInfo, TbResourceInfo.class); + assertThat(updatedResource.getTenantId()).isEqualTo(TenantId.SYS_TENANT_ID); + assertThat(findResourceInfo(savedResource.getId()).getTenantId()).isEqualTo(TenantId.SYS_TENANT_ID); + + doDelete("/api/resource/" + savedResource.getUuidId()).andExpect(status().isOk()); + } + + @Test + public void testUpdateResourceInfoKeepsStoredCustomer() throws Exception { + Customer storedCustomer = saveCustomer("Stored resource customer"); + Customer otherCustomer = saveCustomer("Other resource customer"); + + TbResource resource = new TbResource(); + resource.setResourceType(ResourceType.JS_MODULE); + resource.setResourceSubType(ResourceSubType.EXTENSION); + resource.setTitle("Js resource"); + resource.setFileName(JS_TEST_FILE_NAME); + resource.setEncodedData(TEST_DATA); + resource.setCustomerId(storedCustomer.getId()); + TbResourceInfo savedResource = doPost("/api/resource", resource, TbResourceInfo.class); + assertThat(savedResource.getCustomerId()).isEqualTo(storedCustomer.getId()); + + TbResourceInfo resourceInfo = findResourceInfo(savedResource.getId()); + resourceInfo.setCustomerId(otherCustomer.getId()); + TbResourceInfo updatedResource = doPut("/api/resource/" + savedResource.getUuidId() + "/info", resourceInfo, TbResourceInfo.class); + assertThat(updatedResource.getCustomerId()).isEqualTo(storedCustomer.getId()); + + resourceInfo.setCustomerId(null); + updatedResource = doPut("/api/resource/" + savedResource.getUuidId() + "/info", resourceInfo, TbResourceInfo.class); + assertThat(updatedResource.getCustomerId()).isEqualTo(storedCustomer.getId()); + assertThat(findResourceInfo(savedResource.getId()).getCustomerId()).isEqualTo(storedCustomer.getId()); + } + + private Customer saveCustomer(String title) throws Exception { + Customer customer = new Customer(); + customer.setTitle(title); + return doPost("/api/customer", customer, Customer.class); + } + @Test public void testGetLwm2mListObjectsPage() throws Exception { loginTenantAdmin(); @@ -1087,6 +1243,16 @@ public class TbResourceControllerTest extends AbstractControllerTest { return uploadResource(HttpMethod.POST, "/api/resource/upload", tbResource.getFileName(), tbResource.getResourceType().getMediaType(), data, parts); } + private TbResourceInfo saveJsModule() throws Exception { + TbResource resource = new TbResource(); + resource.setResourceType(ResourceType.JS_MODULE); + resource.setResourceSubType(ResourceSubType.EXTENSION); + resource.setTitle("Js resource"); + resource.setFileName(JS_TEST_FILE_NAME); + resource.setEncodedData(TEST_DATA); + return save(resource); + } + private TbResourceInfo findResourceInfo(TbResourceId id) throws Exception { return doGet("/api/resource/info/" + id, TbResourceInfo.class); } diff --git a/application/src/test/java/org/thingsboard/server/edge/CalculatedFieldEdgeTest.java b/application/src/test/java/org/thingsboard/server/edge/CalculatedFieldEdgeTest.java index f6c34f1ffa..e4a78643f5 100644 --- a/application/src/test/java/org/thingsboard/server/edge/CalculatedFieldEdgeTest.java +++ b/application/src/test/java/org/thingsboard/server/edge/CalculatedFieldEdgeTest.java @@ -20,6 +20,7 @@ import org.thingsboard.server.common.data.cf.configuration.TimeSeriesOutput; import org.thingsboard.server.common.data.debug.DebugSettings; import org.thingsboard.server.common.data.id.CalculatedFieldId; import org.thingsboard.server.common.data.id.EntityId; +import org.thingsboard.server.common.data.id.TenantId; import org.thingsboard.server.dao.cf.CalculatedFieldService; import org.thingsboard.server.dao.service.DaoSqlTest; import org.thingsboard.server.gen.edge.v1.CalculatedFieldRequestMsg; @@ -109,6 +110,40 @@ public class CalculatedFieldEdgeTest extends AbstractEdgeTest { checkCalculatedFieldOnCloud(uplinkMsg, uuid, calculatedField.getName()); } + @Test + public void testSendCalculatedFieldToCloudSavesItUnderEdgeTenant() throws Exception { + Device savedDevice = saveDeviceOnCloudAndVerifyDeliveryToEdge(); + + SimpleCalculatedFieldConfiguration config = new SimpleCalculatedFieldConfiguration(); + CalculatedField calculatedField = createSimpleCalculatedField(savedDevice.getId(), config); + calculatedField.setTenantId(TenantId.fromUUID(UUID.randomUUID())); + UUID uuid = Uuids.timeBased(); + UplinkMsg uplinkMsg = getUplinkMsg(uuid, calculatedField, UpdateMsgType.ENTITY_CREATED_RPC_MESSAGE); + + checkCalculatedFieldOnCloud(uplinkMsg, uuid, calculatedField.getName()); + + CalculatedField calculatedFieldFromCloud = doGet("/api/calculatedField/" + uuid, CalculatedField.class); + Assert.assertEquals(tenantId, calculatedFieldFromCloud.getTenantId()); + } + + @Test + public void testSendCalculatedFieldWithOtherTenantReferenceToCloud() throws Exception { + Device savedDevice = saveDeviceOnCloudAndVerifyDeliveryToEdge(); + + SimpleCalculatedFieldConfiguration config = new SimpleCalculatedFieldConfiguration(); + CalculatedField calculatedField = createSimpleCalculatedField(savedDevice.getId(), config); + config.getArguments().get("T").setRefEntityId(TenantId.fromUUID(UUID.randomUUID())); + UUID uuid = Uuids.timeBased(); + UplinkMsg uplinkMsg = getUplinkMsg(uuid, calculatedField, UpdateMsgType.ENTITY_CREATED_RPC_MESSAGE); + + edgeImitator.expectResponsesAmount(1); + edgeImitator.sendUplinkMsg(uplinkMsg); + Assert.assertTrue(edgeImitator.waitForResponses()); + + Assert.assertFalse(edgeImitator.getLatestResponseMsg().getSuccess()); + doGet("/api/calculatedField/" + uuid).andExpect(status().isNotFound()); + } + @Test public void testSendCalculatedFieldRequestToCloud() throws Exception { Device savedDevice = saveDeviceOnCloudAndVerifyDeliveryToEdge(); diff --git a/application/src/test/java/org/thingsboard/server/edge/DeviceEdgeTest.java b/application/src/test/java/org/thingsboard/server/edge/DeviceEdgeTest.java index db600a0d17..49736cdb3d 100644 --- a/application/src/test/java/org/thingsboard/server/edge/DeviceEdgeTest.java +++ b/application/src/test/java/org/thingsboard/server/edge/DeviceEdgeTest.java @@ -679,6 +679,61 @@ public class DeviceEdgeTest extends AbstractEdgeTest { Assert.assertEquals(deviceName + " Updated", device.getName()); } + @Test + public void testSendDeviceToCloudAddsDeviceOnlyToGroupOfEdgeTenant() throws Exception { + loginDifferentTenant(); + EntityGroup otherTenantGroup = new EntityGroup(); + otherTenantGroup.setType(EntityType.DEVICE); + otherTenantGroup.setName("Other Tenant Device Group"); + otherTenantGroup = doPost("/api/entityGroup", otherTenantGroup, EntityGroup.class); + loginTenantAdmin(); + + Device deviceMsg = buildDeviceForUplinkMsg("Edge Device In Group", "test"); + UplinkMsg.Builder uplinkMsgBuilder = UplinkMsg.newBuilder(); + DeviceUpdateMsg.Builder deviceUpdateMsgBuilder = DeviceUpdateMsg.newBuilder(); + deviceUpdateMsgBuilder.setIdMSB(deviceMsg.getUuidId().getMostSignificantBits()); + deviceUpdateMsgBuilder.setIdLSB(deviceMsg.getUuidId().getLeastSignificantBits()); + deviceUpdateMsgBuilder.setEntityGroupIdMSB(otherTenantGroup.getUuidId().getMostSignificantBits()); + deviceUpdateMsgBuilder.setEntityGroupIdLSB(otherTenantGroup.getUuidId().getLeastSignificantBits()); + deviceUpdateMsgBuilder.setEntity(JacksonUtil.toString(deviceMsg)); + deviceUpdateMsgBuilder.setMsgType(UpdateMsgType.ENTITY_CREATED_RPC_MESSAGE); + uplinkMsgBuilder.addDeviceUpdateMsg(deviceUpdateMsgBuilder.build()); + + edgeImitator.expectResponsesAmount(1); + edgeImitator.sendUplinkMsg(uplinkMsgBuilder.build()); + Assert.assertTrue(edgeImitator.waitForResponses()); + + Device device = doGet("/api/device/" + deviceMsg.getId().getId(), Device.class); + Assert.assertNotNull(device); + Assert.assertFalse(entityGroupService.isEntityInGroup(differentTenantId, device.getId(), otherTenantGroup.getId())); + } + + @Test + public void testDeleteDeviceFromGroupOnCloudKeepsGroupsOfOtherTenant() throws Exception { + loginDifferentTenant(); + EntityGroup otherTenantGroup = new EntityGroup(); + otherTenantGroup.setType(EntityType.DEVICE); + otherTenantGroup.setName("Other Tenant Device Group"); + otherTenantGroup = doPost("/api/entityGroup", otherTenantGroup, EntityGroup.class); + Device otherTenantDevice = saveDevice("Other Tenant Device", "test", otherTenantGroup.getId()); + loginTenantAdmin(); + + UplinkMsg.Builder uplinkMsgBuilder = UplinkMsg.newBuilder(); + DeviceUpdateMsg.Builder deviceUpdateMsgBuilder = DeviceUpdateMsg.newBuilder(); + deviceUpdateMsgBuilder.setIdMSB(otherTenantDevice.getUuidId().getMostSignificantBits()); + deviceUpdateMsgBuilder.setIdLSB(otherTenantDevice.getUuidId().getLeastSignificantBits()); + deviceUpdateMsgBuilder.setEntityGroupIdMSB(otherTenantGroup.getUuidId().getMostSignificantBits()); + deviceUpdateMsgBuilder.setEntityGroupIdLSB(otherTenantGroup.getUuidId().getLeastSignificantBits()); + deviceUpdateMsgBuilder.setMsgType(UpdateMsgType.ENTITY_DELETED_RPC_MESSAGE); + uplinkMsgBuilder.addDeviceUpdateMsg(deviceUpdateMsgBuilder.build()); + + edgeImitator.expectResponsesAmount(1); + edgeImitator.sendUplinkMsg(uplinkMsgBuilder.build()); + Assert.assertTrue(edgeImitator.waitForResponses()); + + Assert.assertTrue(entityGroupService.isEntityInGroup(differentTenantId, otherTenantDevice.getId(), otherTenantGroup.getId())); + } + @Test public void testRpcCall() throws Exception { Device device = saveDeviceOnCloudAndVerifyDeliveryToEdge(); diff --git a/application/src/test/java/org/thingsboard/server/edge/EntityViewEdgeTest.java b/application/src/test/java/org/thingsboard/server/edge/EntityViewEdgeTest.java index 176481a248..4bb40b6a87 100644 --- a/application/src/test/java/org/thingsboard/server/edge/EntityViewEdgeTest.java +++ b/application/src/test/java/org/thingsboard/server/edge/EntityViewEdgeTest.java @@ -18,6 +18,7 @@ import org.thingsboard.server.common.data.group.EntityGroup; import org.thingsboard.server.common.data.id.DeviceId; import org.thingsboard.server.common.data.id.EntityGroupId; import org.thingsboard.server.common.data.id.EntityViewId; +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.dao.service.DaoSqlTest; @@ -191,6 +192,69 @@ public class EntityViewEdgeTest extends AbstractEdgeTest { Assert.assertNotEquals(entityViewOnCloudName, entityView.getName()); } + @Test + public void testEntityViewFromEdgeSavedInEdgeTenant() throws Exception { + Device device = saveDeviceOnCloudAndVerifyDeliveryToEdge(); + + EntityView entityViewMsg = buildEntityViewForUplinkMsg(device, "Edge EntityView 3"); + entityViewMsg.setTenantId(TenantId.fromUUID(UUID.randomUUID())); + + UplinkMsg.Builder uplinkMsgBuilder = UplinkMsg.newBuilder(); + EntityViewUpdateMsg.Builder entityViewUpdateMsgBuilder = EntityViewUpdateMsg.newBuilder(); + entityViewUpdateMsgBuilder.setIdMSB(entityViewMsg.getUuidId().getMostSignificantBits()); + entityViewUpdateMsgBuilder.setIdLSB(entityViewMsg.getUuidId().getLeastSignificantBits()); + entityViewUpdateMsgBuilder.setEntity(JacksonUtil.toString(entityViewMsg)); + entityViewUpdateMsgBuilder.setMsgType(UpdateMsgType.ENTITY_CREATED_RPC_MESSAGE); + uplinkMsgBuilder.addEntityViewUpdateMsg(entityViewUpdateMsgBuilder.build()); + + edgeImitator.expectResponsesAmount(1); + edgeImitator.expectMessageAmount(1); + edgeImitator.sendUplinkMsg(uplinkMsgBuilder.build()); + Assert.assertTrue(edgeImitator.waitForResponses()); + Assert.assertTrue(edgeImitator.getLatestResponseMsg().getSuccess()); + + EntityView entityView = doGet("/api/entityView/" + entityViewMsg.getUuidId(), EntityView.class); + Assert.assertEquals(tenantId, entityView.getTenantId()); + } + + @Test + public void testEntityViewFromEdgeWithIdOfOtherTenantViewNotSaved() throws Exception { + Device edgeDevice = saveDeviceOnCloudAndVerifyDeliveryToEdge(); + + loginDifferentTenant(); + Device otherTenantDevice = new Device(); + otherTenantDevice.setName("Other tenant device"); + otherTenantDevice.setType("default"); + otherTenantDevice = doPost("/api/device", otherTenantDevice, Device.class); + EntityView otherTenantView = saveEntityView("Other tenant EntityView", otherTenantDevice.getId(), null); + loginTenantAdmin(); + + EntityView entityViewMsg = buildEntityViewForUplinkMsg(edgeDevice, "Edge EntityView 4"); + entityViewMsg.setId(otherTenantView.getId()); + + UplinkMsg.Builder uplinkMsgBuilder = UplinkMsg.newBuilder(); + EntityViewUpdateMsg.Builder entityViewUpdateMsgBuilder = EntityViewUpdateMsg.newBuilder(); + entityViewUpdateMsgBuilder.setIdMSB(entityViewMsg.getUuidId().getMostSignificantBits()); + entityViewUpdateMsgBuilder.setIdLSB(entityViewMsg.getUuidId().getLeastSignificantBits()); + entityViewUpdateMsgBuilder.setEntity(JacksonUtil.toString(entityViewMsg)); + entityViewUpdateMsgBuilder.setMsgType(UpdateMsgType.ENTITY_UPDATED_RPC_MESSAGE); + uplinkMsgBuilder.addEntityViewUpdateMsg(entityViewUpdateMsgBuilder.build()); + + edgeImitator.expectResponsesAmount(1); + edgeImitator.sendUplinkMsg(uplinkMsgBuilder.build()); + Assert.assertTrue(edgeImitator.waitForResponses()); + Assert.assertFalse(edgeImitator.getLatestResponseMsg().getSuccess()); + + loginDifferentTenant(); + EntityView storedView = doGet("/api/entityView/" + otherTenantView.getUuidId(), EntityView.class); + Assert.assertEquals(differentTenantId, storedView.getTenantId()); + Assert.assertEquals("Other tenant EntityView", storedView.getName()); + Assert.assertEquals(otherTenantDevice.getId(), storedView.getEntityId()); + Assert.assertEquals(otherTenantView.getCustomerId(), storedView.getCustomerId()); + Assert.assertEquals(otherTenantView.getOwnerId(), storedView.getOwnerId()); + loginTenantAdmin(); + } + @Test public void testSendUnassignEntityViewFromGroupOnEdgeToCloud() throws Exception { Device device = saveDeviceOnCloudAndVerifyDeliveryToEdge(); diff --git a/application/src/test/java/org/thingsboard/server/edge/TelemetryEdgeTest.java b/application/src/test/java/org/thingsboard/server/edge/TelemetryEdgeTest.java index 031b646b00..c4f4e25942 100644 --- a/application/src/test/java/org/thingsboard/server/edge/TelemetryEdgeTest.java +++ b/application/src/test/java/org/thingsboard/server/edge/TelemetryEdgeTest.java @@ -390,4 +390,49 @@ public class TelemetryEdgeTest extends AbstractEdgeTest { }); } + @Test + public void testSendEntityGroupAttributesAndTelemetryForGroupOfDifferentTenantToCloud() throws Exception { + loginDifferentTenant(); + EntityGroup entityGroup = new EntityGroup(); + entityGroup.setType(EntityType.DEVICE); + entityGroup.setName("Different Tenant Device Group"); + EntityGroup savedEntityGroup = doPost("/api/entityGroup", entityGroup, EntityGroup.class); + loginTenantAdmin(); + + EntityDataProto entityData = EntityDataProto.newBuilder() + .setEntityIdMSB(savedEntityGroup.getUuidId().getMostSignificantBits()) + .setEntityIdLSB(savedEntityGroup.getUuidId().getLeastSignificantBits()) + .setEntityType(EntityType.ENTITY_GROUP.name()) + .setAttributesUpdatedMsg(TransportProtos.PostAttributeMsg.newBuilder() + .addKv(TransportProtos.KeyValueProto.newBuilder() + .setKey("groupKey") + .setType(TransportProtos.KeyValueType.STRING_V) + .setStringV("groupValue").build()) + .build()) + .setPostAttributeScope(DataConstants.SERVER_SCOPE) + .setPostTelemetryMsg(TransportProtos.PostTelemetryMsg.newBuilder() + .addTsKvList(TransportProtos.TsKvListProto.newBuilder() + .setTs(System.currentTimeMillis()) + .addKv(TransportProtos.KeyValueProto.newBuilder() + .setKey("groupTemperature") + .setType(TransportProtos.KeyValueType.LONG_V) + .setLongV(25).build()) + .build()) + .build()) + .build(); + sendUplinkMsgAndWaitForResponse(uplinkMsgBuilder -> uplinkMsgBuilder.addEntityData(entityData)); + + loginDifferentTenant(); + String keysUrl = "/api/plugins/telemetry/ENTITY_GROUP/" + savedEntityGroup.getUuidId() + "/keys/"; + Awaitility.await() + .pollDelay(3, TimeUnit.SECONDS) + .atMost(10, TimeUnit.SECONDS) + .untilAsserted(() -> { + List attributeKeys = doGetAsyncTyped(keysUrl + "attributes/" + DataConstants.SERVER_SCOPE, new TypeReference<>() {}); + Assert.assertTrue(attributeKeys.isEmpty()); + List timeseriesKeys = doGetAsyncTyped(keysUrl + "timeseries", new TypeReference<>() {}); + Assert.assertTrue(timeseriesKeys.isEmpty()); + }); + } + } diff --git a/application/src/test/java/org/thingsboard/server/service/entitiy/EntityServiceTest.java b/application/src/test/java/org/thingsboard/server/service/entitiy/EntityServiceTest.java index 208c4ae00e..e509d2666d 100644 --- a/application/src/test/java/org/thingsboard/server/service/entitiy/EntityServiceTest.java +++ b/application/src/test/java/org/thingsboard/server/service/entitiy/EntityServiceTest.java @@ -2105,6 +2105,7 @@ public class EntityServiceTest extends AbstractControllerTest { entityView.setCustomerId(customerId); entityView.setName("test"); entityView.setType("default"); + entityView.setEntityId(deviceId); customerEntityIds.add(entityViewService.saveEntityView(entityView).getId()); EntityGroup entityGroup = new EntityGroup(); @@ -3876,12 +3877,18 @@ public class EntityServiceTest extends AbstractControllerTest { @Test public void testEntityViewEntityMapping() { + Device device = new Device(); + device.setTenantId(tenantId); + device.setName("Device for entity view"); + device.setType("default"); + device = deviceService.saveDevice(device); + EntityView entityView = new EntityView(); entityView.setTenantId(tenantId); entityView.setCustomerId(customerId); entityView.setName("test"); entityView.setType("default"); - entityView.setEntityId(new DeviceId(UUID.randomUUID())); + entityView.setEntityId(device.getId()); entityView.setKeys(new TelemetryEntityView(List.of("test"), null)); entityView.setStartTimeMs(124); entityView.setEndTimeMs(256); @@ -3913,12 +3920,18 @@ public class EntityServiceTest extends AbstractControllerTest { @Test public void testFindEntitiesWithEntityViewFilter() { + Device device = new Device(); + device.setTenantId(tenantId); + device.setName("Device for entity view"); + device.setType("default"); + device = deviceService.saveDevice(device); + EntityView entityView = new EntityView(); entityView.setTenantId(tenantId); entityView.setCustomerId(customerId); entityView.setName("test"); entityView.setType("default"); - entityView.setEntityId(new DeviceId(UUID.randomUUID())); + entityView.setEntityId(device.getId()); entityView.setKeys(new TelemetryEntityView(List.of("test"), null)); entityView.setStartTimeMs(124); entityView.setEndTimeMs(256); diff --git a/application/src/test/java/org/thingsboard/server/service/install/update/EntityViewGroupAllUpdaterTest.java b/application/src/test/java/org/thingsboard/server/service/install/update/EntityViewGroupAllUpdaterTest.java new file mode 100644 index 0000000000..f939680b3f --- /dev/null +++ b/application/src/test/java/org/thingsboard/server/service/install/update/EntityViewGroupAllUpdaterTest.java @@ -0,0 +1,35 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +package org.thingsboard.server.service.install.update; + +import org.junit.jupiter.api.Test; +import org.thingsboard.server.common.data.EntityView; +import org.thingsboard.server.common.data.group.EntityGroup; +import org.thingsboard.server.common.data.id.CustomerId; +import org.thingsboard.server.dao.customer.CustomerService; +import org.thingsboard.server.dao.entityview.EntityViewService; +import org.thingsboard.server.dao.group.EntityGroupService; + +import java.util.UUID; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; + +class EntityViewGroupAllUpdaterTest { + + @Test + void testUnassignFromCustomerSavesWithoutValidation() { + EntityViewService entityViewService = mock(EntityViewService.class); + EntityViewGroupAllUpdater updater = new EntityViewGroupAllUpdater(entityViewService, mock(CustomerService.class), + mock(EntityGroupService.class), new EntityGroup(), true); + EntityView entityView = new EntityView(); + entityView.setCustomerId(new CustomerId(UUID.randomUUID())); + + updater.unassignFromCustomer(entityView); + + verify(entityViewService).saveEntityView(entityView, false); + assertThat(entityView.getCustomerId().isNullUid()).isTrue(); + } + +} 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 919c0884ca..a7ac68bd8e 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 @@ -21,6 +21,21 @@ import org.mockito.junit.jupiter.MockitoExtension; import org.slf4j.LoggerFactory; import org.thingsboard.common.util.JacksonUtil; import org.thingsboard.server.common.data.Device; +import org.thingsboard.server.common.data.cf.CalculatedField; +import org.thingsboard.server.common.data.cf.CalculatedFieldType; +import org.thingsboard.server.common.data.cf.configuration.AlarmCalculatedFieldConfiguration; +import org.thingsboard.server.common.data.cf.configuration.Argument; +import org.thingsboard.server.common.data.cf.configuration.ArgumentType; +import org.thingsboard.server.common.data.cf.configuration.ArgumentsBasedCalculatedFieldConfiguration; +import org.thingsboard.server.common.data.cf.configuration.CalculatedFieldConfiguration; +import org.thingsboard.server.common.data.cf.configuration.ReferencedEntityKey; +import org.thingsboard.server.common.data.cf.configuration.SimpleCalculatedFieldConfiguration; +import org.thingsboard.server.common.data.cf.configuration.TimeSeriesOutput; +import org.thingsboard.server.common.data.cf.configuration.geofencing.EntityCoordinates; +import org.thingsboard.server.common.data.cf.configuration.geofencing.GeofencingCalculatedFieldConfiguration; +import org.thingsboard.server.common.data.cf.configuration.geofencing.GeofencingReportStrategy; +import org.thingsboard.server.common.data.cf.configuration.geofencing.ZoneGroupConfiguration; +import org.thingsboard.server.common.data.id.CalculatedFieldId; import org.thingsboard.server.common.data.id.DashboardId; import org.thingsboard.server.common.data.id.DeviceId; import org.thingsboard.server.common.data.id.DeviceProfileId; @@ -32,6 +47,8 @@ import org.thingsboard.server.common.data.rule.RuleChain; import org.thingsboard.server.exception.DataValidationException; import org.thingsboard.server.common.data.id.TenantId; import org.thingsboard.server.common.data.integration.Integration; +import org.thingsboard.server.common.data.iot_hub.AlarmRuleInstalledItemDescriptor; +import org.thingsboard.server.common.data.iot_hub.CalculatedFieldInstalledItemDescriptor; import org.thingsboard.server.common.data.iot_hub.DeviceInstalledItemDescriptor; import org.thingsboard.server.common.data.iot_hub.IotHubInstalledItem; import org.thingsboard.server.common.data.iot_hub.RuleChainInstalledItemDescriptor; @@ -40,6 +57,7 @@ import org.thingsboard.server.common.data.DeviceProfile; import org.thingsboard.server.common.data.converter.Converter; import org.thingsboard.server.common.data.id.ConverterId; import org.thingsboard.server.common.data.page.PageData; +import org.thingsboard.server.dao.cf.CalculatedFieldService; import org.thingsboard.server.dao.dashboard.DashboardService; import org.thingsboard.server.dao.converter.ConverterService; import org.thingsboard.server.dao.device.DeviceProfileService; @@ -47,6 +65,7 @@ import org.thingsboard.server.dao.device.DeviceService; import org.thingsboard.server.dao.entity.EntityService; import org.thingsboard.server.dao.integration.IntegrationService; import org.thingsboard.server.dao.iot_hub.IotHubInstalledItemService; +import org.thingsboard.server.service.entitiy.cf.TbCalculatedFieldService; import org.thingsboard.server.dao.rule.RuleChainService; import org.thingsboard.server.service.entitiy.dashboard.TbDashboardService; import org.thingsboard.server.service.entitiy.converter.TbConverterService; @@ -55,6 +74,7 @@ import org.thingsboard.server.service.entitiy.device.profile.TbDeviceProfileServ import org.thingsboard.server.service.rule.TbRuleChainService; import org.thingsboard.server.service.security.model.SecurityUser; +import java.nio.charset.StandardCharsets; import java.util.List; import java.util.Map; import java.util.Optional; @@ -87,6 +107,10 @@ class DefaultIotHubServiceTest { @Mock private IotHubInstalledItemService iotHubInstalledItemService; @Mock + private TbCalculatedFieldService tbCalculatedFieldService; + @Mock + private CalculatedFieldService calculatedFieldService; + @Mock private DeviceService deviceService; @Mock private EntityService entityService; @@ -107,6 +131,8 @@ class DefaultIotHubServiceTest { @Mock private TbConverterService tbConverterService; @Mock + private DevicePackageEntities devicePackageEntities; + @Mock private RuleChainService ruleChainService; @Mock private TbRuleChainService tbRuleChainService; @@ -474,6 +500,151 @@ class DefaultIotHubServiceTest { assertThat(result.getErrorMessage()).contains("install failed"); } + @Test + void doInstallVersion_calculatedField_mapsTenantReferencesToInstallingTenant() throws Exception { + mockTenant(); + String versionId = UUID.randomUUID().toString(); + when(iotHubRestClient.getVersionInfo(versionId)) + .thenReturn(version(versionId, UUID.randomUUID().toString(), "CALCULATED_FIELD", "CF", "1.0")); + when(iotHubRestClient.getVersionFileData(versionId)).thenReturn(calculatedFieldFileData()); + when(tbCalculatedFieldService.save(any(), eq(user))).thenAnswer(invocation -> invocation.getArgument(0)); + when(iotHubInstalledItemService.save(eq(tenantId), any())).thenAnswer(invocation -> invocation.getArgument(1)); + + service.doInstallVersion(user, versionId, null, null); + + ArgumentCaptor captor = ArgumentCaptor.forClass(CalculatedField.class); + verify(tbCalculatedFieldService).save(captor.capture(), eq(user)); + assertThat(((ArgumentsBasedCalculatedFieldConfiguration) captor.getValue().getConfiguration()).getArguments().get("T").getRefEntityId()).isEqualTo(tenantId); + } + + @Test + void updateItemVersion_calculatedField_mapsTenantReferencesToInstallingTenant() throws Exception { + mockTenant(); + String versionId = UUID.randomUUID().toString(); + CalculatedFieldId calculatedFieldId = new CalculatedFieldId(UUID.randomUUID()); + CalculatedFieldInstalledItemDescriptor descriptor = new CalculatedFieldInstalledItemDescriptor(); + descriptor.setCalculatedFieldId(calculatedFieldId); + IotHubInstalledItem item = installedItem(UUID.randomUUID()); + item.setItemType("CALCULATED_FIELD"); + item.setItemVersionId(UUID.randomUUID()); + item.setDescriptor(descriptor); + when(iotHubInstalledItemService.findById(tenantId, item.getId())).thenReturn(item); + when(iotHubRestClient.getVersionInfo(anyString())) + .thenReturn(version(versionId, UUID.randomUUID().toString(), "CALCULATED_FIELD", "CF", "2.0")); + when(iotHubRestClient.getVersionFileData(versionId)).thenReturn(calculatedFieldFileData()); + CalculatedField existing = new CalculatedField(calculatedFieldId); + existing.setTenantId(tenantId); + when(calculatedFieldService.findById(tenantId, calculatedFieldId)).thenReturn(existing); + + UpdateItemVersionResult result = service.updateItemVersion(user, item.getId(), versionId, true, null); + + assertThat(result.isSuccess()).isTrue(); + ArgumentCaptor captor = ArgumentCaptor.forClass(CalculatedField.class); + verify(tbCalculatedFieldService).save(captor.capture(), eq(user)); + assertThat(((ArgumentsBasedCalculatedFieldConfiguration) captor.getValue().getConfiguration()).getArguments().get("T").getRefEntityId()).isEqualTo(tenantId); + } + + @Test + void doInstallVersion_alarmRule_mapsTenantReferencesToInstallingTenant() throws Exception { + mockTenant(); + String versionId = UUID.randomUUID().toString(); + when(iotHubRestClient.getVersionInfo(versionId)) + .thenReturn(version(versionId, UUID.randomUUID().toString(), "ALARM_RULE", "Alarm", "1.0")); + when(iotHubRestClient.getVersionFileData(versionId)).thenReturn(alarmRuleFileData()); + when(tbCalculatedFieldService.save(any(), eq(user))).thenAnswer(invocation -> invocation.getArgument(0)); + when(iotHubInstalledItemService.save(eq(tenantId), any())).thenAnswer(invocation -> invocation.getArgument(1)); + + service.doInstallVersion(user, versionId, null, null); + + ArgumentCaptor captor = ArgumentCaptor.forClass(CalculatedField.class); + verify(tbCalculatedFieldService).save(captor.capture(), eq(user)); + assertThat(((ArgumentsBasedCalculatedFieldConfiguration) captor.getValue().getConfiguration()).getArguments().get("T").getRefEntityId()).isEqualTo(tenantId); + } + + @Test + void updateItemVersion_alarmRule_mapsTenantReferencesToInstallingTenant() throws Exception { + mockTenant(); + String versionId = UUID.randomUUID().toString(); + CalculatedFieldId calculatedFieldId = new CalculatedFieldId(UUID.randomUUID()); + AlarmRuleInstalledItemDescriptor descriptor = new AlarmRuleInstalledItemDescriptor(); + descriptor.setCalculatedFieldId(calculatedFieldId); + IotHubInstalledItem item = installedItem(UUID.randomUUID()); + item.setItemType("ALARM_RULE"); + item.setItemVersionId(UUID.randomUUID()); + item.setDescriptor(descriptor); + when(iotHubInstalledItemService.findById(tenantId, item.getId())).thenReturn(item); + when(iotHubRestClient.getVersionInfo(anyString())) + .thenReturn(version(versionId, UUID.randomUUID().toString(), "ALARM_RULE", "Alarm", "2.0")); + when(iotHubRestClient.getVersionFileData(versionId)).thenReturn(alarmRuleFileData()); + CalculatedField existing = new CalculatedField(calculatedFieldId); + existing.setTenantId(tenantId); + when(calculatedFieldService.findById(tenantId, calculatedFieldId)).thenReturn(existing); + + UpdateItemVersionResult result = service.updateItemVersion(user, item.getId(), versionId, true, null); + + assertThat(result.isSuccess()).isTrue(); + ArgumentCaptor captor = ArgumentCaptor.forClass(CalculatedField.class); + verify(tbCalculatedFieldService).save(captor.capture(), eq(user)); + assertThat(((ArgumentsBasedCalculatedFieldConfiguration) captor.getValue().getConfiguration()).getArguments().get("T").getRefEntityId()).isEqualTo(tenantId); + } + + @Test + void doInstallVersion_geofencingCalculatedField_mapsZoneGroupTenantReferencesToInstallingTenant() throws Exception { + mockTenant(); + String versionId = UUID.randomUUID().toString(); + when(iotHubRestClient.getVersionInfo(versionId)) + .thenReturn(version(versionId, UUID.randomUUID().toString(), "CALCULATED_FIELD", "Geofencing", "1.0")); + when(iotHubRestClient.getVersionFileData(versionId)).thenReturn(geofencingFileData()); + when(tbCalculatedFieldService.save(any(), eq(user))).thenAnswer(invocation -> invocation.getArgument(0)); + when(iotHubInstalledItemService.save(eq(tenantId), any())).thenAnswer(invocation -> invocation.getArgument(1)); + + service.doInstallVersion(user, versionId, null, null); + + ArgumentCaptor captor = ArgumentCaptor.forClass(CalculatedField.class); + verify(tbCalculatedFieldService).save(captor.capture(), eq(user)); + assertThat(((GeofencingCalculatedFieldConfiguration) captor.getValue().getConfiguration()).getZoneGroups().get("zones").getRefEntityId()).isEqualTo(tenantId); + } + + private byte[] calculatedFieldFileData() { + SimpleCalculatedFieldConfiguration configuration = new SimpleCalculatedFieldConfiguration(); + configuration.setArguments(Map.of("T", otherTenantArgument())); + configuration.setExpression("T"); + return fileData(CalculatedFieldType.SIMPLE, configuration); + } + + private byte[] alarmRuleFileData() { + AlarmCalculatedFieldConfiguration configuration = new AlarmCalculatedFieldConfiguration(); + configuration.setArguments(Map.of("T", otherTenantArgument())); + configuration.setCreateRules(Map.of()); + return fileData(CalculatedFieldType.ALARM, configuration); + } + + private byte[] geofencingFileData() { + ZoneGroupConfiguration zoneGroup = new ZoneGroupConfiguration("perimeter", GeofencingReportStrategy.REPORT_PRESENCE_STATUS_ONLY, false); + zoneGroup.setRefEntityId(TenantId.fromUUID(UUID.randomUUID())); + GeofencingCalculatedFieldConfiguration configuration = new GeofencingCalculatedFieldConfiguration(); + configuration.setEntityCoordinates(new EntityCoordinates("latitude", "longitude")); + configuration.setZoneGroups(Map.of("zones", zoneGroup)); + configuration.setOutput(new TimeSeriesOutput()); + return fileData(CalculatedFieldType.GEOFENCING, configuration); + } + + private Argument otherTenantArgument() { + Argument argument = new Argument(); + argument.setRefEntityId(TenantId.fromUUID(UUID.randomUUID())); + argument.setRefEntityKey(new ReferencedEntityKey("temperature", ArgumentType.TS_LATEST, null)); + return argument; + } + + private byte[] fileData(CalculatedFieldType type, CalculatedFieldConfiguration configuration) { + CalculatedField calculatedField = new CalculatedField(); + calculatedField.setEntityId(new DeviceId(UUID.randomUUID())); + calculatedField.setType(type); + calculatedField.setName("CF"); + calculatedField.setConfiguration(configuration); + return JacksonUtil.toString(calculatedField).getBytes(StandardCharsets.UTF_8); + } + @Test void deleteInstalledItem_devicePackage_removesEachEntityBeforeWhatItRefersTo() throws Exception { mockTenant(); @@ -482,6 +653,9 @@ class DefaultIotHubServiceTest { profile.setDefaultDashboardId(dashboard.getId()); Integration integration = new Integration(new IntegrationId(UUID.randomUUID())); Converter converter = new Converter(new ConverterId(UUID.randomUUID())); + profile.setTenantId(tenantId); + dashboard.setTenantId(tenantId); + integration.setTenantId(tenantId); converter.setTenantId(tenantId); // The profile and the integration listed first: in reverse order of creation, the dashboard would go before the // profile that refers to it, and the converter before the integration that uses it. @@ -516,6 +690,7 @@ class DefaultIotHubServiceTest { when(iotHubInstalledItemService.findByTenantId(eq(tenantId), eq(List.of("DEVICE")), isNull(), any())) .thenReturn(new PageData<>(List.of(deleted, other), 1, 2, false)); Device device = new Device(deviceId); + device.setTenantId(tenantId); when(deviceService.findDeviceById(tenantId, deviceId)).thenReturn(device); service.deleteInstalledItem(user, deleted.getId()); @@ -661,6 +836,12 @@ class DefaultIotHubServiceTest { when(iotHubInstalledItemService.findById(tenantId, checked.getId())).thenReturn(checked); when(iotHubInstalledItemService.findByTenantId(eq(tenantId), eq(List.of("DEVICE")), isNull(), any())) .thenReturn(new PageData<>(List.of(checked, first, second, unrelated), 1, 4, false)); + DeviceProfile sharedProfile = new DeviceProfile(sharedProfileId); + sharedProfile.setTenantId(tenantId); + when(deviceProfileService.findDeviceProfileById(tenantId, sharedProfileId)).thenReturn(sharedProfile); + Dashboard sharedDashboard = new Dashboard(sharedDashboardId); + sharedDashboard.setTenantId(tenantId); + when(dashboardService.findDashboardById(tenantId, sharedDashboardId)).thenReturn(sharedDashboard); when(entityService.fetchEntityName(tenantId, sharedProfileId)).thenReturn(Optional.of("Shared profile")); when(entityService.fetchEntityName(tenantId, sharedDashboardId)).thenReturn(Optional.of("Shared dashboard")); @@ -683,6 +864,7 @@ class DefaultIotHubServiceTest { when(iotHubInstalledItemService.findByTenantId(eq(tenantId), eq(List.of("DEVICE")), isNull(), any())) .thenReturn(new PageData<>(List.of(deleted), 1, 1, false)); Device device = new Device(deviceId); + device.setTenantId(tenantId); when(deviceService.findDeviceById(tenantId, deviceId)).thenReturn(device); service.deleteInstalledItem(user, deleted.getId()); @@ -700,6 +882,9 @@ class DefaultIotHubServiceTest { when(iotHubInstalledItemService.findById(tenantId, checked.getId())).thenReturn(checked); when(iotHubInstalledItemService.findByTenantId(eq(tenantId), eq(List.of("DEVICE")), isNull(), any())) .thenReturn(new PageData<>(List.of(checked), 1, 1, false)); + Dashboard usersDashboard = new Dashboard(usersDashboardId); + usersDashboard.setTenantId(tenantId); + when(dashboardService.findDashboardById(tenantId, usersDashboardId)).thenReturn(usersDashboard); when(entityService.fetchEntityName(tenantId, usersDashboardId)).thenReturn(Optional.of("My dashboard")); InstalledItemKeptEntities kept = service.findKeptEntities(tenantId, checked.getId()); @@ -810,8 +995,13 @@ class DefaultIotHubServiceTest { @Test void findKeptEntities_devicePackage_namesTheProfileDevicesUseAndWhatItRefersTo_apartFromTheShared() { DeviceProfile profile = new DeviceProfile(new DeviceProfileId(UUID.randomUUID())); - RuleChainId ruleChainId = new RuleChainId(UUID.randomUUID()); - DashboardId dashboardId = new DashboardId(UUID.randomUUID()); + profile.setTenantId(tenantId); + RuleChain ruleChain = new RuleChain(new RuleChainId(UUID.randomUUID())); + ruleChain.setTenantId(tenantId); + RuleChainId ruleChainId = ruleChain.getId(); + Dashboard dashboard = new Dashboard(new DashboardId(UUID.randomUUID())); + dashboard.setTenantId(tenantId); + DashboardId dashboardId = dashboard.getId(); profile.setDefaultRuleChainId(ruleChainId); profile.setDefaultDashboardId(dashboardId); // The user's, not the package's: not listed @@ -827,6 +1017,8 @@ class DefaultIotHubServiceTest { .thenReturn(new PageData<>(List.of(), 3, 3, true)); when(deviceService.findDeviceById(tenantId, packageDevice.getId())).thenReturn(packageDevice); when(deviceProfileService.findDeviceProfileById(tenantId, profile.getId())).thenReturn(profile); + when(ruleChainService.findRuleChainById(tenantId, ruleChainId)).thenReturn(ruleChain); + when(dashboardService.findDashboardById(tenantId, dashboardId)).thenReturn(dashboard); when(entityService.fetchEntityName(tenantId, profile.getId())).thenReturn(Optional.of("smartico-l2-lr")); when(entityService.fetchEntityName(tenantId, ruleChainId)).thenReturn(Optional.of("Smartico L2-LR")); when(entityService.fetchEntityName(tenantId, dashboardId)).thenReturn(Optional.of("Smartico L2-LR Fleet")); @@ -950,6 +1142,7 @@ class DefaultIotHubServiceTest { private List deleteRuleChainFailingWith(Exception failure) throws Exception { mockTenant(); RuleChain ruleChain = new RuleChain(new RuleChainId(UUID.randomUUID())); + ruleChain.setTenantId(tenantId); IotHubInstalledItem deleted = devicePackage(ruleChain.getId()); when(iotHubInstalledItemService.findById(tenantId, deleted.getId())).thenReturn(deleted); when(iotHubInstalledItemService.findByTenantId(eq(tenantId), eq(List.of("DEVICE")), isNull(), any())) @@ -986,4 +1179,184 @@ class DefaultIotHubServiceTest { return item; } + private Dashboard dashboard(TenantId owner) { + Dashboard dashboard = new Dashboard(new DashboardId(UUID.randomUUID())); + dashboard.setTenantId(owner); + return dashboard; + } + + private Device device(TenantId owner) { + Device device = new Device(new DeviceId(UUID.randomUUID())); + device.setTenantId(owner); + return device; + } + + private DeviceInstalledItemDescriptor devicePackageDescriptor(EntityId... createdEntityIds) { + DeviceInstalledItemDescriptor descriptor = new DeviceInstalledItemDescriptor(); + descriptor.setCreatedEntityIds(List.of(createdEntityIds)); + return descriptor; + } + + @Test + void registerDeviceInstall_unknownEntity_rejectedAndNotSaved() { + mockTenant(); + String versionId = UUID.randomUUID().toString(); + when(iotHubRestClient.getVersionInfo(versionId)) + .thenReturn(version(versionId, UUID.randomUUID().toString(), "DEVICE", "Pkg", "1.0")); + Device knownDevice = device(tenantId); + Dashboard unknownDashboard = dashboard(TenantId.fromUUID(UUID.randomUUID())); + when(deviceService.findDeviceById(tenantId, knownDevice.getId())).thenReturn(knownDevice); + when(dashboardService.findDashboardById(tenantId, unknownDashboard.getId())).thenReturn(unknownDashboard); + + InstallItemVersionResult result = service.registerDeviceInstall(user, versionId, + devicePackageDescriptor(knownDevice.getId(), unknownDashboard.getId())); + + assertThat(result.isSuccess()).isFalse(); + verify(iotHubInstalledItemService, never()).save(any(), any()); + verify(tbDeviceService, never()).delete(any(Device.class), any()); + verify(tbDashboardService, never()).delete(any(Dashboard.class), any()); + } + + @Test + void registerDeviceInstall_unknownDashboardId_rejectedAndNotSaved() { + mockTenant(); + String versionId = UUID.randomUUID().toString(); + when(iotHubRestClient.getVersionInfo(versionId)) + .thenReturn(version(versionId, UUID.randomUUID().toString(), "DEVICE", "Pkg", "1.0")); + Dashboard unknownDashboard = dashboard(TenantId.fromUUID(UUID.randomUUID())); + when(dashboardService.findDashboardById(tenantId, unknownDashboard.getId())).thenReturn(unknownDashboard); + DeviceInstalledItemDescriptor descriptor = devicePackageDescriptor(); + descriptor.setDashboardId(unknownDashboard.getId()); + + InstallItemVersionResult result = service.registerDeviceInstall(user, versionId, descriptor); + + assertThat(result.isSuccess()).isFalse(); + verify(iotHubInstalledItemService, never()).save(any(), any()); + } + + @Test + void registerDeviceInstall_knownEntities_saved() { + mockTenant(); + String versionId = UUID.randomUUID().toString(); + when(iotHubRestClient.getVersionInfo(versionId)) + .thenReturn(version(versionId, UUID.randomUUID().toString(), "DEVICE", "Pkg", "1.0")); + Device knownDevice = device(tenantId); + Dashboard knownDashboard = dashboard(tenantId); + when(deviceService.findDeviceById(tenantId, knownDevice.getId())).thenReturn(knownDevice); + when(dashboardService.findDashboardById(tenantId, knownDashboard.getId())).thenReturn(knownDashboard); + DeviceInstalledItemDescriptor descriptor = devicePackageDescriptor(knownDevice.getId(), knownDashboard.getId()); + descriptor.setDashboardId(knownDashboard.getId()); + when(iotHubInstalledItemService.save(eq(tenantId), any())).thenAnswer(inv -> inv.getArgument(1)); + + InstallItemVersionResult result = service.registerDeviceInstall(user, versionId, descriptor); + + assertThat(result.isSuccess()).isTrue(); + verify(iotHubInstalledItemService).save(eq(tenantId), any(IotHubInstalledItem.class)); + } + + @Test + void deleteInstalledItem_devicePackage_skipsEntityNotFound() throws Exception { + mockTenant(); + Device knownDevice = device(tenantId); + Dashboard unknownDashboard = dashboard(TenantId.fromUUID(UUID.randomUUID())); + when(deviceService.findDeviceById(tenantId, knownDevice.getId())).thenReturn(knownDevice); + when(dashboardService.findDashboardById(tenantId, unknownDashboard.getId())).thenReturn(unknownDashboard); + UUID id = UUID.randomUUID(); + IotHubInstalledItem item = installedItem(id); + item.setDescriptor(devicePackageDescriptor(knownDevice.getId(), unknownDashboard.getId())); + when(iotHubInstalledItemService.findById(tenantId, new IotHubInstalledItemId(id))).thenReturn(item); + when(iotHubInstalledItemService.findByTenantId(eq(tenantId), eq(List.of("DEVICE")), isNull(), any())) + .thenReturn(new PageData<>(List.of(item), 1, 1, false)); + + service.deleteInstalledItem(user, new IotHubInstalledItemId(id)); + + verify(tbDeviceService).delete(knownDevice, user); + verify(tbDashboardService, never()).delete(any(Dashboard.class), any()); + verify(iotHubInstalledItemService).deleteById(tenantId, new IotHubInstalledItemId(id)); + } + + @Test + void deleteInstalledItem_devicePackage_deletesItsIntegrationAndConverter() throws Exception { + mockTenant(); + Integration integration = new Integration(new IntegrationId(UUID.randomUUID())); + integration.setTenantId(tenantId); + Converter converter = new Converter(new ConverterId(UUID.randomUUID())); + converter.setTenantId(tenantId); + Integration unknownIntegration = new Integration(new IntegrationId(UUID.randomUUID())); + unknownIntegration.setTenantId(TenantId.fromUUID(UUID.randomUUID())); + when(integrationService.findIntegrationById(tenantId, integration.getId())).thenReturn(integration); + when(integrationService.findIntegrationById(tenantId, unknownIntegration.getId())).thenReturn(unknownIntegration); + when(converterService.findConverterById(tenantId, converter.getId())).thenReturn(converter); + UUID id = UUID.randomUUID(); + IotHubInstalledItem item = installedItem(id); + item.setDescriptor(devicePackageDescriptor(converter.getId(), integration.getId(), unknownIntegration.getId())); + when(iotHubInstalledItemService.findById(tenantId, new IotHubInstalledItemId(id))).thenReturn(item); + when(iotHubInstalledItemService.findByTenantId(eq(tenantId), eq(List.of("DEVICE")), isNull(), any())) + .thenReturn(new PageData<>(List.of(item), 1, 1, false)); + + service.deleteInstalledItem(user, new IotHubInstalledItemId(id)); + + verify(integrationService).deleteIntegration(tenantId, integration.getId()); + verify(integrationService, never()).deleteIntegration(tenantId, unknownIntegration.getId()); + verify(tbConverterService).delete(converter, user); + verify(iotHubInstalledItemService).deleteById(tenantId, new IotHubInstalledItemId(id)); + } + + @Test + void registerDeviceInstall_usedExistingEntityOfAnotherTenant_rejectedAndNotSaved() { + mockTenant(); + String versionId = UUID.randomUUID().toString(); + when(iotHubRestClient.getVersionInfo(versionId)) + .thenReturn(version(versionId, UUID.randomUUID().toString(), "DEVICE", "Pkg", "1.0")); + Device knownDevice = device(tenantId); + when(deviceService.findDeviceById(tenantId, knownDevice.getId())).thenReturn(knownDevice); + Dashboard otherTenantDashboard = dashboard(TenantId.fromUUID(UUID.randomUUID())); + when(dashboardService.findDashboardById(tenantId, otherTenantDashboard.getId())).thenReturn(otherTenantDashboard); + DeviceInstalledItemDescriptor descriptor = devicePackageDescriptor(knownDevice.getId()); + descriptor.setUsedExistingEntityIds(List.of(otherTenantDashboard.getId())); + + InstallItemVersionResult result = service.registerDeviceInstall(user, versionId, descriptor); + + assertThat(result.isSuccess()).isFalse(); + verify(iotHubInstalledItemService, never()).save(any(), any()); + } + + @Test + void deleteInstalledItem_devicePackage_leavesTheIntegrationOfAnotherTenantAsItIs() { + mockTenant(); + IntegrationId integrationId = new IntegrationId(UUID.randomUUID()); + IotHubInstalledItem deleted = devicePackage(integrationId); + setIntegrationState(deleted, integrationId, Map.of("profile.milesight-iot-am308", "am308-custom")); + ((DeviceInstalledItemDescriptor) deleted.getDescriptor()).setUsedExistingEntityIds(List.of(integrationId)); + when(iotHubInstalledItemService.findById(tenantId, deleted.getId())).thenReturn(deleted); + when(iotHubInstalledItemService.findByTenantId(eq(tenantId), eq(List.of("DEVICE")), isNull(), any())) + .thenReturn(new PageData<>(List.of(deleted), 1, 1, false)); + Integration otherTenantIntegration = integration(integrationId, Map.of("profile.milesight-iot-am308", "am308-custom")); + otherTenantIntegration.setTenantId(TenantId.fromUUID(UUID.randomUUID())); + when(integrationService.findIntegrationById(tenantId, integrationId)).thenReturn(otherTenantIntegration); + + service.deleteInstalledItem(user, deleted.getId()); + + verify(integrationService, never()).saveIntegration(any()); + verify(integrationService, never()).deleteIntegration(any(), any()); + } + + @Test + void findKeptEntities_devicePackage_namesNoEntityOfAnotherTenant() { + DashboardId otherTenantDashboardId = new DashboardId(UUID.randomUUID()); + IotHubInstalledItem checked = devicePackage(new DeviceId(UUID.randomUUID()), otherTenantDashboardId); + ((DeviceInstalledItemDescriptor) checked.getDescriptor()).setUsedExistingEntityIds(List.of(otherTenantDashboardId)); + when(iotHubInstalledItemService.findById(tenantId, checked.getId())).thenReturn(checked); + when(iotHubInstalledItemService.findByTenantId(eq(tenantId), eq(List.of("DEVICE")), isNull(), any())) + .thenReturn(new PageData<>(List.of(checked), 1, 1, false)); + Dashboard otherTenantDashboard = new Dashboard(otherTenantDashboardId); + otherTenantDashboard.setTenantId(TenantId.fromUUID(UUID.randomUUID())); + when(dashboardService.findDashboardById(tenantId, otherTenantDashboardId)).thenReturn(otherTenantDashboard); + + InstalledItemKeptEntities kept = service.findKeptEntities(tenantId, checked.getId()); + + assertThat(kept.getEntities()).containsExactly(new InstalledItemKeptEntities.KeptEntity(otherTenantDashboardId, null)); + verify(entityService, never()).fetchEntityName(any(), any()); + } + } diff --git a/application/src/test/java/org/thingsboard/server/service/notification/NotificationApiTest.java b/application/src/test/java/org/thingsboard/server/service/notification/NotificationApiTest.java index 9b91c00669..fc79a220d6 100644 --- a/application/src/test/java/org/thingsboard/server/service/notification/NotificationApiTest.java +++ b/application/src/test/java/org/thingsboard/server/service/notification/NotificationApiTest.java @@ -1123,6 +1123,42 @@ public class NotificationApiTest extends AbstractNotificationApiTest { assertThat(getAvailableDeliveryMethods()).doesNotContain(NotificationDeliveryMethod.MOBILE_APP); } + @Test + public void testNotificationRequest_templateOfOtherTenant_returnsBadRequest() throws Exception { + loginDifferentTenant(); + NotificationTemplate otherTemplate = createNotificationTemplate(NotificationType.GENERAL, "Subject", "Text", NotificationDeliveryMethod.WEB); + loginTenantAdmin(); + NotificationTarget target = createNotificationTarget(tenantAdminUserId); + long requestsCount = findNotificationRequests().getTotalElements(); + + NotificationRequest notificationRequest = NotificationRequest.builder() + .targets(List.of(target.getUuidId())) + .templateId(otherTemplate.getId()) + .additionalConfig(new NotificationRequestConfig()) + .build(); + doPost("/api/notification/request", notificationRequest).andExpect(status().isBadRequest()); + + assertThat(findNotificationRequests().getTotalElements()).isEqualTo(requestsCount); + } + + @Test + public void testNotificationRequest_systemTemplate_isDelivered() throws Exception { + loginSysAdmin(); + NotificationTemplate systemTemplate = createNotificationTemplate(NotificationType.GENERAL, "Subject", "Text", NotificationDeliveryMethod.WEB); + loginTenantAdmin(); + NotificationTarget target = createNotificationTarget(tenantAdminUserId); + + NotificationRequest notificationRequest = NotificationRequest.builder() + .tenantId(tenantId) + .templateId(systemTemplate.getId()) + .originatorEntityId(tenantAdminUserId) + .targets(List.of(target.getUuidId())) + .build(); + NotificationRequestStats stats = submitNotificationRequestAndWait(notificationRequest); + assertThat(stats.getErrors()).isEmpty(); + assertThat(stats.getSent().get(NotificationDeliveryMethod.WEB).get()).isOne(); + } + private NotificationRequestStats submitNotificationRequestAndWait(NotificationRequest notificationRequest) throws Exception { SettableFuture future = SettableFuture.create(); notificationCenter.processNotificationRequest(notificationRequest.getTenantId(), notificationRequest, new FutureCallback<>() { diff --git a/application/src/test/java/org/thingsboard/server/service/notification/NotificationRuleApiTest.java b/application/src/test/java/org/thingsboard/server/service/notification/NotificationRuleApiTest.java index 93bf08af0a..fb45e6c772 100644 --- a/application/src/test/java/org/thingsboard/server/service/notification/NotificationRuleApiTest.java +++ b/application/src/test/java/org/thingsboard/server/service/notification/NotificationRuleApiTest.java @@ -46,6 +46,7 @@ import org.thingsboard.server.common.data.device.data.DeviceData; import org.thingsboard.server.common.data.edge.Edge; import org.thingsboard.server.common.data.id.AlarmId; import org.thingsboard.server.common.data.id.DeviceId; +import org.thingsboard.server.common.data.id.NotificationTemplateId; import org.thingsboard.server.common.data.id.TenantId; import org.thingsboard.server.common.data.limit.LimitedApi; import org.thingsboard.server.common.data.notification.Notification; @@ -899,6 +900,136 @@ public class NotificationRuleApiTest extends AbstractNotificationApiTest { }); } + @Test + public void testSaveNotificationRule_templateOfOtherTenant_returnsBadRequest() throws Exception { + loginDifferentTenant(); + NotificationTemplate otherTemplate = createNotificationTemplate(NotificationType.ENTITY_ACTION, "Created", "Created", NotificationDeliveryMethod.WEB); + loginTenantAdmin(); + NotificationTarget target = createNotificationTarget(tenantAdminUserId); + + NotificationRule rule = newDeviceCreatedRule(otherTemplate.getId(), List.of(target.getUuidId())); + doPost("/api/notification/rule", rule).andExpect(status().isBadRequest()); + + assertThat(findNotificationRules().getData()).extracting(NotificationRuleInfo::getName).doesNotContain(rule.getName()); + } + + @Test + public void testSaveNotificationRule_targetOfOtherTenant_returnsForbidden() throws Exception { + loginDifferentTenant(); + NotificationTarget otherTarget = createNotificationTarget(savedDifferentTenantUser.getId()); + loginTenantAdmin(); + NotificationTemplate template = createNotificationTemplate(NotificationType.ENTITY_ACTION, "Created", "Created", NotificationDeliveryMethod.WEB); + + NotificationRule rule = newDeviceCreatedRule(template.getId(), List.of(otherTarget.getUuidId())); + doPost("/api/notification/rule", rule).andExpect(status().isForbidden()); + + NotificationTemplate alarmTemplate = createNotificationTemplate(NotificationType.ALARM, "Alarm", "Alarm", NotificationDeliveryMethod.WEB); + NotificationTarget ownTarget = createNotificationTarget(tenantAdminUserId); + NotificationRule alarmRule = new NotificationRule(); + alarmRule.setName("Alarm rule " + UUID.randomUUID()); + alarmRule.setEnabled(true); + alarmRule.setTemplateId(alarmTemplate.getId()); + alarmRule.setTriggerType(NotificationRuleTriggerType.ALARM); + AlarmNotificationRuleTriggerConfig triggerConfig = new AlarmNotificationRuleTriggerConfig(); + triggerConfig.setNotifyOn(Set.of(AlarmAction.CREATED)); + alarmRule.setTriggerConfig(triggerConfig); + EscalatedNotificationRuleRecipientsConfig recipientsConfig = new EscalatedNotificationRuleRecipientsConfig(); + recipientsConfig.setEscalationTable(Map.of( + 0, List.of(ownTarget.getUuidId()), + 60, List.of(otherTarget.getUuidId()) + )); + alarmRule.setRecipientsConfig(recipientsConfig); + doPost("/api/notification/rule", alarmRule).andExpect(status().isForbidden()); + + assertThat(findNotificationRules().getData()).extracting(NotificationRuleInfo::getName) + .doesNotContain(rule.getName(), alarmRule.getName()); + } + + @Test + public void testSaveNotificationRule_systemTemplate_isSaved() throws Exception { + loginSysAdmin(); + NotificationTemplate systemTemplate = createNotificationTemplate(NotificationType.ENTITY_ACTION, "Created", "Created", NotificationDeliveryMethod.WEB); + loginTenantAdmin(); + NotificationTarget target = createNotificationTarget(tenantAdminUserId); + + NotificationRule rule = saveNotificationRule(newDeviceCreatedRule(systemTemplate.getId(), List.of(target.getUuidId()))); + + try { + assertThat(rule.getId()).isNotNull(); + assertThat(rule.getTemplateId()).isEqualTo(systemTemplate.getId()); + } finally { + // the rule references a system template, which afterEach deletes before the tenant + notificationRuleService.deleteNotificationRuleById(tenantId, rule.getId()); + } + } + + @Test + public void testSaveNotificationRule_nonExistentTarget_returnsNotFound() throws Exception { + NotificationTemplate template = createNotificationTemplate(NotificationType.ENTITY_ACTION, "Created", "Created", NotificationDeliveryMethod.WEB); + + NotificationRule rule = newDeviceCreatedRule(template.getId(), List.of(UUID.randomUUID())); + doPost("/api/notification/rule", rule).andExpect(status().isNotFound()); + + assertThat(findNotificationRules().getData()).extracting(NotificationRuleInfo::getName).doesNotContain(rule.getName()); + } + + @Test + public void testRuleProcessing_deliversOnlyToTargetsOfRuleTenant() throws Exception { + loginDifferentTenant(); + NotificationTarget otherTarget = createNotificationTarget(savedDifferentTenantUser.getId()); + loginTenantAdmin(); + NotificationTemplate template = createNotificationTemplate(NotificationType.ENTITY_ACTION, "Device created", "Device created", NotificationDeliveryMethod.WEB); + NotificationTarget ownTarget = createNotificationTarget(tenantAdminUserId); + + NotificationRule rule = newDeviceCreatedRule(template.getId(), List.of(ownTarget.getUuidId(), otherTarget.getUuidId())); + rule.setTenantId(tenantId); + notificationRuleService.saveNotificationRule(tenantId, rule); + notificationRulesCache.evict(tenantId); + + createDevice("Device 1", "default", "111"); + await().atMost(TIMEOUT, TimeUnit.SECONDS) + .untilAsserted(() -> assertThat(getMyNotifications(false, 100)).extracting(Notification::getSubject).contains("Device created")); + + loginDifferentTenant(); + await().during(3, TimeUnit.SECONDS).atMost(5, TimeUnit.SECONDS) + .untilAsserted(() -> assertThat(getMyNotifications(false, 100)).extracting(Notification::getSubject).doesNotContain("Device created")); + } + + @Test + public void testRuleProcessing_templateOfOtherTenant_deliversNothing() throws Exception { + loginDifferentTenant(); + NotificationTemplate otherTemplate = createNotificationTemplate(NotificationType.ENTITY_ACTION, "Device created", "Device created", NotificationDeliveryMethod.WEB); + loginTenantAdmin(); + NotificationTarget target = createNotificationTarget(tenantAdminUserId); + + NotificationRule rule = newDeviceCreatedRule(otherTemplate.getId(), List.of(target.getUuidId())); + rule.setTenantId(tenantId); + notificationRuleService.saveNotificationRule(tenantId, rule); + notificationRulesCache.evict(tenantId); + + createDevice("Device 1", "default", "111"); + await().during(3, TimeUnit.SECONDS).atMost(5, TimeUnit.SECONDS) + .untilAsserted(() -> assertThat(getMyNotifications(false, 100)).extracting(Notification::getSubject).doesNotContain("Device created")); + } + + private NotificationRule newDeviceCreatedRule(NotificationTemplateId templateId, List targets) { + EntityActionNotificationRuleTriggerConfig triggerConfig = new EntityActionNotificationRuleTriggerConfig(); + triggerConfig.setEntityTypes(Set.of(EntityType.DEVICE)); + triggerConfig.setCreated(true); + + NotificationRule rule = new NotificationRule(); + rule.setName("Device created " + UUID.randomUUID()); + rule.setEnabled(true); + rule.setTemplateId(templateId); + rule.setTriggerType(NotificationRuleTriggerType.ENTITY_ACTION); + rule.setTriggerConfig(triggerConfig); + + DefaultNotificationRuleRecipientsConfig recipientsConfig = DefaultNotificationRuleRecipientsConfig.forTriggerType(NotificationRuleTriggerType.ENTITY_ACTION); + recipientsConfig.setTargets(targets); + rule.setRecipientsConfig(recipientsConfig); + return rule; + } + private R checkNotificationAfter(Callable action, BiConsumer check) throws Exception { if (getWsClient().getLastDataUpdate() == null) { getWsClient().subscribeForUnreadNotifications(10).waitForReply(true); diff --git a/application/src/test/java/org/thingsboard/server/service/notification/NotificationTemplateApiTest.java b/application/src/test/java/org/thingsboard/server/service/notification/NotificationTemplateApiTest.java index 8df57c6a2a..e8ed81a632 100644 --- a/application/src/test/java/org/thingsboard/server/service/notification/NotificationTemplateApiTest.java +++ b/application/src/test/java/org/thingsboard/server/service/notification/NotificationTemplateApiTest.java @@ -9,9 +9,18 @@ import org.junit.Before; import org.junit.Test; import org.springframework.test.web.servlet.ResultActions; import org.springframework.test.web.servlet.ResultMatcher; +import org.thingsboard.server.common.data.EntityType; import org.thingsboard.server.common.data.id.IdBased; +import org.thingsboard.server.common.data.id.UserId; import org.thingsboard.server.common.data.notification.NotificationDeliveryMethod; +import org.thingsboard.server.common.data.notification.NotificationRequest; +import org.thingsboard.server.common.data.notification.NotificationRequestConfig; import org.thingsboard.server.common.data.notification.NotificationType; +import org.thingsboard.server.common.data.notification.rule.DefaultNotificationRuleRecipientsConfig; +import org.thingsboard.server.common.data.notification.rule.NotificationRule; +import org.thingsboard.server.common.data.notification.rule.NotificationRuleInfo; +import org.thingsboard.server.common.data.notification.rule.trigger.config.EntityActionNotificationRuleTriggerConfig; +import org.thingsboard.server.common.data.notification.targets.NotificationTarget; import org.thingsboard.server.common.data.notification.template.EmailDeliveryMethodNotificationTemplate; import org.thingsboard.server.common.data.notification.template.NotificationTemplate; import org.thingsboard.server.common.data.notification.template.NotificationTemplateConfig; @@ -21,6 +30,7 @@ import org.thingsboard.server.dao.service.DaoSqlTest; import java.util.List; import java.util.Map; +import java.util.Set; import static org.assertj.core.api.Assertions.assertThat; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; @@ -86,6 +96,91 @@ public class NotificationTemplateApiTest extends AbstractNotificationApiTest { .containsOnly(generalNotificationTemplate.getId(), alarmNotificationTemplate.getId(), entityActionNotificationTemplate.getId()); } + @Test + public void testSaveTemplateWithReportRequiresPermissionOverReportUser() throws Exception { + UserId otherTenantUserId = getDifferentTenantUserId(); + + NotificationTemplate notificationTemplate = buildTemplateWithReport(otherTenantUserId); + save(notificationTemplate, status().isForbidden()); + + notificationTemplate.getConfiguration().setUserId(tenantAdminUserId); + save(notificationTemplate, status().isOk()); + } + + @Test + public void testNotificationRequestWithReportRequiresPermissionOverReportUser() throws Exception { + UserId otherTenantUserId = getDifferentTenantUserId(); + NotificationTarget target = createNotificationTarget(tenantAdminUserId); + + NotificationRequest inlineTemplateRequest = NotificationRequest.builder() + .targets(List.of(target.getUuidId())) + .template(buildTemplateWithReport(otherTenantUserId)) + .additionalConfig(new NotificationRequestConfig()) + .build(); + doPost("/api/notification/request", inlineTemplateRequest).andExpect(status().isForbidden()); + + NotificationTemplate storedTemplate = saveTemplateWithReportUser(otherTenantUserId); + NotificationRequest storedTemplateRequest = NotificationRequest.builder() + .targets(List.of(target.getUuidId())) + .templateId(storedTemplate.getId()) + .additionalConfig(new NotificationRequestConfig()) + .build(); + doPost("/api/notification/request", storedTemplateRequest).andExpect(status().isForbidden()); + + assertThat(findNotificationRequests().getData()).isEmpty(); + } + + @Test + public void testSaveRuleWithReportTemplateRequiresPermissionOverReportUser() throws Exception { + UserId otherTenantUserId = getDifferentTenantUserId(); + NotificationTemplate storedTemplate = saveTemplateWithReportUser(otherTenantUserId); + + EntityActionNotificationRuleTriggerConfig triggerConfig = new EntityActionNotificationRuleTriggerConfig(); + triggerConfig.setEntityTypes(Set.of(EntityType.DEVICE)); + triggerConfig.setCreated(true); + NotificationRule rule = new NotificationRule(); + rule.setName("Device created"); + rule.setEnabled(true); + rule.setTemplateId(storedTemplate.getId()); + rule.setTriggerType(triggerConfig.getTriggerType()); + rule.setTriggerConfig(triggerConfig); + DefaultNotificationRuleRecipientsConfig recipientsConfig = DefaultNotificationRuleRecipientsConfig.forTriggerType(triggerConfig.getTriggerType()); + recipientsConfig.setTargets(List.of(createNotificationTarget(tenantAdminUserId).getUuidId())); + rule.setRecipientsConfig(recipientsConfig); + + doPost("/api/notification/rule", rule).andExpect(status().isForbidden()); + assertThat(findNotificationRules().getData()).extracting(NotificationRuleInfo::getName).doesNotContain(rule.getName()); + } + + private UserId getDifferentTenantUserId() throws Exception { + loginDifferentTenant(); + UserId userId = savedDifferentTenantUser.getId(); + loginTenantAdmin(); + return userId; + } + + private NotificationTemplate buildTemplateWithReport(UserId userId) { + NotificationTemplate notificationTemplate = new NotificationTemplate(); + notificationTemplate.setName("Template with report"); + notificationTemplate.setNotificationType(NotificationType.GENERAL); + NotificationTemplateConfig config = new NotificationTemplateConfig(); + EmailDeliveryMethodNotificationTemplate emailTemplate = new EmailDeliveryMethodNotificationTemplate(); + emailTemplate.setEnabled(true); + emailTemplate.setSubject("Report"); + emailTemplate.setBody("Report"); + config.setDeliveryMethodsTemplates(Map.of(NotificationDeliveryMethod.EMAIL, emailTemplate)); + config.setAttachReport(true); + config.setUserId(userId); + notificationTemplate.setConfiguration(config); + return notificationTemplate; + } + + private NotificationTemplate saveTemplateWithReportUser(UserId userId) { + NotificationTemplate notificationTemplate = buildTemplateWithReport(userId); + notificationTemplate.setTenantId(tenantId); + return notificationTemplateService.saveNotificationTemplate(tenantId, notificationTemplate); + } + private String saveAndGetError(NotificationTemplate notificationTemplate, ResultMatcher statusMatcher) throws Exception { return getErrorMessage(save(notificationTemplate, statusMatcher)); } diff --git a/application/src/test/java/org/thingsboard/server/service/resource/sql/BaseTbResourceServiceTest.java b/application/src/test/java/org/thingsboard/server/service/resource/sql/BaseTbResourceServiceTest.java index 2469f8b703..aacf9ccb84 100644 --- a/application/src/test/java/org/thingsboard/server/service/resource/sql/BaseTbResourceServiceTest.java +++ b/application/src/test/java/org/thingsboard/server/service/resource/sql/BaseTbResourceServiceTest.java @@ -358,6 +358,21 @@ public class BaseTbResourceServiceTest extends AbstractControllerTest { }); } + @Test + public void testSaveTbResourceWithUnknownIdIsRefused() { + TbResourceId resourceId = new TbResourceId(Uuids.timeBased()); + TbResource resource = new TbResource(); + resource.setId(resourceId); + resource.setResourceType(ResourceType.JS_MODULE); + resource.setTitle("My resource"); + resource.setFileName(DEFAULT_FILE_NAME); + + assertThatThrownBy(() -> tbResourceService.save(resource)) + .isInstanceOf(ThingsboardException.class) + .hasMessageContaining("wasn't found"); + assertThat(resourceService.findResourceInfoById(TenantId.SYS_TENANT_ID, resourceId)).isNull(); + } + @Test public void testSaveLwm2mTbResourceWithXXE() { TbResource resource = new TbResource(); diff --git a/application/src/test/java/org/thingsboard/server/service/scheduler/sql/SchedulerEventTest.java b/application/src/test/java/org/thingsboard/server/service/scheduler/sql/SchedulerEventTest.java index 4bc4fbed43..72de51dc2d 100644 --- a/application/src/test/java/org/thingsboard/server/service/scheduler/sql/SchedulerEventTest.java +++ b/application/src/test/java/org/thingsboard/server/service/scheduler/sql/SchedulerEventTest.java @@ -4,6 +4,8 @@ package org.thingsboard.server.service.scheduler.sql; import com.fasterxml.jackson.databind.node.ObjectNode; import com.google.common.util.concurrent.ListeningScheduledExecutorService; +import com.google.common.util.concurrent.MoreExecutors; +import org.awaitility.Awaitility; import org.junit.Before; import org.junit.Test; import org.mockito.Mockito; @@ -11,13 +13,22 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.util.ReflectionTestUtils; import org.thingsboard.common.util.JacksonUtil; import org.thingsboard.server.common.data.Device; +import org.thingsboard.server.common.data.DeviceProfileInfo; +import org.thingsboard.server.common.data.EntityType; +import org.thingsboard.server.common.data.OtaPackageInfo; +import org.thingsboard.server.common.data.SaveOtaPackageInfoRequest; +import org.thingsboard.server.common.data.group.EntityGroup; +import org.thingsboard.server.common.data.id.DeviceProfileId; import org.thingsboard.server.common.data.id.EntityId; import org.thingsboard.server.common.data.scheduler.SchedulerEvent; import org.thingsboard.server.controller.AbstractControllerTest; +import org.thingsboard.server.dao.ota.DeviceGroupOtaPackageService; import org.thingsboard.server.dao.service.DaoSqlTest; import org.thingsboard.server.queue.discovery.TbServiceInfoProvider; import org.thingsboard.server.service.scheduler.DefaultSchedulerService; +import java.util.Map; +import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; @@ -31,7 +42,9 @@ import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.timeout; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; +import static org.thingsboard.server.common.data.DataConstants.UPDATE_FIRMWARE; import static org.thingsboard.server.common.data.msg.TbMsgType.RPC_CALL_FROM_SERVER_TO_DEVICE; +import static org.thingsboard.server.common.data.ota.OtaPackageType.FIRMWARE; import static org.thingsboard.server.dao.scheduler.BaseSchedulerEventService.getOriginatorId; @DaoSqlTest @@ -43,6 +56,9 @@ public class SchedulerEventTest extends AbstractControllerTest { @Autowired TbServiceInfoProvider serviceInfoProvider; + @Autowired + DeviceGroupOtaPackageService deviceGroupOtaPackageService; + @Before public void before() throws Exception { loginTenantAdmin(); @@ -126,6 +142,52 @@ public class SchedulerEventTest extends AbstractControllerTest { ), any()); } + @Test + public void shouldNotUpdateFirmwareOfDeviceGroupOfAnotherTenant() throws Exception { + DeviceProfileInfo deviceProfile = doGet("/api/deviceProfileInfo/default", DeviceProfileInfo.class); + SaveOtaPackageInfoRequest firmwareRequest = new SaveOtaPackageInfoRequest(); + firmwareRequest.setDeviceProfileId(new DeviceProfileId(deviceProfile.getId().getId())); + firmwareRequest.setType(FIRMWARE); + firmwareRequest.setTitle("My firmware"); + firmwareRequest.setVersion("v1.0"); + firmwareRequest.setUsesUrl(false); + OtaPackageInfo firmware = doPost("/api/otaPackage", firmwareRequest, OtaPackageInfo.class); + + loginDifferentTenant(); + EntityGroup otherTenantGroup = new EntityGroup(); + otherTenantGroup.setName("Other Tenant Devices"); + otherTenantGroup.setType(EntityType.DEVICE); + otherTenantGroup = doPost("/api/entityGroup", otherTenantGroup, EntityGroup.class); + loginTenantAdmin(); + + Object originalExecutor = ReflectionTestUtils.getField(schedulerService, "scheduledExecutor"); + ListeningScheduledExecutorService executor = MoreExecutors.listeningDecorator(Executors.newSingleThreadScheduledExecutor()); + ReflectionTestUtils.setField(schedulerService, "scheduledExecutor", executor); + try { + SchedulerEvent schedulerEvent = new SchedulerEvent(); + schedulerEvent.setName("Firmware update"); + schedulerEvent.setType(UPDATE_FIRMWARE); + schedulerEvent.setEnabled(true); + ObjectNode schedule = JacksonUtil.newObjectNode(); + schedule.put("startTime", Long.MAX_VALUE); + schedule.put("timezone", "UTC"); + schedulerEvent.setSchedule(schedule); + schedulerEvent.setOriginatorId(otherTenantGroup.getId()); + ObjectNode configuration = JacksonUtil.newObjectNode(); + configuration.set("msgBody", JacksonUtil.valueToTree(firmware.getId())); + schedulerEvent.setConfiguration(configuration); + SchedulerEvent savedSchedulerEvent = doPost("/api/schedulerEvent", schedulerEvent, SchedulerEvent.class); + + Map eventsMetaData = (Map) ReflectionTestUtils.getField(schedulerService, "eventsMetaData"); + Awaitility.await().atMost(10, TimeUnit.SECONDS).until(() -> eventsMetaData.containsKey(savedSchedulerEvent.getId())); + ReflectionTestUtils.invokeMethod(schedulerService, "processEvent", tenantId, savedSchedulerEvent.getId()); + } finally { + ReflectionTestUtils.setField(schedulerService, "scheduledExecutor", originalExecutor); + executor.shutdownNow(); + } + assertThat(deviceGroupOtaPackageService.findDeviceGroupOtaPackageByGroupIdAndType(otherTenantGroup.getId(), FIRMWARE)).isNull(); + } + private SchedulerEvent createSchedulerEvent(EntityId originatorId, boolean enabled) { SchedulerEvent schedulerEvent = new SchedulerEvent(); schedulerEvent.setName("TestRpc"); diff --git a/application/src/test/java/org/thingsboard/server/service/security/auth/oauth2/CustomOAuth2ClientMapperTest.java b/application/src/test/java/org/thingsboard/server/service/security/auth/oauth2/CustomOAuth2ClientMapperTest.java new file mode 100644 index 0000000000..df66b09e1b --- /dev/null +++ b/application/src/test/java/org/thingsboard/server/service/security/auth/oauth2/CustomOAuth2ClientMapperTest.java @@ -0,0 +1,131 @@ +// SPDX-FileCopyrightText: Copyright The ThingsBoard Authors +// SPDX-License-Identifier: Apache-2.0 +package org.thingsboard.server.service.security.auth.oauth2; + +import com.sun.net.httpserver.HttpServer; +import jakarta.servlet.http.HttpServletRequest; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.springframework.security.oauth2.client.authentication.OAuth2AuthenticationToken; +import org.springframework.security.oauth2.core.user.DefaultOAuth2User; +import org.thingsboard.common.util.SsrfProtectionValidator; +import org.thingsboard.server.common.data.oauth2.MapperType; +import org.thingsboard.server.common.data.oauth2.OAuth2Client; +import org.thingsboard.server.common.data.oauth2.OAuth2CustomMapperConfig; +import org.thingsboard.server.common.data.oauth2.OAuth2MapperConfig; +import org.thingsboard.server.dao.oauth2.OAuth2User; +import org.thingsboard.server.service.security.model.SecurityUser; + +import java.net.InetSocketAddress; +import java.nio.charset.StandardCharsets; +import java.util.Base64; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.concurrent.CopyOnWriteArrayList; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +public class CustomOAuth2ClientMapperTest { + + private static final String PROVIDER_ACCESS_TOKEN = "provider-access-token"; + + private final List> receivedHeaders = new CopyOnWriteArrayList<>(); + private final CustomOAuth2ClientMapper mapper = new CustomOAuth2ClientMapper() { + @Override + protected SecurityUser getOrCreateSecurityUserFromOAuth2User(OAuth2User oauth2User, OAuth2Client oAuth2Client) { + return null; + } + }; + + private HttpServer server; + private boolean uriValidationEnabled; + private OAuth2AuthenticationToken token; + + @BeforeEach + public void setUp() throws Exception { + server = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0); + server.createContext("/mapper", exchange -> { + Map headers = new HashMap<>(); + String authorization = exchange.getRequestHeaders().getFirst("Authorization"); + if (authorization != null) { + headers.put("Authorization", authorization); + } + String providerToken = exchange.getRequestHeaders().getFirst(PROVIDER_ACCESS_TOKEN); + if (providerToken != null) { + headers.put(PROVIDER_ACCESS_TOKEN, providerToken); + } + receivedHeaders.add(headers); + byte[] body = "{\"email\":\"user@example.com\"}".getBytes(StandardCharsets.UTF_8); + exchange.getResponseHeaders().add("Content-Type", "application/json"); + exchange.sendResponseHeaders(200, body.length); + exchange.getResponseBody().write(body); + exchange.close(); + }); + server.start(); + + uriValidationEnabled = SsrfProtectionValidator.isEnabled(); + SsrfProtectionValidator.setEnabled(false); + + token = mock(OAuth2AuthenticationToken.class); + when(token.getPrincipal()).thenReturn(new DefaultOAuth2User(List.of(), Map.of("email", "user@example.com"), "email")); + } + + @AfterEach + public void tearDown() { + server.stop(0); + SsrfProtectionValidator.setEnabled(uriValidationEnabled); + } + + @Test + public void sendsOwnCredentialsAndTokenWhenConfigured() { + login(client("user", "pass", true), "token-1"); + login(client("user2", "pass2", true), "token-2"); + + assertThat(receivedHeaders).containsExactly( + Map.of("Authorization", basic("user", "pass"), PROVIDER_ACCESS_TOKEN, "token-1"), + Map.of("Authorization", basic("user2", "pass2"), PROVIDER_ACCESS_TOKEN, "token-2")); + } + + @Test + public void sendsNoAuthorizationHeaderWhenClientHasNoCredentials() { + login(client("user", "pass", true), "token-1"); + login(client(null, null, false), "token-2"); + + assertThat(receivedHeaders).hasSize(2); + assertThat(receivedHeaders.get(1)).isEmpty(); + } + + @Test + public void sendsNoProviderTokenWhenSendTokenIsOff() { + login(client("user", "pass", true), "token-1"); + login(client("user", "pass", false), "token-2"); + + assertThat(receivedHeaders).hasSize(2); + assertThat(receivedHeaders.get(1)).isEqualTo(Map.of("Authorization", basic("user", "pass"))); + } + + private void login(OAuth2Client client, String providerAccessToken) { + mapper.getOrCreateUserByClientPrincipal(mock(HttpServletRequest.class), token, providerAccessToken, client); + } + + private OAuth2Client client(String username, String password, boolean sendToken) { + OAuth2CustomMapperConfig custom = OAuth2CustomMapperConfig.builder() + .url("http://127.0.0.1:" + server.getAddress().getPort() + "/mapper") + .username(username) + .password(password) + .sendToken(sendToken) + .build(); + OAuth2Client client = new OAuth2Client(); + client.setMapperConfig(OAuth2MapperConfig.builder().type(MapperType.CUSTOM).custom(custom).build()); + return client; + } + + private static String basic(String username, String password) { + return "Basic " + Base64.getEncoder().encodeToString((username + ":" + password).getBytes(StandardCharsets.UTF_8)); + } + +} diff --git a/application/src/test/java/org/thingsboard/server/service/security/system/DefaultSystemSecurityServiceTest.java b/application/src/test/java/org/thingsboard/server/service/security/system/DefaultSystemSecurityServiceTest.java index 9a46775ede..3c71a289d4 100644 --- a/application/src/test/java/org/thingsboard/server/service/security/system/DefaultSystemSecurityServiceTest.java +++ b/application/src/test/java/org/thingsboard/server/service/security/system/DefaultSystemSecurityServiceTest.java @@ -16,9 +16,12 @@ import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.thingsboard.common.util.JacksonUtil; import org.thingsboard.rule.engine.api.MailService; import org.thingsboard.server.common.data.AdminSettings; +import org.thingsboard.server.common.data.User; +import org.thingsboard.server.common.data.exception.ThingsboardErrorCode; import org.thingsboard.server.common.data.exception.ThingsboardException; import org.thingsboard.server.common.data.id.TenantId; import org.thingsboard.server.common.data.id.UserId; +import org.thingsboard.server.common.data.permission.MergedUserPermissions; import org.thingsboard.server.common.data.security.UserCredentials; import org.thingsboard.server.common.data.security.model.SecuritySettings; import org.thingsboard.server.common.data.security.model.UserPasswordPolicy; @@ -28,6 +31,8 @@ import org.thingsboard.server.dao.settings.AdminSettingsService; import org.thingsboard.server.dao.settings.SecuritySettingsService; import org.thingsboard.server.dao.user.UserService; import org.thingsboard.server.dao.wl.WhiteLabelingService; +import org.thingsboard.server.service.security.model.SecurityUser; +import org.thingsboard.server.service.security.model.token.AccessJwtToken; import org.thingsboard.server.service.security.model.token.JwtTokenFactory; import org.thingsboard.server.service.security.permission.UserPermissionsService; @@ -37,6 +42,7 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; @@ -252,4 +258,33 @@ public class DefaultSystemSecurityServiceTest { return request; } + @Test + public void testCreateUserAccessTokenForUserOfSameTenant() throws Exception { + User user = createUser(tenantId); + when(userService.findUserById(tenantId, userId)).thenReturn(user); + when(userService.findUserCredentialsByUserId(tenantId, userId)).thenReturn(userCredentials); + when(userPermissionsService.getMergedPermissions(user, false)).thenReturn(mock(MergedUserPermissions.class)); + AccessJwtToken token = mock(AccessJwtToken.class); + when(tokenFactory.createAccessJwtToken(any(SecurityUser.class))).thenReturn(token); + + assertThat(systemSecurityService.createUserAccessToken(tenantId, userId)).isSameAs(token); + } + + @Test + public void testCreateUserAccessTokenForUserOfOtherTenantFails() { + when(userService.findUserById(tenantId, userId)).thenReturn(createUser(TenantId.fromUUID(UUID.randomUUID()))); + + assertThatThrownBy(() -> systemSecurityService.createUserAccessToken(tenantId, userId)) + .isInstanceOfSatisfying(ThingsboardException.class, e -> assertThat(e.getErrorCode()).isEqualTo(ThingsboardErrorCode.BAD_REQUEST_PARAMS)); + + verify(tokenFactory, never()).createAccessJwtToken(any()); + } + + private User createUser(TenantId userTenantId) { + User user = new User(userId); + user.setTenantId(userTenantId); + user.setEmail(username); + return user; + } + } diff --git a/application/src/test/java/org/thingsboard/server/service/sync/vc/VersionControlTest.java b/application/src/test/java/org/thingsboard/server/service/sync/vc/VersionControlTest.java index c05cdfe553..41f3a077bb 100644 --- a/application/src/test/java/org/thingsboard/server/service/sync/vc/VersionControlTest.java +++ b/application/src/test/java/org/thingsboard/server/service/sync/vc/VersionControlTest.java @@ -2605,7 +2605,7 @@ public class VersionControlTest extends AbstractControllerTest { reportConfig.put("type", "pdf"); reportConfig.put("timezone", "Europe/Kiev"); reportConfig.put("useCurrentUserCredentials", true); - reportConfig.put("userId", "7a306270-4820-11f0-bc58-39b3596e763d"); + reportConfig.put("userId", tenantAdmin1.getId().toString()); reportConfig.put("dashboardId", dashboardId.toString()); reportConfig.put("state", ""); diff --git a/application/src/test/java/org/thingsboard/server/utils/MiscUtilsTest.java b/application/src/test/java/org/thingsboard/server/utils/MiscUtilsTest.java new file mode 100644 index 0000000000..1680f5a739 --- /dev/null +++ b/application/src/test/java/org/thingsboard/server/utils/MiscUtilsTest.java @@ -0,0 +1,73 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +package org.thingsboard.server.utils; + +import org.junit.jupiter.api.Test; +import org.springframework.mock.web.MockHttpServletRequest; + +import java.net.URI; + +import static org.assertj.core.api.Assertions.assertThat; + +public class MiscUtilsTest { + + @Test + public void testBaseUrlUsesForwardedHttpsScheme() { + MockHttpServletRequest request = newRequest(); + request.addHeader("x-forwarded-proto", "https"); + + assertThat(MiscUtils.constructBaseUrl(request)).isEqualTo("https://localhost:443"); + } + + @Test + public void testForwardedSchemeIsLowerCased() { + MockHttpServletRequest request = newRequest(); + request.addHeader("x-forwarded-proto", "HTTPS"); + + assertThat(MiscUtils.getScheme(request)).isEqualTo("https"); + } + + @Test + public void testNonHttpForwardedSchemeFallsBackToHttp() { + MockHttpServletRequest request = newRequest(); + request.addHeader("x-forwarded-proto", "ftp"); + + assertThat(MiscUtils.getScheme(request)).isEqualTo("http"); + URI baseUrl = URI.create(MiscUtils.constructBaseUrl(request)); + assertThat(baseUrl.getScheme()).isEqualTo("http"); + assertThat(baseUrl.getHost()).isEqualTo("localhost"); + } + + @Test + public void testNonHttpForwardedSchemeOnSecureRequestFallsBackToHttps() { + MockHttpServletRequest request = newRequest(); + request.addHeader("x-forwarded-proto", "ftp"); + request.setSecure(true); + + assertThat(MiscUtils.getScheme(request)).isEqualTo("https"); + assertThat(URI.create(MiscUtils.constructBaseUrl(request)).getHost()).isEqualTo("localhost"); + } + + @Test + public void testRequestSchemeIsUsedWithoutForwardedHeader() { + MockHttpServletRequest request = newRequest(); + request.setScheme("https"); + + assertThat(MiscUtils.getScheme(request)).isEqualTo("https"); + } + + @Test + public void testNonHttpRequestSchemeFallsBackToHttp() { + MockHttpServletRequest request = newRequest(); + request.setScheme("ftp"); + + assertThat(MiscUtils.getScheme(request)).isEqualTo("http"); + } + + private MockHttpServletRequest newRequest() { + MockHttpServletRequest request = new MockHttpServletRequest(); + request.setServerName("localhost"); + return request; + } + +} 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/common/version-control/src/main/java/org/thingsboard/server/service/sync/DefaultGitSyncService.java b/common/version-control/src/main/java/org/thingsboard/server/service/sync/DefaultGitSyncService.java index afe209b96f..675c642ef3 100644 --- a/common/version-control/src/main/java/org/thingsboard/server/service/sync/DefaultGitSyncService.java +++ b/common/version-control/src/main/java/org/thingsboard/server/service/sync/DefaultGitSyncService.java @@ -150,7 +150,7 @@ public class DefaultGitSyncService implements GitSyncService { private Path getRepoDirectory(RepositorySettings settings) { // using uri to define folder name in case repo url is changed String name = URI.create(settings.getRepositoryUri()).getPath().replaceAll("[^a-zA-Z]", ""); - return Path.of(repositoriesFolder, name); + return GitRepository.resolveDirectory(repositoriesFolder, name); } private RevCommit getLastCommit(String key) { diff --git a/common/version-control/src/main/java/org/thingsboard/server/service/sync/vc/DefaultGitRepositoryService.java b/common/version-control/src/main/java/org/thingsboard/server/service/sync/vc/DefaultGitRepositoryService.java index e1113315ec..5e4b9f4c65 100644 --- a/common/version-control/src/main/java/org/thingsboard/server/service/sync/vc/DefaultGitRepositoryService.java +++ b/common/version-control/src/main/java/org/thingsboard/server/service/sync/vc/DefaultGitRepositoryService.java @@ -358,7 +358,8 @@ public class DefaultGitRepositoryService implements GitRepositoryService { private GitRepository openOrCloneRepository(TenantId tenantId, RepositorySettings settings, boolean fetch) throws Exception { log.debug("[{}] Init tenant repository started.", tenantId); - Path repositoryDirectory = Path.of(repositoriesFolder, settings.isLocalOnly() ? "local_" + settings.getRepositoryUri() : tenantId.getId().toString()); + String directoryName = settings.isLocalOnly() ? "local_" + settings.getRepositoryUri() : tenantId.getId().toString(); + Path repositoryDirectory = GitRepository.resolveDirectory(repositoriesFolder, directoryName); GitRepository repository = GitRepository.openOrClone(repositoryDirectory, settings, fetch); repositories.put(tenantId, repository); log.debug("[{}] Init tenant repository completed.", tenantId); diff --git a/common/version-control/src/main/java/org/thingsboard/server/service/sync/vc/GitRepository.java b/common/version-control/src/main/java/org/thingsboard/server/service/sync/vc/GitRepository.java index 9bb8e61ef9..c371c81bd8 100644 --- a/common/version-control/src/main/java/org/thingsboard/server/service/sync/vc/GitRepository.java +++ b/common/version-control/src/main/java/org/thingsboard/server/service/sync/vc/GitRepository.java @@ -476,6 +476,15 @@ public class GitRepository { return git.getRepository().resolve(rev); } + public static Path resolveDirectory(String repositoriesFolder, String directoryName) { + Path root = Path.of(repositoriesFolder).toAbsolutePath().normalize(); + Path directory = root.resolve(directoryName).normalize(); + if (!root.equals(directory.getParent()) || !directoryName.equals(directory.getFileName().toString())) { + throw new IllegalArgumentException("Repository directory name must be a single path segment"); + } + return directory; + } + @SneakyThrows public static boolean exists(String directory) { File gitDirectory = Path.of(directory, ".git").toFile(); diff --git a/common/version-control/src/test/java/org/thingsboard/server/service/sync/vc/DefaultGitRepositoryServiceTest.java b/common/version-control/src/test/java/org/thingsboard/server/service/sync/vc/DefaultGitRepositoryServiceTest.java new file mode 100644 index 0000000000..c7fdda9cc6 --- /dev/null +++ b/common/version-control/src/test/java/org/thingsboard/server/service/sync/vc/DefaultGitRepositoryServiceTest.java @@ -0,0 +1,65 @@ +// SPDX-FileCopyrightText: Copyright The ThingsBoard Authors +// SPDX-License-Identifier: Apache-2.0 +package org.thingsboard.server.service.sync.vc; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import org.springframework.test.util.ReflectionTestUtils; +import org.thingsboard.server.common.data.id.TenantId; +import org.thingsboard.server.common.data.sync.vc.RepositorySettings; + +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.UUID; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +public class DefaultGitRepositoryServiceTest { + + @TempDir + Path tempDir; + + private DefaultGitRepositoryService service; + private final TenantId tenantId = TenantId.fromUUID(UUID.randomUUID()); + + @BeforeEach + public void setUp() { + service = new DefaultGitRepositoryService(); + ReflectionTestUtils.setField(service, "repositoriesFolder", tempDir.toString()); + } + + @Test + public void localRepositoryIsCreatedDirectlyUnderRepositoriesFolder() throws Exception { + RepositorySettings settings = localSettings("repo1"); + + service.initRepository(tenantId, settings, false); + + assertThat(tempDir.resolve("local_repo1").resolve(".git")).isDirectory(); + assertThat(service.getRepositorySettings(tenantId)).isEqualTo(settings); + } + + @Test + public void localRepositoryNameWithMultipleSegmentsIsRejected() throws Exception { + Path marker = tempDir.resolve("keep").resolve("marker.txt"); + Files.createDirectories(marker.getParent()); + Files.writeString(marker, "content"); + + assertThatThrownBy(() -> service.initRepository(tenantId, localSettings("repo1/main"), false)) + .isInstanceOf(IllegalArgumentException.class); + + assertThat(tempDir.resolve("local_repo1")).doesNotExist(); + assertThat(marker).exists(); + assertThat(service.getRepositorySettings(tenantId)).isNull(); + } + + private RepositorySettings localSettings(String repositoryUri) { + RepositorySettings settings = new RepositorySettings(); + settings.setRepositoryUri(repositoryUri); + settings.setDefaultBranch("main"); + settings.setLocalOnly(true); + return settings; + } + +} diff --git a/common/version-control/src/test/java/org/thingsboard/server/service/sync/vc/GitRepositoryTest.java b/common/version-control/src/test/java/org/thingsboard/server/service/sync/vc/GitRepositoryTest.java new file mode 100644 index 0000000000..0ca2fd59cc --- /dev/null +++ b/common/version-control/src/test/java/org/thingsboard/server/service/sync/vc/GitRepositoryTest.java @@ -0,0 +1,36 @@ +// SPDX-FileCopyrightText: Copyright The ThingsBoard Authors +// SPDX-License-Identifier: Apache-2.0 +package org.thingsboard.server.service.sync.vc; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; + +import java.nio.file.Path; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +public class GitRepositoryTest { + + @TempDir + Path tempDir; + + @Test + public void directoryIsResolvedDirectlyUnderRepositoriesFolder() { + assertThat(GitRepository.resolveDirectory(tempDir.toString(), "repo1")) + .isEqualTo(tempDir.toAbsolutePath().normalize().resolve("repo1")); + } + + @Test + public void emptyDirectoryNameIsRejected() { + assertThatThrownBy(() -> GitRepository.resolveDirectory(tempDir.toString(), "")) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + public void directoryNameThatIsNotNormalizedIsRejected() { + assertThatThrownBy(() -> GitRepository.resolveDirectory(tempDir.toString(), "./repo1")) + .isInstanceOf(IllegalArgumentException.class); + } + +} diff --git a/dao/pom.xml b/dao/pom.xml index 9e3cd7750e..38027a5a7b 100644 --- a/dao/pom.xml +++ b/dao/pom.xml @@ -288,11 +288,4 @@ - - - - thingsboard-repo - https://repo.thingsboard.io/artifactory/libs-release-public - - 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 75b51d3442..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); @@ -1211,6 +1225,12 @@ public class BaseEntityGroupService extends AbstractCachedEntityService { + EntityGroupInfo findByTenantIdAndId(TenantId tenantId, UUID entityGroupId); + + ListenableFuture findByTenantIdAndIdAsync(TenantId tenantId, UUID entityGroupId); + EntityInfo findEntityGroupEntityInfoById(TenantId tenantId, UUID entityGroupId); PageData findEntityGroupsByType(UUID tenantId, UUID parentEntityId, EntityType parentEntityType, EntityType groupType, PageLink pageLink); diff --git a/dao/src/main/java/org/thingsboard/server/dao/grouppermission/GroupPermissionServiceImpl.java b/dao/src/main/java/org/thingsboard/server/dao/grouppermission/GroupPermissionServiceImpl.java index 7a62e5ae0b..4fa030ef64 100644 --- a/dao/src/main/java/org/thingsboard/server/dao/grouppermission/GroupPermissionServiceImpl.java +++ b/dao/src/main/java/org/thingsboard/server/dao/grouppermission/GroupPermissionServiceImpl.java @@ -15,6 +15,7 @@ import org.springframework.transaction.annotation.Transactional; import org.thingsboard.common.util.JacksonUtil; import org.thingsboard.server.common.data.EntityType; import org.thingsboard.server.common.data.group.EntityGroup; +import org.thingsboard.server.common.data.group.EntityGroupInfo; import org.thingsboard.server.common.data.id.EntityGroupId; import org.thingsboard.server.common.data.id.EntityId; import org.thingsboard.server.common.data.id.GroupPermissionId; @@ -303,13 +304,16 @@ public class GroupPermissionServiceImpl extends AbstractEntityService implements } private ListenableFuture fetchUserGroupPermissionInfoAsync(TenantId tenantId, GroupPermission groupPermission) { - ListenableFuture roleFuture = roleDao.findByIdAsync(tenantId, groupPermission.getRoleId().getId()); + ListenableFuture roleFuture = findRoleAsync(tenantId, groupPermission.getRoleId()); return Futures.transformAsync(roleFuture, role -> { GroupPermissionInfo groupPermissionInfo = new GroupPermissionInfo(groupPermission); groupPermissionInfo.setRole(role); if (groupPermission.getEntityGroupId() != null && !groupPermission.getEntityGroupId().isNullUid()) { - ListenableFuture entityGroup = entityGroupService.findEntityGroupByIdAsync(tenantId, groupPermission.getEntityGroupId()); + ListenableFuture entityGroup = entityGroupService.findEntityGroupInfoByTenantIdAndIdAsync(tenantId, groupPermission.getEntityGroupId()); return Futures.transform(entityGroup, entityGroup1 -> { + if (entityGroup1 == null) { + return null; + } groupPermissionInfo.setEntityGroupName(entityGroup1.getName()); groupPermissionInfo.setEntityGroupType(entityGroup1.getType()); EntityId ownerId = entityGroup1.getOwnerId(); @@ -324,12 +328,15 @@ public class GroupPermissionServiceImpl extends AbstractEntityService implements } private ListenableFuture fetchEntityGroupPermissionInfoAsync(TenantId tenantId, GroupPermission groupPermission) { - ListenableFuture roleFuture = roleDao.findByIdAsync(tenantId, groupPermission.getRoleId().getId()); + ListenableFuture roleFuture = findRoleAsync(tenantId, groupPermission.getRoleId()); return Futures.transformAsync(roleFuture, role -> { GroupPermissionInfo groupPermissionInfo = new GroupPermissionInfo(groupPermission); groupPermissionInfo.setRole(role); - ListenableFuture userGroup = entityGroupService.findEntityGroupByIdAsync(tenantId, groupPermission.getUserGroupId()); + ListenableFuture userGroup = entityGroupService.findEntityGroupInfoByTenantIdAndIdAsync(tenantId, groupPermission.getUserGroupId()); return Futures.transform(userGroup, userGroup1 -> { + if (userGroup1 == null) { + return null; + } groupPermissionInfo.setUserGroupName(userGroup1.getName()); EntityId ownerId = userGroup1.getOwnerId(); groupPermissionInfo.setUserGroupOwnerId(ownerId); @@ -339,6 +346,12 @@ public class GroupPermissionServiceImpl extends AbstractEntityService implements }, MoreExecutors.directExecutor()); } + private ListenableFuture findRoleAsync(TenantId tenantId, RoleId roleId) { + return Futures.transform(roleDao.findByIdAsync(tenantId, roleId.getId()), + role -> role != null && (tenantId.equals(role.getTenantId()) || role.getTenantId().isSysTenantId()) ? role : null, + MoreExecutors.directExecutor()); + } + private final PaginatedRemover tenantGroupPermissionRemover = new PaginatedRemover<>() { @Override diff --git a/dao/src/main/java/org/thingsboard/server/dao/menu/CustomMenuServiceImpl.java b/dao/src/main/java/org/thingsboard/server/dao/menu/CustomMenuServiceImpl.java index 0a652fa014..55c1c050e4 100644 --- a/dao/src/main/java/org/thingsboard/server/dao/menu/CustomMenuServiceImpl.java +++ b/dao/src/main/java/org/thingsboard/server/dao/menu/CustomMenuServiceImpl.java @@ -185,8 +185,10 @@ public class CustomMenuServiceImpl extends AbstractCachedEntityService Collections.emptyList(); case CUSTOMERS -> customerService.findCustomersByCustomMenuId(customMenuInfo.getId()).stream() + .filter(customer -> isAvailableToTenant(customMenuInfo, customer.getTenantId())) .map(customer -> new EntityInfo(customer.getId(), customer.getName())).toList(); case USERS -> userService.findUsersByCustomMenuId(customMenuInfo.getId()).stream() + .filter(user -> isAvailableToTenant(customMenuInfo, user.getTenantId())) .map(user -> new EntityInfo(user.getId(), user.getName())).toList(); default -> throw new RuntimeException("Invalid custom menu assignee type '" + customMenuInfo.getAssigneeType() + "' specified for custom menu!"); @@ -334,7 +336,7 @@ public class CustomMenuServiceImpl extends AbstractCachedEntityService { protected AdminSettings validateUpdate(TenantId tenantId, AdminSettings adminSettings) { AdminSettings existentAdminSettings = adminSettingsService.findAdminSettingsById(tenantId, adminSettings.getId()); if (existentAdminSettings != null) { + TenantId targetTenantId = adminSettings.getTenantId() != null ? adminSettings.getTenantId() : TenantId.SYS_TENANT_ID; + if (!existentAdminSettings.getTenantId().equals(targetTenantId)) { + throw new DataValidationException("Can't move existing admin settings entry to different tenant!"); + } if (!existentAdminSettings.getKey().equals(adminSettings.getKey())) { throw new DataValidationException("Changing key of admin settings entry is prohibited!"); } diff --git a/dao/src/main/java/org/thingsboard/server/dao/service/validator/CalculatedFieldDataValidator.java b/dao/src/main/java/org/thingsboard/server/dao/service/validator/CalculatedFieldDataValidator.java index 3bd186ebe1..9ae93f3b6d 100644 --- a/dao/src/main/java/org/thingsboard/server/dao/service/validator/CalculatedFieldDataValidator.java +++ b/dao/src/main/java/org/thingsboard/server/dao/service/validator/CalculatedFieldDataValidator.java @@ -5,6 +5,8 @@ package org.thingsboard.server.dao.service.validator; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; +import org.thingsboard.server.common.data.EntityType; +import org.thingsboard.server.common.data.HasTenantId; import org.thingsboard.server.common.data.cf.CalculatedField; import org.thingsboard.server.common.data.cf.CalculatedFieldType; import org.thingsboard.server.common.data.cf.configuration.ArgumentsBasedCalculatedFieldConfiguration; @@ -12,26 +14,36 @@ import org.thingsboard.server.common.data.cf.configuration.RelationPathQueryDyna import org.thingsboard.server.common.data.cf.configuration.ScheduledUpdateSupportedCalculatedFieldConfiguration; import org.thingsboard.server.common.data.cf.configuration.aggregation.RelatedEntitiesAggregationCalculatedFieldConfiguration; import org.thingsboard.server.common.data.cf.configuration.aggregation.single.EntityAggregationCalculatedFieldConfiguration; +import org.thingsboard.server.common.data.id.EntityId; import org.thingsboard.server.common.data.id.TenantId; import org.thingsboard.server.common.data.tenant.profile.DefaultTenantProfileConfiguration; import org.thingsboard.server.dao.cf.CalculatedFieldDao; +import org.thingsboard.server.dao.entity.EntityDaoRegistry; import org.thingsboard.server.dao.service.DataValidator; import org.thingsboard.server.dao.usagerecord.ApiLimitService; import org.thingsboard.server.exception.DataValidationException; +import java.util.EnumSet; import java.util.Map; +import java.util.Set; import java.util.concurrent.TimeUnit; import java.util.stream.Collectors; @Component public class CalculatedFieldDataValidator extends DataValidator { + private static final Set SUPPORTED_ENTITY_TYPES = EnumSet.of( + EntityType.CUSTOMER, EntityType.ASSET, EntityType.DEVICE, EntityType.ASSET_PROFILE, EntityType.DEVICE_PROFILE); + @Autowired private CalculatedFieldDao calculatedFieldDao; @Autowired private ApiLimitService apiLimitService; + @Autowired + private EntityDaoRegistry entityDaoRegistry; + @Override protected void validateDataImpl(TenantId tenantId, CalculatedField calculatedField) { validateNumberOfArgumentsPerCF(tenantId, calculatedField); @@ -40,6 +52,13 @@ public class CalculatedFieldDataValidator extends DataValidator validateRelationQuerySourceArguments(tenantId, calculatedField); validateRelatedAggregationConfiguration(tenantId, calculatedField); validateEntityAggregationConfiguration(tenantId, calculatedField); + if (calculatedField.getTenantId() == null) { + throw new DataValidationException("Calculated field should be assigned to tenant!"); + } + validateEntityTenant(calculatedField.getTenantId(), calculatedField.getEntityId()); + for (EntityId referencedEntityId : calculatedField.getConfiguration().getReferencedEntities()) { + validateReferencedEntityTenant(calculatedField.getTenantId(), referencedEntityId); + } } @Override @@ -62,6 +81,9 @@ public class CalculatedFieldDataValidator extends DataValidator if (old == null) { throw new DataValidationException("Can't update non existing calculated field!"); } + if (!old.getTenantId().equals(calculatedField.getTenantId())) { + throw new DataValidationException("Can't update calculated field tenant id!"); + } return old; } @@ -140,4 +162,28 @@ public class CalculatedFieldDataValidator extends DataValidator } } + private void validateReferencedEntityTenant(TenantId cfTenantId, EntityId entityId) { + EntityType entityType = entityId.getEntityType(); + switch (entityType) { + case TENANT -> { + if (!cfTenantId.equals(entityId)) { + throw new DataValidationException("Referenced tenant must be the calculated field's tenant!"); + } + } + case CUSTOMER, ASSET, DEVICE -> validateEntityTenant(cfTenantId, entityId); + default -> throw new DataValidationException("Calculated fields do not support '" + entityType + "' for referenced entities."); + } + } + + private void validateEntityTenant(TenantId cfTenantId, EntityId entityId) { + EntityType entityType = entityId.getEntityType(); + if (!SUPPORTED_ENTITY_TYPES.contains(entityType)) { + throw new DataValidationException("Entity type '" + entityType + "' does not support calculated fields."); + } + HasTenantId entity = entityDaoRegistry.getDao(entityType).findById(cfTenantId, entityId.getId()); + if (entity == null || !cfTenantId.equals(entity.getTenantId())) { + throw new DataValidationException(entityType.getNormalName() + " with id [" + entityId.getId() + "] does not belong to the calculated field's tenant!"); + } + } + } diff --git a/dao/src/main/java/org/thingsboard/server/dao/service/validator/EntityViewDataValidator.java b/dao/src/main/java/org/thingsboard/server/dao/service/validator/EntityViewDataValidator.java index c61523bed3..a85566c037 100644 --- a/dao/src/main/java/org/thingsboard/server/dao/service/validator/EntityViewDataValidator.java +++ b/dao/src/main/java/org/thingsboard/server/dao/service/validator/EntityViewDataValidator.java @@ -8,9 +8,12 @@ import org.springframework.context.annotation.Lazy; import org.springframework.stereotype.Component; import org.thingsboard.server.common.data.Customer; import org.thingsboard.server.common.data.EntityView; +import org.thingsboard.server.common.data.HasTenantId; import org.thingsboard.server.common.data.id.CustomerId; +import org.thingsboard.server.common.data.id.HasId; import org.thingsboard.server.common.data.id.TenantId; import org.thingsboard.server.dao.customer.CustomerDao; +import org.thingsboard.server.dao.entity.EntityService; import org.thingsboard.server.dao.entityview.EntityViewDao; import org.thingsboard.server.dao.entityview.EntityViewService; import org.thingsboard.server.dao.service.DataValidator; @@ -35,6 +38,10 @@ public class EntityViewDataValidator extends DataValidator { @Autowired private CustomerDao customerDao; + @Autowired + @Lazy + private EntityService entityService; + @Override protected void validateCreate(TenantId tenantId, EntityView entityView) { validateNameUniqueness(entityView, null, entityViewService::findEntityViewByTenantIdAndName, "Entity view with such name already exists!"); @@ -63,6 +70,21 @@ public class EntityViewDataValidator extends DataValidator { throw new DataValidationException("Entity view is referencing to non-existent tenant!"); } } + if (entityView.getEntityId() == null) { + throw new DataValidationException("Entity view should be assigned to entity!"); + } + HasId entity; + try { + entity = entityService.fetchEntity(entityView.getTenantId(), entityView.getEntityId()).orElse(null); + } catch (IllegalArgumentException e) { + entity = null; + } + if (entity == null) { + throw new DataValidationException("Entity view is referencing to non-existent entity!"); + } + if (!(entity instanceof HasTenantId hasTenantId) || !entityView.getTenantId().equals(hasTenantId.getTenantId())) { + throw new DataValidationException("Can't assign entity view to entity from different tenant!"); + } if (entityView.getCustomerId() == null) { entityView.setCustomerId(new CustomerId(NULL_UUID)); } else if (!entityView.getCustomerId().getId().equals(NULL_UUID)) { 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!"); } diff --git a/dao/src/main/java/org/thingsboard/server/dao/sql/group/EntityGroupInfoRepository.java b/dao/src/main/java/org/thingsboard/server/dao/sql/group/EntityGroupInfoRepository.java index eeffe3a19c..01290bc3aa 100644 --- a/dao/src/main/java/org/thingsboard/server/dao/sql/group/EntityGroupInfoRepository.java +++ b/dao/src/main/java/org/thingsboard/server/dao/sql/group/EntityGroupInfoRepository.java @@ -16,6 +16,12 @@ import java.util.UUID; public interface EntityGroupInfoRepository extends JpaRepository { + String OWNED_WITHIN_TENANT = "((e.ownerId = :tenantId AND e.ownerType = 'TENANT') OR " + + "(e.ownerType = 'CUSTOMER' AND EXISTS (SELECT 1 FROM CustomerEntity c WHERE c.id = e.ownerId AND c.tenantId = :tenantId)))"; + + @Query("SELECT e FROM EntityGroupInfoEntity e WHERE e.id = :entityGroupId AND " + OWNED_WITHIN_TENANT) + EntityGroupInfoEntity findByTenantIdAndId(@Param("tenantId") UUID tenantId, @Param("entityGroupId") UUID entityGroupId); + @Query("SELECT new org.thingsboard.server.common.data.EntityInfo(e.id, 'ENTITY_GROUP', e.name) " + "FROM EntityGroupEntity e " + "WHERE e.id = :entityGroupId") @@ -65,16 +71,20 @@ public interface EntityGroupInfoRepository extends JpaRepository findEntityGroupsByIds(@Param("entityGroupIds") List entityGroupIds, + Page findEntityGroupsByIds(@Param("tenantId") UUID tenantId, + @Param("entityGroupIds") List entityGroupIds, @Param("textSearch") String textSearch, Pageable pageable); @Query("SELECT new org.thingsboard.server.common.data.EntityInfo(e.id, 'ENTITY_GROUP', e.name) " + "FROM EntityGroupEntity e " + "WHERE e.id IN :entityGroupIds " + + "AND " + OWNED_WITHIN_TENANT + " " + "AND (:textSearch IS NULL OR ilike(e.name, CONCAT('%', :textSearch, '%')) = true)") - Page findEntityGroupEntityInfosByIds(@Param("entityGroupIds") List entityGroupIds, + Page findEntityGroupEntityInfosByIds(@Param("tenantId") UUID tenantId, + @Param("entityGroupIds") List entityGroupIds, @Param("textSearch") String textSearch, Pageable pageable); diff --git a/dao/src/main/java/org/thingsboard/server/dao/sql/group/JpaEntityGroupInfoDao.java b/dao/src/main/java/org/thingsboard/server/dao/sql/group/JpaEntityGroupInfoDao.java index b0d7c837c8..bc4e675502 100644 --- a/dao/src/main/java/org/thingsboard/server/dao/sql/group/JpaEntityGroupInfoDao.java +++ b/dao/src/main/java/org/thingsboard/server/dao/sql/group/JpaEntityGroupInfoDao.java @@ -2,6 +2,7 @@ // SPDX-License-Identifier: BUSL-1.1 package org.thingsboard.server.dao.sql.group; +import com.google.common.util.concurrent.ListenableFuture; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Component; @@ -38,6 +39,16 @@ public class JpaEntityGroupInfoDao extends JpaAbstractDao findByTenantIdAndIdAsync(TenantId tenantId, UUID entityGroupId) { + return service.submit(() -> findByTenantIdAndId(tenantId, entityGroupId)); + } + @Override public EntityInfo findEntityGroupEntityInfoById(TenantId tenantId, UUID entityGroupId) { return entityGroupInfoRepository.findEntityGroupEntityInfoById(entityGroupId); @@ -90,6 +101,7 @@ public class JpaEntityGroupInfoDao extends JpaAbstractDao findEntityGroupsByIds(UUID tenantId, List entityGroupIds, PageLink pageLink) { return DaoUtil.toPageData(entityGroupInfoRepository .findEntityGroupsByIds( + tenantId, entityGroupIds, pageLink.getTextSearch(), DaoUtil.toPageable(pageLink))); @@ -99,6 +111,7 @@ public class JpaEntityGroupInfoDao extends JpaAbstractDao findEntityGroupEntityInfosByIds(UUID tenantId, List entityGroupIds, PageLink pageLink) { return DaoUtil.pageToPageData(entityGroupInfoRepository .findEntityGroupEntityInfosByIds( + tenantId, entityGroupIds, pageLink.getTextSearch(), DaoUtil.toPageable(pageLink))); diff --git a/dao/src/test/java/org/thingsboard/server/dao/service/AdminSettingsServiceTest.java b/dao/src/test/java/org/thingsboard/server/dao/service/AdminSettingsServiceTest.java index 8248c6c278..1d27812eb1 100644 --- a/dao/src/test/java/org/thingsboard/server/dao/service/AdminSettingsServiceTest.java +++ b/dao/src/test/java/org/thingsboard/server/dao/service/AdminSettingsServiceTest.java @@ -103,6 +103,63 @@ public class AdminSettingsServiceTest extends AbstractServiceTest { }).hasMessageContaining("already exists"); } + @Test + public void whenUpdatingSettingsOfAnotherTenantById_thenSaveIsRejectedAndStoredSettingsUnchanged() { + AdminSettings systemSettings = saveSettings(SYSTEM_TENANT_ID, 1); + AdminSettings systemSettingsCopy = new AdminSettings(systemSettings); + systemSettingsCopy.setTenantId(tenantId); + systemSettingsCopy.setJsonValue(JacksonUtil.newObjectNode().put("v", 2)); + assertThatThrownBy(() -> adminSettingsService.saveAdminSettings(tenantId, systemSettingsCopy)) + .isInstanceOf(DataValidationException.class) + .hasMessageContaining("different tenant"); + AdminSettings storedSystemSettings = adminSettingsService.findAdminSettingsById(SYSTEM_TENANT_ID, systemSettings.getId()); + assertThat(storedSystemSettings.getTenantId()).isEqualTo(SYSTEM_TENANT_ID); + assertThat(storedSystemSettings.getJsonValue()).isEqualTo(systemSettings.getJsonValue()); + + AdminSettings tenantSettings = saveSettings(tenantId, 1); + AdminSettings tenantSettingsCopy = new AdminSettings(tenantSettings); + tenantSettingsCopy.setTenantId(SYSTEM_TENANT_ID); + tenantSettingsCopy.setJsonValue(JacksonUtil.newObjectNode().put("v", 2)); + assertThatThrownBy(() -> adminSettingsService.saveAdminSettings(SYSTEM_TENANT_ID, tenantSettingsCopy)) + .isInstanceOf(DataValidationException.class) + .hasMessageContaining("different tenant"); + AdminSettings storedTenantSettings = adminSettingsService.findAdminSettingsById(tenantId, tenantSettings.getId()); + assertThat(storedTenantSettings.getTenantId()).isEqualTo(tenantId); + assertThat(storedTenantSettings.getJsonValue()).isEqualTo(tenantSettings.getJsonValue()); + } + + @Test + public void whenUpdatingOwnSettingsById_thenSaved() { + AdminSettings tenantSettings = saveSettings(tenantId, 1); + tenantSettings.setJsonValue(JacksonUtil.newObjectNode().put("v", 2)); + adminSettingsService.saveAdminSettings(tenantId, tenantSettings); + AdminSettings storedTenantSettings = adminSettingsService.findAdminSettingsById(tenantId, tenantSettings.getId()); + assertThat(storedTenantSettings.getTenantId()).isEqualTo(tenantId); + assertThat(storedTenantSettings.getJsonValue()).isEqualTo(tenantSettings.getJsonValue()); + + AdminSettings systemSettings = saveSettings(SYSTEM_TENANT_ID, 1); + systemSettings.setTenantId(null); + systemSettings.setJsonValue(JacksonUtil.newObjectNode().put("v", 2)); + adminSettingsService.saveAdminSettings(SYSTEM_TENANT_ID, systemSettings); + AdminSettings storedSystemSettings = adminSettingsService.findAdminSettingsById(SYSTEM_TENANT_ID, systemSettings.getId()); + assertThat(storedSystemSettings.getTenantId()).isEqualTo(SYSTEM_TENANT_ID); + assertThat(storedSystemSettings.getJsonValue()).isEqualTo(systemSettings.getJsonValue()); + + storedSystemSettings.setJsonValue(JacksonUtil.newObjectNode().put("v", 3)); + adminSettingsService.saveAdminSettings(tenantId, storedSystemSettings); + AdminSettings updatedSystemSettings = adminSettingsService.findAdminSettingsById(SYSTEM_TENANT_ID, systemSettings.getId()); + assertThat(updatedSystemSettings.getTenantId()).isEqualTo(SYSTEM_TENANT_ID); + assertThat(updatedSystemSettings.getJsonValue()).isEqualTo(storedSystemSettings.getJsonValue()); + } + + private AdminSettings saveSettings(TenantId tenantId, int value) { + AdminSettings settings = new AdminSettings(); + settings.setTenantId(tenantId); + settings.setKey(RandomStringUtils.randomAlphanumeric(15)); + settings.setJsonValue(JacksonUtil.newObjectNode().put("v", value)); + return adminSettingsService.saveAdminSettings(tenantId, settings); + } + @Test public void testFindAllByTenantId() { int pageSize = 10; 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 99eda2f067..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); @@ -515,6 +548,55 @@ public class EntityGroupServiceTest extends AbstractServiceTest { .hasMessage("Entity '" + entityGroupId.getEntityType() + "' is not a group entity!"); } + @Test + public void testShouldNotChangeEntityGroupOwnerOnUpdate() { + EntityGroup entityGroup = new EntityGroup(); + entityGroup.setType(EntityType.DEVICE); + entityGroup.setName("Device Group"); + EntityGroup savedEntityGroup = entityGroupService.saveEntityGroup(tenantId, tenantId, entityGroup); + + CustomerId customerId = new CustomerId(UUID.randomUUID()); + EntityGroup movedEntityGroup = new EntityGroup(savedEntityGroup); + movedEntityGroup.setOwnerId(customerId); + + assertThatThrownBy(() -> entityGroupService.saveEntityGroup(tenantId, customerId, movedEntityGroup)) + .isInstanceOf(DataValidationException.class) + .hasMessage("Entity group owner can't be changed!"); + assertThat(entityGroupService.findEntityGroupById(tenantId, savedEntityGroup.getId()).getOwnerId()).isEqualTo(tenantId); + } + + @Test + public void testShouldNotChangeEntityGroupTypeOnUpdate() { + EntityGroup entityGroup = new EntityGroup(); + entityGroup.setType(EntityType.DEVICE); + entityGroup.setName("Device Group"); + EntityGroup savedEntityGroup = entityGroupService.saveEntityGroup(tenantId, tenantId, entityGroup); + + EntityGroup retypedEntityGroup = new EntityGroup(savedEntityGroup); + retypedEntityGroup.setType(EntityType.USER); + + assertThatThrownBy(() -> entityGroupService.saveEntityGroup(tenantId, tenantId, retypedEntityGroup)) + .isInstanceOf(DataValidationException.class) + .hasMessage("Entity group type can't be changed!"); + assertThat(entityGroupService.findEntityGroupById(tenantId, savedEntityGroup.getId()).getType()).isEqualTo(EntityType.DEVICE); + } + + @Test + public void testShouldUpdateEntityGroupWithSameOwner() { + EntityGroup entityGroup = new EntityGroup(); + entityGroup.setType(EntityType.DEVICE); + entityGroup.setName("Device Group"); + EntityGroup savedEntityGroup = entityGroupService.saveEntityGroup(tenantId, tenantId, entityGroup); + + EntityGroup renamedEntityGroup = new EntityGroup(savedEntityGroup); + renamedEntityGroup.setName("Renamed Device Group"); + entityGroupService.saveEntityGroup(tenantId, tenantId, renamedEntityGroup); + + EntityGroup foundEntityGroup = entityGroupService.findEntityGroupById(tenantId, savedEntityGroup.getId()); + assertThat(foundEntityGroup.getName()).isEqualTo("Renamed Device Group"); + assertThat(foundEntityGroup.getOwnerId()).isEqualTo(tenantId); + } + private ListenableFuture saveStringAttribute(EntityId entityId, String key, String value, AttributeScope scope) { KvEntry attrValue = new StringDataEntry(key, value); AttributeKvEntry attr = new BaseAttributeKvEntry(attrValue, 42L); diff --git a/dao/src/test/java/org/thingsboard/server/dao/service/timeseries/BaseTimeseriesServiceTest.java b/dao/src/test/java/org/thingsboard/server/dao/service/timeseries/BaseTimeseriesServiceTest.java index f91e722b3f..488cbb9dfa 100644 --- a/dao/src/test/java/org/thingsboard/server/dao/service/timeseries/BaseTimeseriesServiceTest.java +++ b/dao/src/test/java/org/thingsboard/server/dao/service/timeseries/BaseTimeseriesServiceTest.java @@ -2,7 +2,6 @@ // SPDX-License-Identifier: Apache-2.0 package org.thingsboard.server.dao.service.timeseries; -import com.datastax.oss.driver.api.core.uuid.Uuids; import lombok.extern.slf4j.Slf4j; import org.assertj.core.data.Offset; import org.junit.After; @@ -11,6 +10,7 @@ import org.junit.Before; import org.junit.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; +import org.thingsboard.server.common.data.Device; import org.thingsboard.server.common.data.EntityView; import org.thingsboard.server.common.data.Tenant; import org.thingsboard.server.common.data.id.DeviceId; @@ -31,6 +31,7 @@ import org.thingsboard.server.common.data.kv.ReadTsKvQueryResult; import org.thingsboard.server.common.data.kv.StringDataEntry; import org.thingsboard.server.common.data.kv.TsKvEntry; import org.thingsboard.server.common.data.objects.TelemetryEntityView; +import org.thingsboard.server.dao.device.DeviceService; import org.thingsboard.server.dao.entityview.EntityViewService; import org.thingsboard.server.dao.exception.IncorrectParameterException; import org.thingsboard.server.dao.service.AbstractServiceTest; @@ -63,6 +64,9 @@ public abstract class BaseTimeseriesServiceTest extends AbstractServiceTest { @Autowired EntityViewService entityViewService; + @Autowired + DeviceService deviceService; + @Value("${database.ts.type}") String databaseTsLatestType; @@ -82,7 +86,7 @@ public abstract class BaseTimeseriesServiceTest extends AbstractServiceTest { KvEntry booleanKvEntry = new BooleanDataEntry(BOOLEAN_KEY, Boolean.TRUE); protected TenantId tenantId; - protected DeviceId deviceId = new DeviceId(Uuids.timeBased()); + protected DeviceId deviceId; @Before public void before() { @@ -91,6 +95,12 @@ public abstract class BaseTimeseriesServiceTest extends AbstractServiceTest { Tenant savedTenant = tenantService.saveTenant(tenant); Assert.assertNotNull(savedTenant); tenantId = savedTenant.getId(); + + Device device = new Device(); + device.setTenantId(tenantId); + device.setName("My device"); + device.setType("default"); + deviceId = deviceService.saveDevice(device).getId(); } @After diff --git a/dao/src/test/java/org/thingsboard/server/dao/service/validator/AdminSettingsDataValidatorTest.java b/dao/src/test/java/org/thingsboard/server/dao/service/validator/AdminSettingsDataValidatorTest.java index b42309a6f2..6e7872010a 100644 --- a/dao/src/test/java/org/thingsboard/server/dao/service/validator/AdminSettingsDataValidatorTest.java +++ b/dao/src/test/java/org/thingsboard/server/dao/service/validator/AdminSettingsDataValidatorTest.java @@ -8,12 +8,19 @@ import org.springframework.test.context.bean.override.mockito.MockitoBean; import org.springframework.test.context.bean.override.mockito.MockitoSpyBean; import org.thingsboard.common.util.JacksonUtil; import org.thingsboard.server.common.data.AdminSettings; +import org.thingsboard.server.common.data.id.AdminSettingsId; import org.thingsboard.server.common.data.id.TenantId; import org.thingsboard.server.dao.settings.AdminSettingsService; +import org.thingsboard.server.exception.DataValidationException; import java.util.UUID; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; @SpringBootTest(classes = AdminSettingsDataValidator.class) class AdminSettingsDataValidatorTest { @@ -34,4 +41,38 @@ class AdminSettingsDataValidatorTest { verify(validator).validateString("Key", adminSettings.getKey()); } -} \ No newline at end of file + @Test + void whenStoredSettingsBelongToAnotherTenant_thenUpdateIsRejected() { + AdminSettings stored = settings(TenantId.SYS_TENANT_ID); + when(adminSettingsService.findAdminSettingsById(any(), eq(stored.getId()))).thenReturn(stored); + + AdminSettings update = new AdminSettings(stored); + update.setTenantId(tenantId); + + assertThatThrownBy(() -> validator.validateUpdate(tenantId, update)) + .isInstanceOf(DataValidationException.class) + .hasMessageContaining("different tenant"); + } + + @Test + void whenStoredSettingsBelongToSameTenant_thenStoredSettingsReturned() { + AdminSettings stored = settings(tenantId); + when(adminSettingsService.findAdminSettingsById(any(), eq(stored.getId()))).thenReturn(stored); + assertThat(validator.validateUpdate(TenantId.SYS_TENANT_ID, new AdminSettings(stored))).isEqualTo(stored); + + AdminSettings storedSystemSettings = settings(TenantId.SYS_TENANT_ID); + when(adminSettingsService.findAdminSettingsById(any(), eq(storedSystemSettings.getId()))).thenReturn(storedSystemSettings); + AdminSettings update = new AdminSettings(storedSystemSettings); + update.setTenantId(null); + assertThat(validator.validateUpdate(TenantId.SYS_TENANT_ID, update)).isEqualTo(storedSystemSettings); + } + + private AdminSettings settings(TenantId tenantId) { + AdminSettings settings = new AdminSettings(new AdminSettingsId(UUID.randomUUID())); + settings.setTenantId(tenantId); + settings.setKey("general"); + settings.setJsonValue(JacksonUtil.newObjectNode().put("v", 1)); + return settings; + } + +} diff --git a/dao/src/test/java/org/thingsboard/server/dao/service/validator/CalculatedFieldDataValidatorTest.java b/dao/src/test/java/org/thingsboard/server/dao/service/validator/CalculatedFieldDataValidatorTest.java index 0cb12152be..c3163970a0 100644 --- a/dao/src/test/java/org/thingsboard/server/dao/service/validator/CalculatedFieldDataValidatorTest.java +++ b/dao/src/test/java/org/thingsboard/server/dao/service/validator/CalculatedFieldDataValidatorTest.java @@ -3,36 +3,65 @@ // SPDX-License-Identifier: Apache-2.0 AND BUSL-1.1 package org.thingsboard.server.dao.service.validator; +import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.bean.override.mockito.MockitoBean; import org.springframework.test.context.bean.override.mockito.MockitoSpyBean; +import org.thingsboard.server.common.data.Device; +import org.thingsboard.server.common.data.EntityType; import org.thingsboard.server.common.data.cf.CalculatedField; import org.thingsboard.server.common.data.cf.CalculatedFieldType; +import org.thingsboard.server.common.data.cf.configuration.Argument; +import org.thingsboard.server.common.data.cf.configuration.ArgumentType; +import org.thingsboard.server.common.data.cf.configuration.ReferencedEntityKey; +import org.thingsboard.server.common.data.cf.configuration.SimpleCalculatedFieldConfiguration; +import org.thingsboard.server.common.data.cf.configuration.TimeSeriesOutput; import org.thingsboard.server.common.data.id.CalculatedFieldId; +import org.thingsboard.server.common.data.id.DeviceId; +import org.thingsboard.server.common.data.id.EntityId; import org.thingsboard.server.common.data.id.TenantId; import org.thingsboard.server.dao.cf.CalculatedFieldDao; +import org.thingsboard.server.dao.device.DeviceDao; +import org.thingsboard.server.dao.entity.EntityDaoRegistry; import org.thingsboard.server.dao.usagerecord.DefaultApiLimitService; import org.thingsboard.server.exception.DataValidationException; +import java.util.LinkedHashMap; +import java.util.Map; import java.util.UUID; +import static org.assertj.core.api.Assertions.assertThatCode; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.BDDMockito.given; +import static org.mockito.Mockito.mock; @SpringBootTest(classes = CalculatedFieldDataValidator.class) public class CalculatedFieldDataValidatorTest { private final TenantId TENANT_ID = TenantId.fromUUID(UUID.fromString("7b5229e9-166e-41a9-a257-3b1dafad1b04")); + private final TenantId OTHER_TENANT_ID = TenantId.fromUUID(UUID.fromString("2f3d5c1e-7a52-4c8b-9d36-0b0e4f1a6c27")); private final CalculatedFieldId CALCULATED_FIELD_ID = new CalculatedFieldId(UUID.fromString("060fbe45-fbb2-4549-abf3-f72a6be3cb9f")); + private final DeviceId DEVICE_ID = new DeviceId(UUID.fromString("5a1f0e8c-3b44-4f0e-8e2a-91c7d6b3e512")); + private final DeviceId REFERENCED_DEVICE_ID = new DeviceId(UUID.fromString("c8e2b7d4-1f6a-4e93-a5c0-7d2f9b4e8a31")); @MockitoBean private CalculatedFieldDao calculatedFieldDao; @MockitoBean private DefaultApiLimitService apiLimitService; + @MockitoBean + private EntityDaoRegistry entityDaoRegistry; @MockitoSpyBean private CalculatedFieldDataValidator validator; + private final DeviceDao deviceDao = mock(DeviceDao.class); + + @BeforeEach + public void setUp() { + given(entityDaoRegistry.getDao(EntityType.DEVICE)).willReturn(deviceDao); + given(deviceDao.findById(TENANT_ID, DEVICE_ID.getId())).willReturn(getDevice(DEVICE_ID, TENANT_ID)); + } + @Test public void testUpdateNonExistingCalculatedField() { CalculatedField calculatedField = new CalculatedField(CALCULATED_FIELD_ID); @@ -46,4 +75,85 @@ public class CalculatedFieldDataValidatorTest { .hasMessage("Can't update non existing calculated field!"); } + @Test + public void testUpdateCalculatedFieldOfOtherTenant() { + CalculatedField calculatedField = getCalculatedField(TENANT_ID); + calculatedField.setId(CALCULATED_FIELD_ID); + CalculatedField stored = getCalculatedField(TENANT_ID); + stored.setId(CALCULATED_FIELD_ID); + stored.setTenantId(OTHER_TENANT_ID); + + given(calculatedFieldDao.findById(TENANT_ID, CALCULATED_FIELD_ID.getId())).willReturn(stored); + + assertThatThrownBy(() -> validator.validateUpdate(TENANT_ID, calculatedField)) + .isInstanceOf(DataValidationException.class) + .hasMessage("Can't update calculated field tenant id!"); + } + + @Test + public void testValidateCalculatedFieldWithOwnReferences() { + given(deviceDao.findById(TENANT_ID, REFERENCED_DEVICE_ID.getId())).willReturn(getDevice(REFERENCED_DEVICE_ID, TENANT_ID)); + + assertThatCode(() -> validator.validate(getCalculatedField(TENANT_ID, REFERENCED_DEVICE_ID), CalculatedField::getTenantId)) + .doesNotThrowAnyException(); + } + + @Test + public void testValidateCalculatedFieldWithOtherTenantReference() { + assertThatThrownBy(() -> validator.validate(getCalculatedField(OTHER_TENANT_ID), CalculatedField::getTenantId)) + .isInstanceOf(DataValidationException.class); + } + + @Test + public void testValidateCalculatedFieldWithOtherTenantDeviceReference() { + given(deviceDao.findById(TENANT_ID, REFERENCED_DEVICE_ID.getId())).willReturn(getDevice(REFERENCED_DEVICE_ID, OTHER_TENANT_ID)); + + assertThatThrownBy(() -> validator.validate(getCalculatedField(REFERENCED_DEVICE_ID), CalculatedField::getTenantId)) + .isInstanceOf(DataValidationException.class); + } + + @Test + public void testValidateCalculatedFieldWithMissingDeviceReference() { + assertThatThrownBy(() -> validator.validate(getCalculatedField(REFERENCED_DEVICE_ID), CalculatedField::getTenantId)) + .isInstanceOf(DataValidationException.class); + } + + @Test + public void testValidateCalculatedFieldWithOtherTenantTarget() { + given(deviceDao.findById(TENANT_ID, DEVICE_ID.getId())).willReturn(getDevice(DEVICE_ID, OTHER_TENANT_ID)); + + assertThatThrownBy(() -> validator.validate(getCalculatedField(TENANT_ID), CalculatedField::getTenantId)) + .isInstanceOf(DataValidationException.class); + } + + private CalculatedField getCalculatedField(EntityId... refEntityIds) { + SimpleCalculatedFieldConfiguration configuration = new SimpleCalculatedFieldConfiguration(); + Map arguments = new LinkedHashMap<>(); + for (int i = 0; i < refEntityIds.length; i++) { + Argument argument = new Argument(); + argument.setRefEntityId(refEntityIds[i]); + argument.setRefEntityKey(new ReferencedEntityKey("temperature", ArgumentType.TS_LATEST, null)); + arguments.put("a" + i, argument); + } + configuration.setArguments(arguments); + configuration.setExpression("a0"); + TimeSeriesOutput output = new TimeSeriesOutput(); + output.setName("output"); + configuration.setOutput(output); + + CalculatedField calculatedField = new CalculatedField(); + calculatedField.setTenantId(TENANT_ID); + calculatedField.setEntityId(DEVICE_ID); + calculatedField.setType(CalculatedFieldType.SIMPLE); + calculatedField.setName("Test"); + calculatedField.setConfiguration(configuration); + return calculatedField; + } + + private Device getDevice(DeviceId deviceId, TenantId tenantId) { + Device device = new Device(deviceId); + device.setTenantId(tenantId); + return device; + } + } diff --git a/dao/src/test/java/org/thingsboard/server/dao/service/validator/EntityViewDataValidatorTest.java b/dao/src/test/java/org/thingsboard/server/dao/service/validator/EntityViewDataValidatorTest.java index b367e660f8..67c6fbd0d2 100644 --- a/dao/src/test/java/org/thingsboard/server/dao/service/validator/EntityViewDataValidatorTest.java +++ b/dao/src/test/java/org/thingsboard/server/dao/service/validator/EntityViewDataValidatorTest.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.dao.service.validator; import org.junit.jupiter.api.BeforeEach; @@ -7,15 +8,24 @@ import org.junit.jupiter.api.Test; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.bean.override.mockito.MockitoBean; import org.springframework.test.context.bean.override.mockito.MockitoSpyBean; +import org.thingsboard.server.common.data.Device; import org.thingsboard.server.common.data.EntityView; +import org.thingsboard.server.common.data.id.DeviceId; +import org.thingsboard.server.common.data.id.HasId; import org.thingsboard.server.common.data.id.TenantId; import org.thingsboard.server.dao.customer.CustomerDao; +import org.thingsboard.server.dao.entity.EntityService; import org.thingsboard.server.dao.entityview.EntityViewDao; import org.thingsboard.server.dao.tenant.TenantService; +import org.thingsboard.server.exception.DataValidationException; +import java.util.Optional; import java.util.UUID; +import static org.assertj.core.api.Assertions.assertThatCode; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.BDDMockito.willReturn; +import static org.mockito.BDDMockito.willThrow; import static org.mockito.Mockito.verify; @SpringBootTest(classes = EntityViewDataValidator.class) @@ -27,9 +37,12 @@ class EntityViewDataValidatorTest { TenantService tenantService; @MockitoBean CustomerDao customerDao; + @MockitoBean + EntityService entityService; @MockitoSpyBean EntityViewDataValidator validator; TenantId tenantId = TenantId.fromUUID(UUID.fromString("9ef79cdf-37a8-4119-b682-2e7ed4e018da")); + DeviceId deviceId = new DeviceId(UUID.fromString("3c6f2b7e-5a41-4d8e-9f0b-7e2d1c4a8b95")); @BeforeEach void setUp() { @@ -42,10 +55,86 @@ class EntityViewDataValidatorTest { entityView.setName("view"); entityView.setType("default"); entityView.setTenantId(tenantId); + entityView.setEntityId(deviceId); + willReturn(Optional.of(newDevice(tenantId))).given(entityService).fetchEntity(tenantId, deviceId); validator.validateDataImpl(tenantId, entityView); verify(validator).validateString("Entity view name", entityView.getName()); verify(validator).validateString("Entity view type", entityView.getType()); } + @Test + void testValidateEntityViewWithEntityOfSameTenant() { + EntityView entityView = newEntityView(deviceId); + willReturn(Optional.of(newDevice(tenantId))).given(entityService).fetchEntity(tenantId, deviceId); + + assertThatCode(() -> validator.validateDataImpl(tenantId, entityView)).doesNotThrowAnyException(); + } + + @Test + void testValidateEntityViewWithNonExistentEntity() { + EntityView entityView = newEntityView(deviceId); + willReturn(Optional.empty()).given(entityService).fetchEntity(tenantId, deviceId); + + assertThatThrownBy(() -> validator.validateDataImpl(tenantId, entityView)) + .isInstanceOf(DataValidationException.class) + .hasMessage("Entity view is referencing to non-existent entity!"); + } + + @Test + void testValidateEntityViewWithEntityOfOtherTenant() { + EntityView entityView = newEntityView(deviceId); + TenantId otherTenantId = TenantId.fromUUID(UUID.fromString("b1d4e8a2-6c3f-4a7b-8e5d-2f9c0a1b3d47")); + willReturn(Optional.of(newDevice(otherTenantId))).given(entityService).fetchEntity(tenantId, deviceId); + + assertThatThrownBy(() -> validator.validateDataImpl(tenantId, entityView)) + .isInstanceOf(DataValidationException.class) + .hasMessage("Can't assign entity view to entity from different tenant!"); + } + + @Test + void testValidateEntityViewWithEntityOfUnsupportedType() { + EntityView entityView = newEntityView(deviceId); + willThrow(new IllegalArgumentException("Unsupported entity type DEVICE")).given(entityService).fetchEntity(tenantId, deviceId); + + assertThatThrownBy(() -> validator.validateDataImpl(tenantId, entityView)) + .isInstanceOf(DataValidationException.class) + .hasMessage("Entity view is referencing to non-existent entity!"); + } + + @Test + void testValidateEntityViewWithEntityWithoutTenant() { + EntityView entityView = newEntityView(deviceId); + HasId entity = () -> deviceId; + willReturn(Optional.of(entity)).given(entityService).fetchEntity(tenantId, deviceId); + + assertThatThrownBy(() -> validator.validateDataImpl(tenantId, entityView)) + .isInstanceOf(DataValidationException.class) + .hasMessage("Can't assign entity view to entity from different tenant!"); + } + + @Test + void testValidateEntityViewWithoutEntity() { + EntityView entityView = newEntityView(null); + + assertThatThrownBy(() -> validator.validateDataImpl(tenantId, entityView)) + .isInstanceOf(DataValidationException.class) + .hasMessage("Entity view should be assigned to entity!"); + } + + private EntityView newEntityView(DeviceId entityId) { + EntityView entityView = new EntityView(); + entityView.setName("view"); + entityView.setType("default"); + entityView.setTenantId(tenantId); + entityView.setEntityId(entityId); + return entityView; + } + + private Device newDevice(TenantId deviceTenantId) { + Device device = new Device(deviceId); + device.setTenantId(deviceTenantId); + return device; + } + } diff --git a/msa/edqs/pom.xml b/msa/edqs/pom.xml index 807df3b0b8..e1a0365f4f 100644 --- a/msa/edqs/pom.xml +++ b/msa/edqs/pom.xml @@ -137,7 +137,7 @@ tag ${docker.repo}/${docker.name}:latest - ${docker.repo}/${docker.name}:${project.version} + ${docker.repo}/${docker.name}:${docker.version.tag} @@ -184,7 +184,7 @@ docker push - ${docker.repo}/${docker.name}:${project.version} + ${docker.repo}/${docker.name}:${docker.version.tag} diff --git a/msa/integration/apache-pulsar/pom.xml b/msa/integration/apache-pulsar/pom.xml index 7dbe26541c..54ece3fdd1 100644 --- a/msa/integration/apache-pulsar/pom.xml +++ b/msa/integration/apache-pulsar/pom.xml @@ -140,7 +140,7 @@ tag ${docker.repo}/${docker.name}:latest - ${docker.repo}/${docker.name}:${project.version} + ${docker.repo}/${docker.name}:${docker.version.tag} @@ -187,7 +187,7 @@ docker push - ${docker.repo}/${docker.name}:${project.version} + ${docker.repo}/${docker.name}:${docker.version.tag} diff --git a/msa/integration/aws/pom.xml b/msa/integration/aws/pom.xml index 8b58f4737e..d82fdce9bd 100644 --- a/msa/integration/aws/pom.xml +++ b/msa/integration/aws/pom.xml @@ -140,7 +140,7 @@ tag ${docker.repo}/${docker.name}:latest - ${docker.repo}/${docker.name}:${project.version} + ${docker.repo}/${docker.name}:${docker.version.tag} @@ -187,7 +187,7 @@ docker push - ${docker.repo}/${docker.name}:${project.version} + ${docker.repo}/${docker.name}:${docker.version.tag} diff --git a/msa/integration/azure/pom.xml b/msa/integration/azure/pom.xml index ea12b52480..937a526f01 100644 --- a/msa/integration/azure/pom.xml +++ b/msa/integration/azure/pom.xml @@ -140,7 +140,7 @@ tag ${docker.repo}/${docker.name}:latest - ${docker.repo}/${docker.name}:${project.version} + ${docker.repo}/${docker.name}:${docker.version.tag} @@ -187,7 +187,7 @@ docker push - ${docker.repo}/${docker.name}:${project.version} + ${docker.repo}/${docker.name}:${docker.version.tag} diff --git a/msa/integration/coap/pom.xml b/msa/integration/coap/pom.xml index 1739f56dad..4d62edb089 100644 --- a/msa/integration/coap/pom.xml +++ b/msa/integration/coap/pom.xml @@ -140,7 +140,7 @@ tag ${docker.repo}/${docker.name}:latest - ${docker.repo}/${docker.name}:${project.version} + ${docker.repo}/${docker.name}:${docker.version.tag} @@ -187,7 +187,7 @@ docker push - ${docker.repo}/${docker.name}:${project.version} + ${docker.repo}/${docker.name}:${docker.version.tag} diff --git a/msa/integration/executor/pom.xml b/msa/integration/executor/pom.xml index 35b2788aab..63af6ba57a 100644 --- a/msa/integration/executor/pom.xml +++ b/msa/integration/executor/pom.xml @@ -140,7 +140,7 @@ tag ${docker.repo}/${docker.name}:latest - ${docker.repo}/${docker.name}:${project.version} + ${docker.repo}/${docker.name}:${docker.version.tag} @@ -187,7 +187,7 @@ docker push - ${docker.repo}/${docker.name}:${project.version} + ${docker.repo}/${docker.name}:${docker.version.tag} diff --git a/msa/integration/http/pom.xml b/msa/integration/http/pom.xml index 2d65ebbc76..6b2c2a9116 100644 --- a/msa/integration/http/pom.xml +++ b/msa/integration/http/pom.xml @@ -140,7 +140,7 @@ tag ${docker.repo}/${docker.name}:latest - ${docker.repo}/${docker.name}:${project.version} + ${docker.repo}/${docker.name}:${docker.version.tag} @@ -187,7 +187,7 @@ docker push - ${docker.repo}/${docker.name}:${project.version} + ${docker.repo}/${docker.name}:${docker.version.tag} diff --git a/msa/integration/kafka/pom.xml b/msa/integration/kafka/pom.xml index f6d69ddd3b..5e706a9f8c 100644 --- a/msa/integration/kafka/pom.xml +++ b/msa/integration/kafka/pom.xml @@ -140,7 +140,7 @@ tag ${docker.repo}/${docker.name}:latest - ${docker.repo}/${docker.name}:${project.version} + ${docker.repo}/${docker.name}:${docker.version.tag} @@ -187,7 +187,7 @@ docker push - ${docker.repo}/${docker.name}:${project.version} + ${docker.repo}/${docker.name}:${docker.version.tag} diff --git a/msa/integration/mqtt/pom.xml b/msa/integration/mqtt/pom.xml index 888396d188..47e1781577 100644 --- a/msa/integration/mqtt/pom.xml +++ b/msa/integration/mqtt/pom.xml @@ -140,7 +140,7 @@ tag ${docker.repo}/${docker.name}:latest - ${docker.repo}/${docker.name}:${project.version} + ${docker.repo}/${docker.name}:${docker.version.tag} @@ -187,7 +187,7 @@ docker push - ${docker.repo}/${docker.name}:${project.version} + ${docker.repo}/${docker.name}:${docker.version.tag} diff --git a/msa/integration/opc-ua/pom.xml b/msa/integration/opc-ua/pom.xml index 1389e7395d..39503ca41e 100644 --- a/msa/integration/opc-ua/pom.xml +++ b/msa/integration/opc-ua/pom.xml @@ -140,7 +140,7 @@ tag ${docker.repo}/${docker.name}:latest - ${docker.repo}/${docker.name}:${project.version} + ${docker.repo}/${docker.name}:${docker.version.tag} @@ -187,7 +187,7 @@ docker push - ${docker.repo}/${docker.name}:${project.version} + ${docker.repo}/${docker.name}:${docker.version.tag} diff --git a/msa/integration/pom.xml b/msa/integration/pom.xml index 4feae93369..8dc6d15518 100644 --- a/msa/integration/pom.xml +++ b/msa/integration/pom.xml @@ -54,7 +54,7 @@ ${docker.push-integration-arm-amd-image.phase} - latest,${project.version} + latest,${docker.version.tag} @@ -96,7 +96,7 @@ buildx build -t - ${docker.repo}/${docker.name}:${project.version} + ${docker.repo}/${docker.name}:${docker.version.tag} --platform=linux/amd64,linux/arm64 -o type=registry @@ -121,7 +121,7 @@ false ${docker.push-integration-arm-amd-image.phase} - ${sbom.image.latestTag},${project.version},${docker.lts.tag} + ${sbom.image.latestTag},${docker.version.tag},${docker.lts.tag} @@ -164,7 +164,7 @@ buildx build -t - ${docker.repo}/${docker.name}:${project.version} + ${docker.repo}/${docker.name}:${docker.version.tag} --platform=linux/amd64,linux/arm64 -o type=registry diff --git a/msa/integration/pubsub/pom.xml b/msa/integration/pubsub/pom.xml index e00259414f..3dfc7766a4 100644 --- a/msa/integration/pubsub/pom.xml +++ b/msa/integration/pubsub/pom.xml @@ -140,7 +140,7 @@ tag ${docker.repo}/${docker.name}:latest - ${docker.repo}/${docker.name}:${project.version} + ${docker.repo}/${docker.name}:${docker.version.tag} @@ -187,7 +187,7 @@ docker push - ${docker.repo}/${docker.name}:${project.version} + ${docker.repo}/${docker.name}:${docker.version.tag} diff --git a/msa/integration/rabbitmq/pom.xml b/msa/integration/rabbitmq/pom.xml index c16bfb0ccd..dff8c91cfd 100644 --- a/msa/integration/rabbitmq/pom.xml +++ b/msa/integration/rabbitmq/pom.xml @@ -140,7 +140,7 @@ tag ${docker.repo}/${docker.name}:latest - ${docker.repo}/${docker.name}:${project.version} + ${docker.repo}/${docker.name}:${docker.version.tag} @@ -187,7 +187,7 @@ docker push - ${docker.repo}/${docker.name}:${project.version} + ${docker.repo}/${docker.name}:${docker.version.tag} diff --git a/msa/integration/tcp-udp/pom.xml b/msa/integration/tcp-udp/pom.xml index 2ee453c6c4..24cf0ccf53 100644 --- a/msa/integration/tcp-udp/pom.xml +++ b/msa/integration/tcp-udp/pom.xml @@ -140,7 +140,7 @@ tag ${docker.repo}/${docker.name}:latest - ${docker.repo}/${docker.name}:${project.version} + ${docker.repo}/${docker.name}:${docker.version.tag} @@ -187,7 +187,7 @@ docker push - ${docker.repo}/${docker.name}:${project.version} + ${docker.repo}/${docker.name}:${docker.version.tag} diff --git a/msa/integration/tuya/pom.xml b/msa/integration/tuya/pom.xml index 831cadc812..f7d9bc7c6e 100644 --- a/msa/integration/tuya/pom.xml +++ b/msa/integration/tuya/pom.xml @@ -140,7 +140,7 @@ tag ${docker.repo}/${docker.name}:latest - ${docker.repo}/${docker.name}:${project.version} + ${docker.repo}/${docker.name}:${docker.version.tag} @@ -187,7 +187,7 @@ docker push - ${docker.repo}/${docker.name}:${project.version} + ${docker.repo}/${docker.name}:${docker.version.tag} diff --git a/msa/js-executor/pom.xml b/msa/js-executor/pom.xml index 687d7fbc25..3bfaee55ae 100644 --- a/msa/js-executor/pom.xml +++ b/msa/js-executor/pom.xml @@ -221,7 +221,7 @@ tag ${docker.repo}/${docker.name}:latest - ${docker.repo}/${docker.name}:${project.version} + ${docker.repo}/${docker.name}:${docker.version.tag} @@ -332,7 +332,7 @@ docker push - ${docker.repo}/${docker.name}:${project.version} + ${docker.repo}/${docker.name}:${docker.version.tag} diff --git a/msa/migrator/pom.xml b/msa/migrator/pom.xml index bbb29c50f5..f7a18b533e 100644 --- a/msa/migrator/pom.xml +++ b/msa/migrator/pom.xml @@ -137,7 +137,7 @@ tag ${docker.repo}/${docker.name}:latest - ${docker.repo}/${docker.name}:${project.version} + ${docker.repo}/${docker.name}:${docker.version.tag} @@ -179,7 +179,7 @@ docker push - ${docker.repo}/${docker.name}:${project.version} + ${docker.repo}/${docker.name}:${docker.version.tag} diff --git a/msa/monitoring/pom.xml b/msa/monitoring/pom.xml index 8154decd5d..1de7097bf1 100644 --- a/msa/monitoring/pom.xml +++ b/msa/monitoring/pom.xml @@ -138,7 +138,7 @@ tag ${docker.repo}/${docker.name}:latest - ${docker.repo}/${docker.name}:${project.version} + ${docker.repo}/${docker.name}:${docker.version.tag} @@ -185,7 +185,7 @@ docker push - ${docker.repo}/${docker.name}:${project.version} + ${docker.repo}/${docker.name}:${docker.version.tag} diff --git a/msa/pom.xml b/msa/pom.xml index 7dba66bcfd..2d77c14047 100644 --- a/msa/pom.xml +++ b/msa/pom.xml @@ -26,6 +26,7 @@ pkg.package.phase (which is "none" here since these modules don't produce packaging). --> package thingsboard + ${project.version} thingsboard/openjdk25:trixie-slim true @@ -157,7 +158,7 @@ ${docker.push-arm-amd-image.phase} - latest,${project.version} + latest,${docker.version.tag} @@ -199,7 +200,7 @@ buildx build -t - ${docker.repo}/${docker.name}:${project.version} + ${docker.repo}/${docker.name}:${docker.version.tag} --platform=linux/amd64,linux/arm64 -o type=registry @@ -224,7 +225,7 @@ false ${docker.push-arm-amd-image.phase} - ${sbom.image.latestTag},${project.version},${docker.lts.tag} + ${sbom.image.latestTag},${docker.version.tag},${docker.lts.tag} @@ -267,7 +268,7 @@ buildx build -t - ${docker.repo}/${docker.name}:${project.version} + ${docker.repo}/${docker.name}:${docker.version.tag} --platform=linux/amd64,linux/arm64 -o type=registry diff --git a/msa/report/pom.xml b/msa/report/pom.xml index 806d9f8e71..07951226f9 100644 --- a/msa/report/pom.xml +++ b/msa/report/pom.xml @@ -138,7 +138,7 @@ tag ${docker.repo}/${docker.name}:latest - ${docker.repo}/${docker.name}:${project.version} + ${docker.repo}/${docker.name}:${docker.version.tag} @@ -185,7 +185,7 @@ docker push - ${docker.repo}/${docker.name}:${project.version} + ${docker.repo}/${docker.name}:${docker.version.tag} diff --git a/msa/tb-node/pom.xml b/msa/tb-node/pom.xml index 0b25f1c314..334b8faa55 100644 --- a/msa/tb-node/pom.xml +++ b/msa/tb-node/pom.xml @@ -137,7 +137,7 @@ tag ${docker.repo}/${docker.name}:latest - ${docker.repo}/${docker.name}:${project.version} + ${docker.repo}/${docker.name}:${docker.version.tag} @@ -184,7 +184,7 @@ docker push - ${docker.repo}/${docker.name}:${project.version} + ${docker.repo}/${docker.name}:${docker.version.tag} diff --git a/msa/transport/coap/pom.xml b/msa/transport/coap/pom.xml index 53d1b2aa30..64c3b96edb 100644 --- a/msa/transport/coap/pom.xml +++ b/msa/transport/coap/pom.xml @@ -137,7 +137,7 @@ tag ${docker.repo}/${docker.name}:latest - ${docker.repo}/${docker.name}:${project.version} + ${docker.repo}/${docker.name}:${docker.version.tag} @@ -184,7 +184,7 @@ docker push - ${docker.repo}/${docker.name}:${project.version} + ${docker.repo}/${docker.name}:${docker.version.tag} diff --git a/msa/transport/http/pom.xml b/msa/transport/http/pom.xml index 5d0d7b30f2..4382261ab3 100644 --- a/msa/transport/http/pom.xml +++ b/msa/transport/http/pom.xml @@ -137,7 +137,7 @@ tag ${docker.repo}/${docker.name}:latest - ${docker.repo}/${docker.name}:${project.version} + ${docker.repo}/${docker.name}:${docker.version.tag} @@ -184,7 +184,7 @@ docker push - ${docker.repo}/${docker.name}:${project.version} + ${docker.repo}/${docker.name}:${docker.version.tag} diff --git a/msa/transport/lwm2m/pom.xml b/msa/transport/lwm2m/pom.xml index 6a628aa6e7..5d0b944e17 100644 --- a/msa/transport/lwm2m/pom.xml +++ b/msa/transport/lwm2m/pom.xml @@ -137,7 +137,7 @@ tag ${docker.repo}/${docker.name}:latest - ${docker.repo}/${docker.name}:${project.version} + ${docker.repo}/${docker.name}:${docker.version.tag} @@ -184,7 +184,7 @@ docker push - ${docker.repo}/${docker.name}:${project.version} + ${docker.repo}/${docker.name}:${docker.version.tag} diff --git a/msa/transport/mqtt/pom.xml b/msa/transport/mqtt/pom.xml index 83e767470b..89cb717ee7 100644 --- a/msa/transport/mqtt/pom.xml +++ b/msa/transport/mqtt/pom.xml @@ -137,7 +137,7 @@ tag ${docker.repo}/${docker.name}:latest - ${docker.repo}/${docker.name}:${project.version} + ${docker.repo}/${docker.name}:${docker.version.tag} @@ -184,7 +184,7 @@ docker push - ${docker.repo}/${docker.name}:${project.version} + ${docker.repo}/${docker.name}:${docker.version.tag} diff --git a/msa/transport/snmp/pom.xml b/msa/transport/snmp/pom.xml index 2c223f046f..1aac58a0ea 100644 --- a/msa/transport/snmp/pom.xml +++ b/msa/transport/snmp/pom.xml @@ -138,7 +138,7 @@ tag ${docker.repo}/${docker.name}:latest - ${docker.repo}/${docker.name}:${project.version} + ${docker.repo}/${docker.name}:${docker.version.tag} @@ -185,7 +185,7 @@ docker push - ${docker.repo}/${docker.name}:${project.version} + ${docker.repo}/${docker.name}:${docker.version.tag} diff --git a/msa/vc-executor-docker/pom.xml b/msa/vc-executor-docker/pom.xml index 22f42235ad..d326bfec8a 100644 --- a/msa/vc-executor-docker/pom.xml +++ b/msa/vc-executor-docker/pom.xml @@ -137,7 +137,7 @@ tag ${docker.repo}/${docker.name}:latest - ${docker.repo}/${docker.name}:${project.version} + ${docker.repo}/${docker.name}:${docker.version.tag} @@ -184,7 +184,7 @@ docker push - ${docker.repo}/${docker.name}:${project.version} + ${docker.repo}/${docker.name}:${docker.version.tag} diff --git a/msa/web-report/pom.xml b/msa/web-report/pom.xml index fc1264adb9..4e5958bfb3 100644 --- a/msa/web-report/pom.xml +++ b/msa/web-report/pom.xml @@ -238,7 +238,7 @@ tag ${docker.repo}/${docker.name}:latest - ${docker.repo}/${docker.name}:${project.version} + ${docker.repo}/${docker.name}:${docker.version.tag} @@ -442,7 +442,7 @@ docker push - ${docker.repo}/${docker.name}:${project.version} + ${docker.repo}/${docker.name}:${docker.version.tag} diff --git a/msa/web-ui/pom.xml b/msa/web-ui/pom.xml index 02c8d28238..37d1815a1b 100644 --- a/msa/web-ui/pom.xml +++ b/msa/web-ui/pom.xml @@ -227,7 +227,7 @@ tag ${docker.repo}/${docker.name}:latest - ${docker.repo}/${docker.name}:${project.version} + ${docker.repo}/${docker.name}:${docker.version.tag} @@ -330,7 +330,7 @@ docker push - ${docker.repo}/${docker.name}:${project.version} + ${docker.repo}/${docker.name}:${docker.version.tag} diff --git a/pom.xml b/pom.xml index c153be978c..c86b141c3c 100755 --- a/pom.xml +++ b/pom.xml @@ -111,7 +111,7 @@ 3.25.5 1.76.0 4.0.32 - 1.2.12 + 1.2.13 1.18.48 1.2.5 1.2.5 @@ -2597,6 +2597,14 @@ thingsboard-public-repo https://repo.thingsboard.io/artifactory/libs-release-public + + + thingsboard-repo + https://repo.thingsboard.io/artifactory/libs-release-local + + false + + spring-snapshots Spring Snapshots @@ -2630,7 +2638,7 @@ - thingsboard-repo + thingsboard-public-repo https://repo.thingsboard.io/artifactory/libs-release-public diff --git a/tools/src/main/python/license-headers/curations.json b/tools/src/main/python/license-headers/curations.json index 5db9a77e80..18e0ec560f 100644 --- a/tools/src/main/python/license-headers/curations.json +++ b/tools/src/main/python/license-headers/curations.json @@ -1157,7 +1157,7 @@ "path": "msa/web-report/pom.xml", "header": "busl", "reason": "Build descriptor of the PE-only web-report module; CE has no web-report module. The only CE version is an empty file (blob e69de29bb2d) added by stray commit 2b1c5d92f3a, pushed to fix/maven-node-lts-4.3 after #16417 merged and carried into lts-4.4 via #16419; it never reached CE lts-4.3 and is not the origin of this file.", - "contentHash": "sha256:9ddddeec7898c7232abc7b16c696fdad4f3825d15d3810369f621609f2678f65" + "contentHash": "sha256:1482a75a56fe40ada65e4a1dafedd94c819a03a72ed0bad067ff051d46c12fee" }, { "path": "report/src/main/conf/logback.xml", diff --git a/ui-ngx/package.json b/ui-ngx/package.json index 0364996e3c..bd9ce3d1b1 100644 --- a/ui-ngx/package.json +++ b/ui-ngx/package.json @@ -63,7 +63,6 @@ "flot": "https://github.com/thingsboard/flot.git#0.9-work", "flot.curvedlines": "https://github.com/MichaelZinsmaier/CurvedLines.git#master", "font-awesome": "^4.7.0", - "html2canvas": "^1.4.1", "hugerte": "~1.0.14", "jquery": "^3.7.1", "jquery-sparkline": "^2.4.0", @@ -82,6 +81,7 @@ "libphonenumber-js": "^1.13.15", "maplibre-gl": "6.15.0", "marked": "~16.4.2", + "modern-screenshot": "^4.7.0", "moment": "^2.31.0", "moment-timezone": "^0.6.5", "ngx-captcha": "^14.0.0", diff --git a/ui-ngx/src/app/core/http/widget.service.ts b/ui-ngx/src/app/core/http/widget.service.ts index 0f25a0b2f0..47f7923b9b 100644 --- a/ui-ngx/src/app/core/http/widget.service.ts +++ b/ui-ngx/src/app/core/http/widget.service.ts @@ -26,10 +26,7 @@ import { filter, map, mergeMap, tap } from 'rxjs/operators'; import { WidgetTypeId } from '@shared/models/id/widget-type-id'; import { NULL_UUID } from '@shared/models/id/has-uuid'; import { ActivationEnd, Router } from '@angular/router'; -import { - BasicWidgetConfigComponent, - IBasicWidgetConfigComponent -} from '@home/components/widget/config/widget-config.component.models'; +import type { BasicWidgetConfigComponent, IBasicWidgetConfigComponent } from '@home/components/widget/config/widget-config.component.models'; import { ResourcesService } from '@core/services/resources.service'; import { UserPermissionsService } from '@core/http/user-permissions.service'; import { Operation, Resource } from '@shared/models/security.models'; @@ -301,8 +298,8 @@ export class WidgetService { this.widgetsInfoInMemoryCache.set(widgetInfo.fullFqn, widgetInfo); } - public registerBasicWidgetConfigComponents(module: any) { - Object.assign(this.basicWidgetSettingsComponentsMap, this.resourcesService.extractComponentsFromModule(module, BasicWidgetConfigComponent)); + public registerBasicWidgetConfigComponents(module: any, baseType: typeof BasicWidgetConfigComponent) { + Object.assign(this.basicWidgetSettingsComponentsMap, this.resourcesService.extractComponentsFromModule(module, baseType)); } public getBasicWidgetSettingsComponentBySelector(selector: string): Type { diff --git a/ui-ngx/src/app/core/services/dashboard-utils.service.ts b/ui-ngx/src/app/core/services/dashboard-utils.service.ts index a121cddf28..ffa249754c 100644 --- a/ui-ngx/src/app/core/services/dashboard-utils.service.ts +++ b/ui-ngx/src/app/core/services/dashboard-utils.service.ts @@ -65,7 +65,7 @@ import { BackgroundType, colorBackground, isBackgroundSettings } from '@shared/m import { MediaBreakpoints } from '@shared/models/constants'; import { TranslateService } from '@ngx-translate/core'; import { DashboardPageLayout } from '@home/components/dashboard-page/dashboard-page.models'; -import { maxGridsterCol, maxGridsterRow } from '@home/models/dashboard-component.models'; +import { maxGridsterCol, maxGridsterRow } from '@shared/models/dashboard.models'; import { findWidgetModelDefinition, widgetHasTimewindow, diff --git a/ui-ngx/src/app/core/services/home.service.ts b/ui-ngx/src/app/core/services/home.service.ts index f90ee379df..82a35e4fca 100644 --- a/ui-ngx/src/app/core/services/home.service.ts +++ b/ui-ngx/src/app/core/services/home.service.ts @@ -1,10 +1,11 @@ // 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 import { EventEmitter, Injectable } from '@angular/core'; import { ActiveComponentService } from '@core/services/active-component.service'; import { BehaviorSubject, Observable, shareReplay, Subject } from 'rxjs'; import { distinctUntilChanged } from 'rxjs/operators'; -import { RouterTabsComponent } from '@home/components/router-tabs.component'; +import type { RouterTabsComponent } from '@home/components/router-tabs.component'; import { isDefinedAndNotNull } from '@core/utils'; import { PageComponent } from '@shared/components/page.component'; @@ -43,7 +44,7 @@ export class HomeService { private activeComponentChanged(activeComponent: any) { this.hideMainToolbarSubject.next(false); let hideLoadingBar = false; - if (activeComponent && activeComponent instanceof RouterTabsComponent + if (activeComponent && (activeComponent as RouterTabsComponent).isRouterTabsComponent && isDefinedAndNotNull(activeComponent.activatedRoute?.snapshot?.data?.showMainLoadingBar)) { hideLoadingBar = !activeComponent.activatedRoute.snapshot.data.showMainLoadingBar; } else if (activeComponent && activeComponent instanceof PageComponent diff --git a/ui-ngx/src/app/modules/common/lazy-modules-map.ts b/ui-ngx/src/app/modules/common/lazy-modules-map.ts new file mode 100644 index 0000000000..ce46d971b3 --- /dev/null +++ b/ui-ngx/src/app/modules/common/lazy-modules-map.ts @@ -0,0 +1,18 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +import { defer, map, Observable, shareReplay, switchMap } from 'rxjs'; +import { IModulesMap } from '@modules/common/modules-map.models'; + +class LazyModulesMap implements IModulesMap { + + private modulesMap$: Observable = defer(() => import('@modules/common/modules-map')).pipe( + switchMap(module => module.modulesMap.init().pipe(map(() => module.modulesMap))), + shareReplay(1) + ); + + init(): Observable { + return this.modulesMap$; + } +} + +export const lazyModulesMap = new LazyModulesMap(); diff --git a/ui-ngx/src/app/modules/home/components/blob-entity/blob-entities.component.html b/ui-ngx/src/app/modules/home/components/blob-entity/blob-entities.component.html index 7d170239bc..3352070adf 100644 --- a/ui-ngx/src/app/modules/home/components/blob-entity/blob-entities.component.html +++ b/ui-ngx/src/app/modules/home/components/blob-entity/blob-entities.component.html @@ -20,7 +20,7 @@ asButton historyOnly> @if (widgetMode) { - + } @else {
- } - @if (entityGroup | hasGroupEntityOrGenericPermission: resource.USER: operation.WRITE) { + + } - - @if ((loginAsUserEnabled$ | async) && resource.USER | hasGenericPermission: operation.IMPERSONATE) {