Browse Source

Merge branch 'rc'

pull/16847/head
Viacheslav Klimov 1 week ago
parent
commit
3fce1a4766
Failed to extract signature
  1. 6
      application/src/main/java/org/thingsboard/server/controller/AdminController.java
  2. 4
      application/src/main/java/org/thingsboard/server/controller/ApiKeyController.java
  3. 53
      application/src/main/java/org/thingsboard/server/controller/BaseController.java
  4. 10
      application/src/main/java/org/thingsboard/server/controller/DashboardReportController.java
  5. 80
      application/src/main/java/org/thingsboard/server/controller/EntityGroupController.java
  6. 13
      application/src/main/java/org/thingsboard/server/controller/EntityViewController.java
  7. 43
      application/src/main/java/org/thingsboard/server/controller/GroupPermissionController.java
  8. 3
      application/src/main/java/org/thingsboard/server/controller/NotificationController.java
  9. 17
      application/src/main/java/org/thingsboard/server/controller/NotificationRuleController.java
  10. 1
      application/src/main/java/org/thingsboard/server/controller/NotificationTemplateController.java
  11. 8
      application/src/main/java/org/thingsboard/server/controller/ReportController.java
  12. 3
      application/src/main/java/org/thingsboard/server/controller/RuleEngineController.java
  13. 24
      application/src/main/java/org/thingsboard/server/controller/SchedulerEventController.java
  14. 3
      application/src/main/java/org/thingsboard/server/controller/SelfRegistrationController.java
  15. 41
      application/src/main/java/org/thingsboard/server/controller/SignUpController.java
  16. 4
      application/src/main/java/org/thingsboard/server/controller/UserController.java
  17. 2
      application/src/main/java/org/thingsboard/server/service/edge/rpc/processor/telemetry/BaseTelemetryProcessor.java
  18. 2
      application/src/main/java/org/thingsboard/server/service/install/update/EntityViewGroupAllUpdater.java
  19. 115
      application/src/main/java/org/thingsboard/server/service/iot_hub/DefaultIotHubService.java
  20. 9
      application/src/main/java/org/thingsboard/server/service/notification/DefaultNotificationCenter.java
  21. 17
      application/src/main/java/org/thingsboard/server/service/resource/DefaultTbResourceService.java
  22. 2
      application/src/main/java/org/thingsboard/server/service/scheduler/DefaultSchedulerService.java
  23. 2
      application/src/main/java/org/thingsboard/server/service/security/AccessValidator.java
  24. 11
      application/src/main/java/org/thingsboard/server/service/security/auth/oauth2/CustomOAuth2ClientMapper.java
  25. 4
      application/src/main/java/org/thingsboard/server/service/security/permission/CustomerUserPermissions.java
  26. 2
      application/src/main/java/org/thingsboard/server/service/security/system/DefaultSystemSecurityService.java
  27. 20
      application/src/main/java/org/thingsboard/server/utils/MiscUtils.java
  28. 30
      application/src/test/java/org/thingsboard/server/controller/AdminControllerTest.java
  29. 26
      application/src/test/java/org/thingsboard/server/controller/AlarmRuleControllerTest.java
  30. 51
      application/src/test/java/org/thingsboard/server/controller/ApiKeyControllerTest.java
  31. 30
      application/src/test/java/org/thingsboard/server/controller/AuthControllerTest.java
  32. 62
      application/src/test/java/org/thingsboard/server/controller/CalculatedFieldControllerTest.java
  33. 114
      application/src/test/java/org/thingsboard/server/controller/CustomMenuControllerTest.java
  34. 195
      application/src/test/java/org/thingsboard/server/controller/DashboardReportControllerTest.java
  35. 2
      application/src/test/java/org/thingsboard/server/controller/DevelopmentNoticeCaptureStampTest.java
  36. 473
      application/src/test/java/org/thingsboard/server/controller/EntityGroupControllerTest.java
  37. 89
      application/src/test/java/org/thingsboard/server/controller/EntityViewControllerTest.java
  38. 223
      application/src/test/java/org/thingsboard/server/controller/GroupPermissionControllerTest.java
  39. 32
      application/src/test/java/org/thingsboard/server/controller/ReportControllerTest.java
  40. 35
      application/src/test/java/org/thingsboard/server/controller/RuleEngineControllerTest.java
  41. 75
      application/src/test/java/org/thingsboard/server/controller/SchedulerEventControllerTest.java
  42. 313
      application/src/test/java/org/thingsboard/server/controller/SignUpControllerSqlTest.java
  43. 166
      application/src/test/java/org/thingsboard/server/controller/TbResourceControllerTest.java
  44. 35
      application/src/test/java/org/thingsboard/server/edge/CalculatedFieldEdgeTest.java
  45. 55
      application/src/test/java/org/thingsboard/server/edge/DeviceEdgeTest.java
  46. 64
      application/src/test/java/org/thingsboard/server/edge/EntityViewEdgeTest.java
  47. 45
      application/src/test/java/org/thingsboard/server/edge/TelemetryEdgeTest.java
  48. 17
      application/src/test/java/org/thingsboard/server/service/entitiy/EntityServiceTest.java
  49. 35
      application/src/test/java/org/thingsboard/server/service/install/update/EntityViewGroupAllUpdaterTest.java
  50. 377
      application/src/test/java/org/thingsboard/server/service/iot_hub/DefaultIotHubServiceTest.java
  51. 36
      application/src/test/java/org/thingsboard/server/service/notification/NotificationApiTest.java
  52. 131
      application/src/test/java/org/thingsboard/server/service/notification/NotificationRuleApiTest.java
  53. 95
      application/src/test/java/org/thingsboard/server/service/notification/NotificationTemplateApiTest.java
  54. 15
      application/src/test/java/org/thingsboard/server/service/resource/sql/BaseTbResourceServiceTest.java
  55. 62
      application/src/test/java/org/thingsboard/server/service/scheduler/sql/SchedulerEventTest.java
  56. 131
      application/src/test/java/org/thingsboard/server/service/security/auth/oauth2/CustomOAuth2ClientMapperTest.java
  57. 35
      application/src/test/java/org/thingsboard/server/service/security/system/DefaultSystemSecurityServiceTest.java
  58. 2
      application/src/test/java/org/thingsboard/server/service/sync/vc/VersionControlTest.java
  59. 73
      application/src/test/java/org/thingsboard/server/utils/MiscUtilsTest.java
  60. 4
      common/dao-api/src/main/java/org/thingsboard/server/dao/group/EntityGroupService.java
  61. 2
      common/version-control/src/main/java/org/thingsboard/server/service/sync/DefaultGitSyncService.java
  62. 3
      common/version-control/src/main/java/org/thingsboard/server/service/sync/vc/DefaultGitRepositoryService.java
  63. 9
      common/version-control/src/main/java/org/thingsboard/server/service/sync/vc/GitRepository.java
  64. 65
      common/version-control/src/test/java/org/thingsboard/server/service/sync/vc/DefaultGitRepositoryServiceTest.java
  65. 36
      common/version-control/src/test/java/org/thingsboard/server/service/sync/vc/GitRepositoryTest.java
  66. 7
      dao/pom.xml
  67. 20
      dao/src/main/java/org/thingsboard/server/dao/group/BaseEntityGroupService.java
  68. 5
      dao/src/main/java/org/thingsboard/server/dao/group/EntityGroupInfoDao.java
  69. 21
      dao/src/main/java/org/thingsboard/server/dao/grouppermission/GroupPermissionServiceImpl.java
  70. 15
      dao/src/main/java/org/thingsboard/server/dao/menu/CustomMenuServiceImpl.java
  71. 4
      dao/src/main/java/org/thingsboard/server/dao/service/validator/AdminSettingsDataValidator.java
  72. 46
      dao/src/main/java/org/thingsboard/server/dao/service/validator/CalculatedFieldDataValidator.java
  73. 22
      dao/src/main/java/org/thingsboard/server/dao/service/validator/EntityViewDataValidator.java
  74. 10
      dao/src/main/java/org/thingsboard/server/dao/service/validator/GroupPermissionDataValidator.java
  75. 14
      dao/src/main/java/org/thingsboard/server/dao/sql/group/EntityGroupInfoRepository.java
  76. 13
      dao/src/main/java/org/thingsboard/server/dao/sql/group/JpaEntityGroupInfoDao.java
  77. 57
      dao/src/test/java/org/thingsboard/server/dao/service/AdminSettingsServiceTest.java
  78. 82
      dao/src/test/java/org/thingsboard/server/dao/service/EntityGroupServiceTest.java
  79. 14
      dao/src/test/java/org/thingsboard/server/dao/service/timeseries/BaseTimeseriesServiceTest.java
  80. 43
      dao/src/test/java/org/thingsboard/server/dao/service/validator/AdminSettingsDataValidatorTest.java
  81. 110
      dao/src/test/java/org/thingsboard/server/dao/service/validator/CalculatedFieldDataValidatorTest.java
  82. 91
      dao/src/test/java/org/thingsboard/server/dao/service/validator/EntityViewDataValidatorTest.java
  83. 4
      msa/edqs/pom.xml
  84. 4
      msa/integration/apache-pulsar/pom.xml
  85. 4
      msa/integration/aws/pom.xml
  86. 4
      msa/integration/azure/pom.xml
  87. 4
      msa/integration/coap/pom.xml
  88. 4
      msa/integration/executor/pom.xml
  89. 4
      msa/integration/http/pom.xml
  90. 4
      msa/integration/kafka/pom.xml
  91. 4
      msa/integration/mqtt/pom.xml
  92. 4
      msa/integration/opc-ua/pom.xml
  93. 8
      msa/integration/pom.xml
  94. 4
      msa/integration/pubsub/pom.xml
  95. 4
      msa/integration/rabbitmq/pom.xml
  96. 4
      msa/integration/tcp-udp/pom.xml
  97. 4
      msa/integration/tuya/pom.xml
  98. 4
      msa/js-executor/pom.xml
  99. 4
      msa/migrator/pom.xml
  100. 4
      msa/monitoring/pom.xml

6
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");

4
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);
}

53
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;

10
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);

80
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<EntityGroupInfo> 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<EntityGroupInfo> userGroupOptional = entityGroupService.findEntityGroupInfoByTypeAndName(getTenantId(), shareGroupRequest.getOwnerId(),
EntityType.USER, EntityGroup.GROUP_ALL_NAME);
Optional<EntityGroupInfo> 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<RoleId> roleIds;
List<Role> 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<EntityGroupInfo> userGroupOptional = entityGroupService.findEntityGroupInfoByTypeAndName(getTenantId(), shareGroupRequest.getOwnerId(),
EntityType.USER, EntityGroup.GROUP_ALL_NAME);
Optional<EntityGroupInfo> 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<EntityGroupInfo> 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<Role> resolveRoles(ShareGroupRequest shareGroupRequest) throws ThingsboardException {
List<Role> 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<Operation> 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<Operation> toRoleOperations(Role role) {
CollectionType collectionType = TypeFactory.defaultInstance().constructCollectionType(List.class, Operation.class);
List<Operation> roleOperations = JacksonUtil.readValue(role.getPermissions().toString(), collectionType);
return JacksonUtil.readValue(role.getPermissions().toString(), collectionType);
}
private void shareGroup(Role role, EntityGroup userGroup, EntityGroup entityGroup, Set<Operation> mergedOperations) throws ThingsboardException {
List<Operation> 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);

13
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();
}
}

43
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<GroupPermission> permissions) throws ThingsboardException, ExecutionException, InterruptedException {
TenantId tenantId = getCurrentUser().getTenantId();
accessControlService.checkPermission(getCurrentUser(), Resource.GROUP_PERMISSION, Operation.READ);
List<GroupPermissionInfo> permissionInfoList = groupPermissionService.loadUserGroupPermissionInfoListAsync(tenantId, permissions).get();
List<GroupPermission> readablePermissions = permissions.stream().filter(this::isReadableEntityGroup).toList();
List<GroupPermissionInfo> 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,

3
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<NotificationTargetId> targets = notificationRequest.getTargets().stream()
.map(NotificationTargetId::new)
.toList();

17
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<UUID> targets : notificationRule.getRecipientsConfig().getTargetsTable().values()) {
for (UUID targetId : targets) {
checkNotificationTargetId(new NotificationTargetId(targetId), Operation.READ);
}
}
return doSaveAndLog(EntityType.NOTIFICATION_RULE, notificationRule, notificationRuleService::saveNotificationRule);
}

1
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);
}

8
application/src/main/java/org/thingsboard/server/controller/ReportController.java

@ -248,9 +248,10 @@ public class ReportController extends BaseController {
public ResponseEntity<ByteArrayResource> 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();

3
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<ResponseEntity> response = new DeferredResult<>();
accessValidator.validate(currentUser, Operation.WRITE, entityId, new HttpValidationCallback(response, new FutureCallback<DeferredResult<ResponseEntity>>() {
@Override

24
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"));
}
}

3
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());

41
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<GroupPermission> 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);

4
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);
}

2
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());

2
application/src/main/java/org/thingsboard/server/service/install/update/EntityViewGroupAllUpdater.java

@ -31,7 +31,7 @@ class EntityViewGroupAllUpdater extends EntityGroupAllPaginatedUpdater<EntityVie
@Override
protected void unassignFromCustomer(EntityView entity) {
entity.setCustomerId(new CustomerId(CustomerId.NULL_UUID));
entityViewService.saveEntityView(entity);
entityViewService.saveEntityView(entity, false);
}
@Override

115
application/src/main/java/org/thingsboard/server/service/iot_hub/DefaultIotHubService.java

@ -13,12 +13,17 @@ import org.springframework.stereotype.Service;
import org.thingsboard.common.util.ExceptionUtil;
import org.thingsboard.common.util.JacksonUtil;
import org.thingsboard.server.common.data.Customer;
import org.thingsboard.server.common.data.Dashboard;
import org.thingsboard.server.common.data.Device;
import org.thingsboard.server.common.data.DeviceProfile;
import org.thingsboard.server.common.data.HasTenantId;
import org.thingsboard.server.common.data.EntityType;
import org.thingsboard.server.common.data.asset.AssetProfile;
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;
import org.thingsboard.server.common.data.cf.configuration.geofencing.GeofencingCalculatedFieldConfiguration;
import org.thingsboard.server.common.data.converter.Converter;
import org.thingsboard.server.common.data.exception.ThingsboardException;
import org.thingsboard.server.common.data.group.EntityGroup;
import org.thingsboard.server.common.data.group.EntityGroupInfo;
@ -257,7 +262,7 @@ public class DefaultIotHubService implements IotHubService {
}
private EntityGroupInfo checkEntityGroup(SecurityUser user, EntityGroupId entityGroupId) throws ThingsboardException {
EntityGroupInfo entityGroup = entityGroupService.findEntityGroupInfoById(user.getTenantId(), entityGroupId);
EntityGroupInfo entityGroup = entityGroupService.findEntityGroupInfoByTenantIdAndId(user.getTenantId(), entityGroupId);
if (entityGroup == null) {
throw new IllegalArgumentException("Entity group with id [" + entityGroupId + "] is not found");
}
@ -274,6 +279,7 @@ public class DefaultIotHubService implements IotHubService {
}
calculatedField.setId(null);
calculatedField.setTenantId(tenantId);
mapTenantReferences(calculatedField, tenantId);
if (data != null && data.has("entityId")) {
EntityId entityId = JacksonUtil.treeToValue(data.get("entityId"), EntityId.class);
calculatedField.setEntityId(entityId);
@ -298,6 +304,7 @@ public class DefaultIotHubService implements IotHubService {
}
alarmRule.setId(null);
alarmRule.setTenantId(tenantId);
mapTenantReferences(alarmRule, tenantId);
if (data != null && data.has("entityId")) {
EntityId entityId = JacksonUtil.treeToValue(data.get("entityId"), EntityId.class);
alarmRule.setEntityId(entityId);
@ -537,6 +544,7 @@ public class DefaultIotHubService implements IotHubService {
existing.setName(newCf.getName());
existing.setType(newCf.getType());
existing.setConfiguration(newCf.getConfiguration());
mapTenantReferences(existing, tenantId);
tbCalculatedFieldService.save(existing, user);
}
@ -557,9 +565,26 @@ public class DefaultIotHubService implements IotHubService {
existing.setName(newCf.getName());
existing.setType(newCf.getType());
existing.setConfiguration(newCf.getConfiguration());
mapTenantReferences(existing, tenantId);
tbCalculatedFieldService.save(existing, user);
}
private void mapTenantReferences(CalculatedField calculatedField, TenantId tenantId) {
if (calculatedField.getConfiguration() instanceof GeofencingCalculatedFieldConfiguration geofencingCfg) {
geofencingCfg.getZoneGroups().values().forEach(zoneGroupConfiguration -> {
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<EntityId> 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);
}
}

9
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<NotificationTarget> 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<NotificationChannel> channels, NotificationCenter webNotificationChannel) {
this.channels = channels.stream().collect(Collectors.toMap(NotificationChannel::getDeliveryMethod, c -> c));

17
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");
}

2
application/src/main/java/org/thingsboard/server/service/scheduler/DefaultSchedulerService.java

@ -274,7 +274,7 @@ public class DefaultSchedulerService extends AbstractPartitionBasedService<Tenan
deviceService.saveDevice(device);
break;
case ENTITY_GROUP:
EntityGroup deviceGroup = entityGroupService.findEntityGroupById(tenantId, (EntityGroupId) originatorId);
EntityGroup deviceGroup = entityGroupService.findEntityGroupInfoByTenantIdAndId(tenantId, (EntityGroupId) originatorId);
if (deviceGroup == null) {
throw new RuntimeException("Failed to process event: Device group with id [" + originatorId + "] not found!");
}

2
application/src/main/java/org/thingsboard/server/service/security/AccessValidator.java

@ -647,7 +647,7 @@ public class AccessValidator {
if (currentUser.isSystemAdmin()) {
callback.onSuccess(ValidationResult.accessDenied(SYSTEM_ADMINISTRATOR_IS_NOT_ALLOWED_TO_PERFORM_THIS_OPERATION));
} else {
ListenableFuture<EntityGroupInfo> entityGroupFuture = entityGroupService.findEntityGroupInfoByIdAsync(currentUser.getTenantId(), new EntityGroupId(entityId.getId()));
ListenableFuture<EntityGroupInfo> 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!");

11
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());

4
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);
}

2
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);

20
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){

30
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<String, String> values = Map.of(
"entitiesVersionControl", "{\"repositoryUri\":\"repo1\",\"defaultBranch\":\"main\"}",
"autoCommitSettings", "{}");
for (Map.Entry<String, String> 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();

26
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<AlarmRuleDefinition> 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");

51
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<ApiKeyInfo> 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<ApiKeyInfo> 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);

30
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());

62
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<CalculatedField> 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<String, Argument> 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<String, Argument> 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<String, Argument> 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;
}
}

114
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<EntityInfo> 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<EntityInfo> 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);
}

195
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<DashboardReportData> 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());
}
}

2
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();

473
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<EntityInfo> 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<EntityInfo> 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<RoleId> findSharedRoleIds(EntityGroup entityGroup) {
return groupPermissionService.findGroupPermissionByTenantIdAndEntityGroupId(tenantId, entityGroup.getId(), new PageLink(100))
.getData().stream().map(GroupPermission::getRoleId).collect(Collectors.toList());
}
private List<EntityGroupId> findSharedUserGroupIds(EntityGroup entityGroup) {
return groupPermissionService.findGroupPermissionByTenantIdAndEntityGroupId(tenantId, entityGroup.getId(), new PageLink(100))
.getData().stream().map(GroupPermission::getUserGroupId).collect(Collectors.toList());
}
}

89
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);

223
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<GroupPermission> 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<GroupPermissionInfo> 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<GroupPermissionInfo> 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<GroupPermissionInfo> storedInfos = doGetTyped("/api/userGroup/" + tenantAdminsGroup.getId() + "/groupPermissions",
new TypeReference<>() {});
assertThat(storedInfos).isNotEmpty();
assertThat(storedInfos).allSatisfy(info -> assertThat(info.getRole().getTenantId().isSysTenantId()).isTrue());
List<GroupPermission> permissions = storedInfos.stream().map(GroupPermission::new).toList();
List<GroupPermissionInfo> 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<GroupPermissionInfo> 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<GroupPermissionInfo> groupPermissionsInfos, List<? extends EntityId> ownerIds) {
for (GroupPermissionInfo groupPermissionInfo : groupPermissionsInfos) {
assertTrue(ownerIds.contains(groupPermissionInfo.getUserGroupOwnerId()));

32
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());
}

35
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<JsonNode>() {
}, status().isOk());
ArgumentCaptor<TbMsg> 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<TbMsg> consumer = invocation.getArgument(4);

75
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);
}

313
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<UUID> 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<GroupPermissionInfo> 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<String> 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<GroupPermission> 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<GroupPermission> 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,

166
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);
}

35
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();

55
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();

64
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();

45
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<String> attributeKeys = doGetAsyncTyped(keysUrl + "attributes/" + DataConstants.SERVER_SCOPE, new TypeReference<>() {});
Assert.assertTrue(attributeKeys.isEmpty());
List<String> timeseriesKeys = doGetAsyncTyped(keysUrl + "timeseries", new TypeReference<>() {});
Assert.assertTrue(timeseriesKeys.isEmpty());
});
}
}

17
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);

35
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();
}
}

377
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<CalculatedField> 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<CalculatedField> 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<CalculatedField> 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<CalculatedField> 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<CalculatedField> 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<ILoggingEvent> 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());
}
}

36
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<NotificationRequestStats> future = SettableFuture.create();
notificationCenter.processNotificationRequest(notificationRequest.getTenantId(), notificationRequest, new FutureCallback<>() {

131
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<UUID> 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> R checkNotificationAfter(Callable<R> action, BiConsumer<Notification, R> check) throws Exception {
if (getWsClient().getLastDataUpdate() == null) {
getWsClient().subscribeForUnreadNotifications(10).waitForReply(true);

95
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));
}

15
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();

62
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");

131
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<Map<String, String>> 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<String, String> 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));
}
}

35
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;
}
}

2
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", "");

73
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;
}
}

4
common/dao-api/src/main/java/org/thingsboard/server/dao/group/EntityGroupService.java

@ -37,6 +37,10 @@ public interface EntityGroupService extends EntityDaoService {
ListenableFuture<EntityGroupInfo> findEntityGroupInfoByIdAsync(TenantId tenantId, EntityGroupId entityGroupId);
EntityGroupInfo findEntityGroupInfoByTenantIdAndId(TenantId tenantId, EntityGroupId entityGroupId);
ListenableFuture<EntityGroupInfo> findEntityGroupInfoByTenantIdAndIdAsync(TenantId tenantId, EntityGroupId entityGroupId);
EntityGroup saveEntityGroup(TenantId tenantId, EntityId parentEntityId, EntityGroup entityGroup);
EntityGroup createEntityGroupAll(TenantId tenantId, EntityId parentEntityId, EntityType groupType);

2
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) {

3
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);

9
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();

65
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;
}
}

36
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);
}
}

7
dao/pom.xml

@ -288,11 +288,4 @@
</plugin>
</plugins>
</build>
<repositories>
<repository>
<id>thingsboard-repo</id>
<url>https://repo.thingsboard.io/artifactory/libs-release-public</url>
</repository>
</repositories>
</project>

20
dao/src/main/java/org/thingsboard/server/dao/group/BaseEntityGroupService.java

@ -183,6 +183,20 @@ public class BaseEntityGroupService extends AbstractCachedEntityService<EntityGr
return entityGroupInfoDao.findByIdAsync(tenantId, entityGroupId.getId());
}
@Override
public EntityGroupInfo findEntityGroupInfoByTenantIdAndId(TenantId tenantId, EntityGroupId entityGroupId) {
log.trace("Executing findEntityGroupInfoByTenantIdAndId, tenantId [{}], entityGroupId [{}]", tenantId, entityGroupId);
validateId(entityGroupId, id -> INCORRECT_ENTITY_GROUP_ID + id);
return entityGroupInfoDao.findByTenantIdAndId(tenantId, entityGroupId.getId());
}
@Override
public ListenableFuture<EntityGroupInfo> 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<EntityGr
if (old == null) {
throw new DataValidationException("Can`t update non existing entity group!");
}
if (!data.getOwnerId().equals(old.getOwnerId())) {
throw new DataValidationException("Entity group owner can't be changed!");
}
if (data.getType() != old.getType()) {
throw new DataValidationException("Entity group type can't be changed!");
}
return old;
}

5
dao/src/main/java/org/thingsboard/server/dao/group/EntityGroupInfoDao.java

@ -2,6 +2,7 @@
// SPDX-License-Identifier: BUSL-1.1
package org.thingsboard.server.dao.group;
import com.google.common.util.concurrent.ListenableFuture;
import org.thingsboard.server.common.data.EntityInfo;
import org.thingsboard.server.common.data.EntityType;
import org.thingsboard.server.common.data.group.EntityGroupInfo;
@ -16,6 +17,10 @@ import java.util.UUID;
public interface EntityGroupInfoDao extends Dao<EntityGroupInfo> {
EntityGroupInfo findByTenantIdAndId(TenantId tenantId, UUID entityGroupId);
ListenableFuture<EntityGroupInfo> findByTenantIdAndIdAsync(TenantId tenantId, UUID entityGroupId);
EntityInfo findEntityGroupEntityInfoById(TenantId tenantId, UUID entityGroupId);
PageData<EntityGroupInfo> findEntityGroupsByType(UUID tenantId, UUID parentEntityId, EntityType parentEntityType, EntityType groupType, PageLink pageLink);

21
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<GroupPermissionInfo> fetchUserGroupPermissionInfoAsync(TenantId tenantId, GroupPermission groupPermission) {
ListenableFuture<Role> roleFuture = roleDao.findByIdAsync(tenantId, groupPermission.getRoleId().getId());
ListenableFuture<Role> 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> entityGroup = entityGroupService.findEntityGroupByIdAsync(tenantId, groupPermission.getEntityGroupId());
ListenableFuture<EntityGroupInfo> 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<GroupPermissionInfo> fetchEntityGroupPermissionInfoAsync(TenantId tenantId, GroupPermission groupPermission) {
ListenableFuture<Role> roleFuture = roleDao.findByIdAsync(tenantId, groupPermission.getRoleId().getId());
ListenableFuture<Role> roleFuture = findRoleAsync(tenantId, groupPermission.getRoleId());
return Futures.transformAsync(roleFuture, role -> {
GroupPermissionInfo groupPermissionInfo = new GroupPermissionInfo(groupPermission);
groupPermissionInfo.setRole(role);
ListenableFuture<EntityGroup> userGroup = entityGroupService.findEntityGroupByIdAsync(tenantId, groupPermission.getUserGroupId());
ListenableFuture<EntityGroupInfo> 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<Role> 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<TenantId, GroupPermission> tenantGroupPermissionRemover = new PaginatedRemover<>() {
@Override

15
dao/src/main/java/org/thingsboard/server/dao/menu/CustomMenuServiceImpl.java

@ -185,8 +185,10 @@ public class CustomMenuServiceImpl extends AbstractCachedEntityService<CustomMen
return switch (customMenuInfo.getAssigneeType()) {
case NO_ASSIGN, ALL, USER_GROUPS -> 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<CustomMen
return null;
}
if (user.getCustomMenuId() != null) {
CustomMenu customMenu = findCustomMenuById(tenantId, user.getCustomMenuId());
CustomMenu customMenu = findTenantCustomMenu(tenantId, user.getCustomMenuId());
if (customMenu != null) {
return customMenu;
}
@ -365,13 +367,22 @@ public class CustomMenuServiceImpl extends AbstractCachedEntityService<CustomMen
return null;
}
private CustomMenu findTenantCustomMenu(TenantId tenantId, CustomMenuId customMenuId) {
CustomMenu customMenu = findCustomMenuById(tenantId, customMenuId);
return customMenu != null && isAvailableToTenant(customMenu, tenantId) ? customMenu : null;
}
private static boolean isAvailableToTenant(CustomMenuInfo customMenu, TenantId tenantId) {
return customMenu.getTenantId().isSysTenantId() || customMenu.getTenantId().equals(tenantId);
}
private CustomMenu findCustomerHierarchyCustomMenu(TenantId tenantId, CustomerId customerId) {
CustomMenu result = findDefaultCustomMenuByScope(tenantId, customerId, CMScope.CUSTOMER);
if (result == null) {
Customer customer = customerService.findCustomerById(tenantId, customerId);
CustomMenuId customerCustomMenuId = customer.getCustomMenuId();
if (customerCustomMenuId != null) {
result = findCustomMenuById(tenantId, customerCustomMenuId);
result = findTenantCustomMenu(tenantId, customerCustomMenuId);
}
if (result == null) {
if (customer.isSubCustomer()) {

4
dao/src/main/java/org/thingsboard/server/dao/service/validator/AdminSettingsDataValidator.java

@ -29,6 +29,10 @@ public class AdminSettingsDataValidator extends DataValidator<AdminSettings> {
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!");
}

46
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<CalculatedField> {
private static final Set<EntityType> 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<CalculatedField>
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<CalculatedField>
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<CalculatedField>
}
}
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.<HasTenantId>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!");
}
}
}

22
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<EntityView> {
@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<EntityView> {
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)) {

10
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<GroupPermission> {
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<GroupPermission>
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<GroupPermission>
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<GroupPermission>
}
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!");
}

14
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<EntityGroupInfoEntity, UUID> {
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<EntityGroupInfo
@Query("SELECT e FROM EntityGroupInfoEntity e " +
"WHERE e.id IN :entityGroupIds " +
"AND " + OWNED_WITHIN_TENANT + " " +
"AND (:textSearch IS NULL OR ilike(e.name, CONCAT('%', :textSearch, '%')) = true)")
Page<EntityGroupInfoEntity> findEntityGroupsByIds(@Param("entityGroupIds") List<UUID> entityGroupIds,
Page<EntityGroupInfoEntity> findEntityGroupsByIds(@Param("tenantId") UUID tenantId,
@Param("entityGroupIds") List<UUID> 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<EntityInfo> findEntityGroupEntityInfosByIds(@Param("entityGroupIds") List<UUID> entityGroupIds,
Page<EntityInfo> findEntityGroupEntityInfosByIds(@Param("tenantId") UUID tenantId,
@Param("entityGroupIds") List<UUID> entityGroupIds,
@Param("textSearch") String textSearch,
Pageable pageable);

13
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<EntityGroupInfoEntity,
return entityGroupInfoRepository;
}
@Override
public EntityGroupInfo findByTenantIdAndId(TenantId tenantId, UUID entityGroupId) {
return DaoUtil.getData(entityGroupInfoRepository.findByTenantIdAndId(tenantId.getId(), entityGroupId));
}
@Override
public ListenableFuture<EntityGroupInfo> 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<EntityGroupInfoEntity,
public PageData<EntityGroupInfo> findEntityGroupsByIds(UUID tenantId, List<UUID> entityGroupIds, PageLink pageLink) {
return DaoUtil.toPageData(entityGroupInfoRepository
.findEntityGroupsByIds(
tenantId,
entityGroupIds,
pageLink.getTextSearch(),
DaoUtil.toPageable(pageLink)));
@ -99,6 +111,7 @@ public class JpaEntityGroupInfoDao extends JpaAbstractDao<EntityGroupInfoEntity,
public PageData<EntityInfo> findEntityGroupEntityInfosByIds(UUID tenantId, List<UUID> entityGroupIds, PageLink pageLink) {
return DaoUtil.pageToPageData(entityGroupInfoRepository
.findEntityGroupEntityInfosByIds(
tenantId,
entityGroupIds,
pageLink.getTextSearch(),
DaoUtil.toPageable(pageLink)));

57
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;

82
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<ListenableFuture<Device>> 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<AttributesSaveResult> saveStringAttribute(EntityId entityId, String key, String value, AttributeScope scope) {
KvEntry attrValue = new StringDataEntry(key, value);
AttributeKvEntry attr = new BaseAttributeKvEntry(attrValue, 42L);

14
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

43
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());
}
}
@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;
}
}

110
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.<Device>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<String, Argument> 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;
}
}

91
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<DeviceId> 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;
}
}

4
msa/edqs/pom.xml

@ -137,7 +137,7 @@
<arguments>
<argument>tag</argument>
<argument>${docker.repo}/${docker.name}:latest</argument>
<argument>${docker.repo}/${docker.name}:${project.version}</argument>
<argument>${docker.repo}/${docker.name}:${docker.version.tag}</argument>
</arguments>
</configuration>
</execution>
@ -184,7 +184,7 @@
<executable>docker</executable>
<arguments>
<argument>push</argument>
<argument>${docker.repo}/${docker.name}:${project.version}</argument>
<argument>${docker.repo}/${docker.name}:${docker.version.tag}</argument>
</arguments>
</configuration>
</execution>

4
msa/integration/apache-pulsar/pom.xml

@ -140,7 +140,7 @@
<arguments>
<argument>tag</argument>
<argument>${docker.repo}/${docker.name}:latest</argument>
<argument>${docker.repo}/${docker.name}:${project.version}</argument>
<argument>${docker.repo}/${docker.name}:${docker.version.tag}</argument>
</arguments>
</configuration>
</execution>
@ -187,7 +187,7 @@
<executable>docker</executable>
<arguments>
<argument>push</argument>
<argument>${docker.repo}/${docker.name}:${project.version}</argument>
<argument>${docker.repo}/${docker.name}:${docker.version.tag}</argument>
</arguments>
</configuration>
</execution>

4
msa/integration/aws/pom.xml

@ -140,7 +140,7 @@
<arguments>
<argument>tag</argument>
<argument>${docker.repo}/${docker.name}:latest</argument>
<argument>${docker.repo}/${docker.name}:${project.version}</argument>
<argument>${docker.repo}/${docker.name}:${docker.version.tag}</argument>
</arguments>
</configuration>
</execution>
@ -187,7 +187,7 @@
<executable>docker</executable>
<arguments>
<argument>push</argument>
<argument>${docker.repo}/${docker.name}:${project.version}</argument>
<argument>${docker.repo}/${docker.name}:${docker.version.tag}</argument>
</arguments>
</configuration>
</execution>

4
msa/integration/azure/pom.xml

@ -140,7 +140,7 @@
<arguments>
<argument>tag</argument>
<argument>${docker.repo}/${docker.name}:latest</argument>
<argument>${docker.repo}/${docker.name}:${project.version}</argument>
<argument>${docker.repo}/${docker.name}:${docker.version.tag}</argument>
</arguments>
</configuration>
</execution>
@ -187,7 +187,7 @@
<executable>docker</executable>
<arguments>
<argument>push</argument>
<argument>${docker.repo}/${docker.name}:${project.version}</argument>
<argument>${docker.repo}/${docker.name}:${docker.version.tag}</argument>
</arguments>
</configuration>
</execution>

4
msa/integration/coap/pom.xml

@ -140,7 +140,7 @@
<arguments>
<argument>tag</argument>
<argument>${docker.repo}/${docker.name}:latest</argument>
<argument>${docker.repo}/${docker.name}:${project.version}</argument>
<argument>${docker.repo}/${docker.name}:${docker.version.tag}</argument>
</arguments>
</configuration>
</execution>
@ -187,7 +187,7 @@
<executable>docker</executable>
<arguments>
<argument>push</argument>
<argument>${docker.repo}/${docker.name}:${project.version}</argument>
<argument>${docker.repo}/${docker.name}:${docker.version.tag}</argument>
</arguments>
</configuration>
</execution>

4
msa/integration/executor/pom.xml

@ -140,7 +140,7 @@
<arguments>
<argument>tag</argument>
<argument>${docker.repo}/${docker.name}:latest</argument>
<argument>${docker.repo}/${docker.name}:${project.version}</argument>
<argument>${docker.repo}/${docker.name}:${docker.version.tag}</argument>
</arguments>
</configuration>
</execution>
@ -187,7 +187,7 @@
<executable>docker</executable>
<arguments>
<argument>push</argument>
<argument>${docker.repo}/${docker.name}:${project.version}</argument>
<argument>${docker.repo}/${docker.name}:${docker.version.tag}</argument>
</arguments>
</configuration>
</execution>

4
msa/integration/http/pom.xml

@ -140,7 +140,7 @@
<arguments>
<argument>tag</argument>
<argument>${docker.repo}/${docker.name}:latest</argument>
<argument>${docker.repo}/${docker.name}:${project.version}</argument>
<argument>${docker.repo}/${docker.name}:${docker.version.tag}</argument>
</arguments>
</configuration>
</execution>
@ -187,7 +187,7 @@
<executable>docker</executable>
<arguments>
<argument>push</argument>
<argument>${docker.repo}/${docker.name}:${project.version}</argument>
<argument>${docker.repo}/${docker.name}:${docker.version.tag}</argument>
</arguments>
</configuration>
</execution>

4
msa/integration/kafka/pom.xml

@ -140,7 +140,7 @@
<arguments>
<argument>tag</argument>
<argument>${docker.repo}/${docker.name}:latest</argument>
<argument>${docker.repo}/${docker.name}:${project.version}</argument>
<argument>${docker.repo}/${docker.name}:${docker.version.tag}</argument>
</arguments>
</configuration>
</execution>
@ -187,7 +187,7 @@
<executable>docker</executable>
<arguments>
<argument>push</argument>
<argument>${docker.repo}/${docker.name}:${project.version}</argument>
<argument>${docker.repo}/${docker.name}:${docker.version.tag}</argument>
</arguments>
</configuration>
</execution>

4
msa/integration/mqtt/pom.xml

@ -140,7 +140,7 @@
<arguments>
<argument>tag</argument>
<argument>${docker.repo}/${docker.name}:latest</argument>
<argument>${docker.repo}/${docker.name}:${project.version}</argument>
<argument>${docker.repo}/${docker.name}:${docker.version.tag}</argument>
</arguments>
</configuration>
</execution>
@ -187,7 +187,7 @@
<executable>docker</executable>
<arguments>
<argument>push</argument>
<argument>${docker.repo}/${docker.name}:${project.version}</argument>
<argument>${docker.repo}/${docker.name}:${docker.version.tag}</argument>
</arguments>
</configuration>
</execution>

4
msa/integration/opc-ua/pom.xml

@ -140,7 +140,7 @@
<arguments>
<argument>tag</argument>
<argument>${docker.repo}/${docker.name}:latest</argument>
<argument>${docker.repo}/${docker.name}:${project.version}</argument>
<argument>${docker.repo}/${docker.name}:${docker.version.tag}</argument>
</arguments>
</configuration>
</execution>
@ -187,7 +187,7 @@
<executable>docker</executable>
<arguments>
<argument>push</argument>
<argument>${docker.repo}/${docker.name}:${project.version}</argument>
<argument>${docker.repo}/${docker.name}:${docker.version.tag}</argument>
</arguments>
</configuration>
</execution>

8
msa/integration/pom.xml

@ -54,7 +54,7 @@
<properties>
<!-- With -Dsbom.skip=false, sbom-maven-plugin attaches an SBOM to each image once it is pushed: the tags are those pushed below -->
<sbom.integration-image.phase>${docker.push-integration-arm-amd-image.phase}</sbom.integration-image.phase>
<sbom.integration-image.tags>latest,${project.version}</sbom.integration-image.tags>
<sbom.integration-image.tags>latest,${docker.version.tag}</sbom.integration-image.tags>
</properties>
<build>
<plugins>
@ -96,7 +96,7 @@
<argument>buildx</argument>
<argument>build</argument>
<argument>-t</argument>
<argument>${docker.repo}/${docker.name}:${project.version}</argument>
<argument>${docker.repo}/${docker.name}:${docker.version.tag}</argument>
<argument>--platform=linux/amd64,linux/arm64</argument>
<argument>-o</argument>
<argument>type=registry</argument>
@ -121,7 +121,7 @@
<docker.skip.latest.tag>false</docker.skip.latest.tag>
<!-- With -Dsbom.skip=false, sbom-maven-plugin attaches an SBOM to each image once it is pushed: the tags are those pushed below -->
<sbom.integration-image.phase>${docker.push-integration-arm-amd-image.phase}</sbom.integration-image.phase>
<sbom.integration-image.tags>${sbom.image.latestTag},${project.version},${docker.lts.tag}</sbom.integration-image.tags>
<sbom.integration-image.tags>${sbom.image.latestTag},${docker.version.tag},${docker.lts.tag}</sbom.integration-image.tags>
</properties>
<build>
<plugins>
@ -164,7 +164,7 @@
<argument>buildx</argument>
<argument>build</argument>
<argument>-t</argument>
<argument>${docker.repo}/${docker.name}:${project.version}</argument>
<argument>${docker.repo}/${docker.name}:${docker.version.tag}</argument>
<argument>--platform=linux/amd64,linux/arm64</argument>
<argument>-o</argument>
<argument>type=registry</argument>

4
msa/integration/pubsub/pom.xml

@ -140,7 +140,7 @@
<arguments>
<argument>tag</argument>
<argument>${docker.repo}/${docker.name}:latest</argument>
<argument>${docker.repo}/${docker.name}:${project.version}</argument>
<argument>${docker.repo}/${docker.name}:${docker.version.tag}</argument>
</arguments>
</configuration>
</execution>
@ -187,7 +187,7 @@
<executable>docker</executable>
<arguments>
<argument>push</argument>
<argument>${docker.repo}/${docker.name}:${project.version}</argument>
<argument>${docker.repo}/${docker.name}:${docker.version.tag}</argument>
</arguments>
</configuration>
</execution>

4
msa/integration/rabbitmq/pom.xml

@ -140,7 +140,7 @@
<arguments>
<argument>tag</argument>
<argument>${docker.repo}/${docker.name}:latest</argument>
<argument>${docker.repo}/${docker.name}:${project.version}</argument>
<argument>${docker.repo}/${docker.name}:${docker.version.tag}</argument>
</arguments>
</configuration>
</execution>
@ -187,7 +187,7 @@
<executable>docker</executable>
<arguments>
<argument>push</argument>
<argument>${docker.repo}/${docker.name}:${project.version}</argument>
<argument>${docker.repo}/${docker.name}:${docker.version.tag}</argument>
</arguments>
</configuration>
</execution>

4
msa/integration/tcp-udp/pom.xml

@ -140,7 +140,7 @@
<arguments>
<argument>tag</argument>
<argument>${docker.repo}/${docker.name}:latest</argument>
<argument>${docker.repo}/${docker.name}:${project.version}</argument>
<argument>${docker.repo}/${docker.name}:${docker.version.tag}</argument>
</arguments>
</configuration>
</execution>
@ -187,7 +187,7 @@
<executable>docker</executable>
<arguments>
<argument>push</argument>
<argument>${docker.repo}/${docker.name}:${project.version}</argument>
<argument>${docker.repo}/${docker.name}:${docker.version.tag}</argument>
</arguments>
</configuration>
</execution>

4
msa/integration/tuya/pom.xml

@ -140,7 +140,7 @@
<arguments>
<argument>tag</argument>
<argument>${docker.repo}/${docker.name}:latest</argument>
<argument>${docker.repo}/${docker.name}:${project.version}</argument>
<argument>${docker.repo}/${docker.name}:${docker.version.tag}</argument>
</arguments>
</configuration>
</execution>
@ -187,7 +187,7 @@
<executable>docker</executable>
<arguments>
<argument>push</argument>
<argument>${docker.repo}/${docker.name}:${project.version}</argument>
<argument>${docker.repo}/${docker.name}:${docker.version.tag}</argument>
</arguments>
</configuration>
</execution>

4
msa/js-executor/pom.xml

@ -221,7 +221,7 @@
<arguments>
<argument>tag</argument>
<argument>${docker.repo}/${docker.name}:latest</argument>
<argument>${docker.repo}/${docker.name}:${project.version}</argument>
<argument>${docker.repo}/${docker.name}:${docker.version.tag}</argument>
</arguments>
</configuration>
</execution>
@ -332,7 +332,7 @@
<executable>docker</executable>
<arguments>
<argument>push</argument>
<argument>${docker.repo}/${docker.name}:${project.version}</argument>
<argument>${docker.repo}/${docker.name}:${docker.version.tag}</argument>
</arguments>
</configuration>
</execution>

4
msa/migrator/pom.xml

@ -137,7 +137,7 @@
<arguments>
<argument>tag</argument>
<argument>${docker.repo}/${docker.name}:latest</argument>
<argument>${docker.repo}/${docker.name}:${project.version}</argument>
<argument>${docker.repo}/${docker.name}:${docker.version.tag}</argument>
</arguments>
</configuration>
</execution>
@ -179,7 +179,7 @@
<executable>docker</executable>
<arguments>
<argument>push</argument>
<argument>${docker.repo}/${docker.name}:${project.version}</argument>
<argument>${docker.repo}/${docker.name}:${docker.version.tag}</argument>
</arguments>
</configuration>
</execution>

4
msa/monitoring/pom.xml

@ -138,7 +138,7 @@
<arguments>
<argument>tag</argument>
<argument>${docker.repo}/${docker.name}:latest</argument>
<argument>${docker.repo}/${docker.name}:${project.version}</argument>
<argument>${docker.repo}/${docker.name}:${docker.version.tag}</argument>
</arguments>
</configuration>
</execution>
@ -185,7 +185,7 @@
<executable>docker</executable>
<arguments>
<argument>push</argument>
<argument>${docker.repo}/${docker.name}:${project.version}</argument>
<argument>${docker.repo}/${docker.name}:${docker.version.tag}</argument>
</arguments>
</configuration>
</execution>

Some files were not shown because too many files changed in this diff

Loading…
Cancel
Save