Browse Source

Merge branch 'hotfix-4.4' into fix/license-headers-hotfix-4.4

pull/16844/head
Viacheslav Klimov 3 weeks ago
parent
commit
de265d2db7
Failed to extract signature
  1. 6
      application/src/main/java/org/thingsboard/server/controller/BaseController.java
  2. 22
      application/src/main/java/org/thingsboard/server/service/iot_hub/DefaultIotHubService.java
  3. 4
      application/src/main/java/org/thingsboard/server/utils/CalculatedFieldUtils.java
  4. 29
      application/src/test/java/org/thingsboard/server/controller/AlarmRuleControllerTest.java
  5. 65
      application/src/test/java/org/thingsboard/server/controller/CalculatedFieldControllerTest.java
  6. 35
      application/src/test/java/org/thingsboard/server/edge/CalculatedFieldEdgeTest.java
  7. 169
      application/src/test/java/org/thingsboard/server/service/iot_hub/DefaultIotHubServiceTest.java
  8. 17
      application/src/test/java/org/thingsboard/server/service/notification/AbstractNotificationApiTest.java
  9. 73
      application/src/test/java/org/thingsboard/server/service/notification/NotificationRuleApiTest.java
  10. 37
      application/src/test/java/org/thingsboard/server/utils/CalculatedFieldUtilsTest.java
  11. 7
      common/data/src/main/java/org/thingsboard/server/common/data/cf/configuration/AlarmCalculatedFieldConfiguration.java
  12. 2
      common/data/src/main/java/org/thingsboard/server/common/data/cf/configuration/Argument.java
  13. 8
      common/data/src/main/java/org/thingsboard/server/common/data/cf/configuration/SimpleCalculatedFieldConfiguration.java
  14. 40
      common/data/src/test/java/org/thingsboard/server/common/data/cf/configuration/AlarmCalculatedFieldConfigurationTest.java
  15. 40
      common/data/src/test/java/org/thingsboard/server/common/data/cf/configuration/SimpleCalculatedFieldConfigurationTest.java
  16. 46
      dao/src/main/java/org/thingsboard/server/dao/service/validator/CalculatedFieldDataValidator.java
  17. 110
      dao/src/test/java/org/thingsboard/server/dao/service/validator/CalculatedFieldDataValidatorTest.java

6
application/src/main/java/org/thingsboard/server/controller/BaseController.java

@ -1140,7 +1140,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 + "'.");
}

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

@ -20,6 +20,8 @@ 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;
@ -272,6 +274,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);
@ -296,6 +299,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);
@ -535,6 +539,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);
}
@ -555,9 +560,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;

4
application/src/main/java/org/thingsboard/server/utils/CalculatedFieldUtils.java

@ -263,10 +263,10 @@ public class CalculatedFieldUtils {
proto.getSingleValueArgumentsList().forEach(argProto ->
state.getArguments().put(argProto.getArgName(), fromSingleValueArgumentProto(argProto)));
proto.getRollingValueArgumentsList().forEach(argProto ->
state.getArguments().put(argProto.getKey(), fromRollingArgumentProto(argProto)));
switch (type) {
case SCRIPT -> proto.getRollingValueArgumentsList().forEach(argProto ->
state.getArguments().put(argProto.getKey(), fromRollingArgumentProto(argProto)));
case GEOFENCING -> proto.getGeofencingArgumentsList().forEach(argProto ->
state.getArguments().put(argProto.getArgName(), fromGeofencingArgumentProto(argProto)));
case PROPAGATION -> {

29
application/src/test/java/org/thingsboard/server/controller/AlarmRuleControllerTest.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.controller;
import com.fasterxml.jackson.core.type.TypeReference;
@ -98,6 +99,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");

65
application/src/test/java/org/thingsboard/server/controller/CalculatedFieldControllerTest.java

@ -1,7 +1,9 @@
// 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.controller;
import com.fasterxml.jackson.core.type.TypeReference;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
@ -41,6 +43,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 +301,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 +430,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 +448,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;
}
}

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

169
application/src/test/java/org/thingsboard/server/service/iot_hub/DefaultIotHubServiceTest.java

@ -16,6 +16,21 @@ import org.mockito.Spy;
import org.mockito.junit.jupiter.MockitoExtension;
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;
@ -24,6 +39,8 @@ import org.thingsboard.server.common.data.id.IntegrationId;
import org.thingsboard.server.common.data.id.IotHubInstalledItemId;
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;
@ -32,6 +49,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;
@ -39,12 +57,14 @@ 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.service.entitiy.dashboard.TbDashboardService;
import org.thingsboard.server.service.entitiy.converter.TbConverterService;
import org.thingsboard.server.service.entitiy.device.TbDeviceService;
import org.thingsboard.server.service.entitiy.device.profile.TbDeviceProfileService;
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;
@ -76,6 +96,10 @@ class DefaultIotHubServiceTest {
@Mock
private IotHubInstalledItemService iotHubInstalledItemService;
@Mock
private TbCalculatedFieldService tbCalculatedFieldService;
@Mock
private CalculatedFieldService calculatedFieldService;
@Mock
private DeviceService deviceService;
@Mock
private EntityService entityService;
@ -461,6 +485,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();

17
application/src/test/java/org/thingsboard/server/service/notification/AbstractNotificationApiTest.java

@ -26,6 +26,7 @@ import org.thingsboard.server.common.data.notification.rule.DefaultNotificationR
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.NotificationRuleTriggerConfig;
import org.thingsboard.server.common.data.notification.rule.trigger.config.NotificationRuleTriggerType;
import org.thingsboard.server.common.data.notification.settings.NotificationDeliveryMethodConfig;
import org.thingsboard.server.common.data.notification.settings.NotificationSettings;
import org.thingsboard.server.common.data.notification.template.NotificationTemplate;
@ -43,14 +44,17 @@ import org.thingsboard.server.dao.notification.NotificationTargetService;
import org.thingsboard.server.dao.notification.NotificationTemplateService;
import org.thingsboard.server.dao.secret.SecretService;
import org.thingsboard.server.dao.sqlts.insert.sql.SqlPartitioningRepository;
import org.thingsboard.server.service.notification.rule.cache.DefaultNotificationRulesCache;
import java.net.URISyntaxException;
import java.util.Arrays;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
import static org.assertj.core.api.Assertions.assertThat;
import static org.awaitility.Awaitility.await;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
public abstract class AbstractNotificationApiTest extends AbstractControllerTest {
@ -64,6 +68,8 @@ public abstract class AbstractNotificationApiTest extends AbstractControllerTest
@Autowired
protected NotificationRuleService notificationRuleService;
@Autowired
protected DefaultNotificationRulesCache notificationRulesCache;
@Autowired
protected NotificationTemplateService notificationTemplateService;
@Autowired
protected NotificationTargetService notificationTargetService;
@ -192,7 +198,16 @@ public abstract class AbstractNotificationApiTest extends AbstractControllerTest
}
protected NotificationRule saveNotificationRule(NotificationRule notificationRule) {
return doPost("/api/notification/rule", notificationRule, NotificationRule.class);
NotificationRule savedRule = doPost("/api/notification/rule", notificationRule, NotificationRule.class);
awaitNotificationRulesCacheUpdate(savedRule.getTenantId(), savedRule.getTriggerType());
return savedRule;
}
// saving a rule evicts the rules cache asynchronously
protected void awaitNotificationRulesCacheUpdate(TenantId tenantId, NotificationRuleTriggerType triggerType) {
await().atMost(TIMEOUT, TimeUnit.SECONDS).pollInterval(10, TimeUnit.MILLISECONDS)
.until(() -> Set.copyOf(notificationRulesCache.getEnabled(tenantId, triggerType))
.equals(Set.copyOf(notificationRuleService.findEnabledNotificationRulesByTenantIdAndTriggerType(tenantId, triggerType))));
}
protected PageData<NotificationRuleInfo> findNotificationRules() throws Exception {

73
application/src/test/java/org/thingsboard/server/service/notification/NotificationRuleApiTest.java

@ -13,6 +13,7 @@ import org.mockito.MockedStatic;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.bean.override.mockito.MockitoSpyBean;
import org.springframework.data.util.Pair;
import org.springframework.test.util.ReflectionTestUtils;
import org.springframework.test.context.TestPropertySource;
import org.thingsboard.common.util.JacksonUtil;
import org.thingsboard.common.util.SystemUtil;
@ -55,6 +56,7 @@ import org.thingsboard.server.common.data.notification.NotificationRequestInfo;
import org.thingsboard.server.common.data.notification.NotificationType;
import org.thingsboard.server.common.data.notification.info.AlarmNotificationInfo;
import org.thingsboard.server.common.data.notification.info.RateLimitsNotificationInfo;
import org.thingsboard.server.common.data.notification.info.ResourcesShortageNotificationInfo;
import org.thingsboard.server.common.data.notification.rule.DefaultNotificationRuleRecipientsConfig;
import org.thingsboard.server.common.data.notification.rule.EscalatedNotificationRuleRecipientsConfig;
import org.thingsboard.server.common.data.notification.rule.NotificationRule;
@ -90,12 +92,10 @@ import org.thingsboard.server.dao.notification.NotificationRequestService;
import org.thingsboard.server.dao.rule.RuleChainService;
import org.thingsboard.server.dao.service.DaoSqlTest;
import org.thingsboard.server.queue.notification.DefaultNotificationDeduplicationService;
import org.thingsboard.server.service.notification.rule.cache.DefaultNotificationRulesCache;
import org.thingsboard.server.service.state.DeviceStateService;
import org.thingsboard.server.service.system.DefaultSystemInfoService;
import org.thingsboard.server.service.telemetry.AlarmSubscriptionService;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@ -123,7 +123,9 @@ import static org.thingsboard.server.common.data.notification.rule.trigger.confi
@TestPropertySource(properties = {
"transport.http.enabled=true",
"notification_system.rules.deduplication_durations=RATE_LIMITS:10000",
"edges.enabled=true"
"edges.enabled=true",
// the real system info job reports resource shortages only once, at startup
"metrics.system_info.persist_frequency=3600"
})
public class NotificationRuleApiTest extends AbstractNotificationApiTest {
@ -140,8 +142,6 @@ public class NotificationRuleApiTest extends AbstractNotificationApiTest {
@Autowired
private NotificationRuleProcessor notificationRuleProcessor;
@Autowired
private DefaultNotificationRulesCache notificationRulesCache;
@Autowired
private DeviceStateService deviceStateService;
@Before
@ -272,7 +272,7 @@ public class NotificationRuleApiTest extends AbstractNotificationApiTest {
Device device = createDevice("Device with alarm", "233");
NotificationTarget target = createNotificationTarget(tenantAdminUserId);
defaultNotifications.create(tenantId, DefaultNotifications.newAlarm, target.getId());
notificationRulesCache.evict(tenantId);
awaitNotificationRulesCacheUpdate(tenantId, NotificationRuleTriggerType.ALARM);
Alarm alarm = new Alarm();
alarm.setSeverity(AlarmSeverity.CRITICAL);
@ -449,7 +449,7 @@ public class NotificationRuleApiTest extends AbstractNotificationApiTest {
defaultNotifications.create(TenantId.SYS_TENANT_ID, DefaultNotifications.exceededRateLimitsForSysadmin, sysadmins.getId());
defaultNotifications.create(TenantId.SYS_TENANT_ID, DefaultNotifications.exceededRateLimits, affectedTenantAdmins.getId());
defaultNotifications.create(TenantId.SYS_TENANT_ID, DefaultNotifications.exceededPerEntityRateLimits, affectedTenantAdmins.getId());
notificationRulesCache.evict(TenantId.SYS_TENANT_ID);
awaitNotificationRulesCacheUpdate(TenantId.SYS_TENANT_ID, NotificationRuleTriggerType.RATE_LIMITS);
int n = 10;
updateDefaultTenantProfileConfig(profileConfiguration -> {
@ -788,14 +788,8 @@ public class NotificationRuleApiTest extends AbstractNotificationApiTest {
createNotificationRule(triggerConfig, "Warning: ${resource} shortage", "${resource} shortage", createNotificationTarget(tenantAdminUserId).getId());
loginTenantAdmin();
// Mock SystemUtil to return 15% memory usage (exceeds 1% threshold)
try (MockedStatic<SystemUtil> mockedSystemUtil = mockStatic(SystemUtil.class)) {
mockedSystemUtil.when(SystemUtil::getMemoryUsage).thenReturn(Optional.of(15));
Method method = DefaultSystemInfoService.class.getDeclaredMethod("saveCurrentMonolithSystemInfo");
method.setAccessible(true);
method.invoke(systemInfoService);
}
// 15% RAM exceeds the 1% threshold, CPU and storage stay below 100%
saveMonolithSystemInfo(15);
await().atMost(TIMEOUT, TimeUnit.SECONDS).until(() -> getMyNotifications(false, 100).size() == 1);
Notification notification = getMyNotifications(false, 100).get(0);
@ -814,29 +808,32 @@ public class NotificationRuleApiTest extends AbstractNotificationApiTest {
.build();
createNotificationRule(triggerConfig, "Warning: ${resource} shortage", "${resource} shortage", sysadmins.getId());
assertThat(getMyNotifications(false, 100)).size().isZero();
// the real system info job reports RAM under this node's service id, so count only this test's
String serviceId = "test-service-" + UUID.randomUUID();
for (int i = 0; i < 10; i++) {
notificationRuleProcessor.process(ResourcesShortageTrigger.builder()
.resource(Resource.RAM)
.usage(15L)
.serviceType("serviceType")
.serviceId("serviceId")
.serviceId(serviceId)
.build());
TimeUnit.MILLISECONDS.sleep(300);
}
await().atMost(TIMEOUT, TimeUnit.SECONDS).until(() -> getMyNotifications(false, 100).size() == 1);
Notification notification = getMyNotifications(false, 100).get(0);
List<Notification> notifications = await().atMost(TIMEOUT, TimeUnit.SECONDS)
.until(() -> getResourcesShortageNotifications(serviceId), list -> list.size() == 1);
Notification notification = notifications.get(0);
assertThat(notification.getSubject()).isEqualTo("Warning: RAM shortage");
assertThat(notification.getText()).isEqualTo("RAM shortage");
// deduplication is 1 minute, no new message is exp
// deduplication is 1 hour, no new message is expected
notificationRuleProcessor.process(ResourcesShortageTrigger.builder()
.resource(Resource.RAM)
.usage(5L)
.serviceType("serviceType")
.serviceId("serviceId")
.serviceId(serviceId)
.build());
await("").atMost(TIMEOUT, TimeUnit.SECONDS).untilAsserted(() -> assertThat(getMyNotifications(false, 100)).size().isOne());
await().during(3, TimeUnit.SECONDS).atMost(TIMEOUT, TimeUnit.SECONDS)
.untilAsserted(() -> assertThat(getResourcesShortageNotifications(serviceId)).hasSize(1));
}
@Test
@ -851,16 +848,7 @@ public class NotificationRuleApiTest extends AbstractNotificationApiTest {
NotificationRule rule = createNotificationRule(triggerConfig, "Warning: ${resource} shortage", "${resource} shortage", sysadmins.getId());
// Mock SystemUtil to return 15% usages (not exceeds 99% threshold)
Method method;
try (MockedStatic<SystemUtil> mockedSystemUtil = mockStatic(SystemUtil.class)) {
mockedSystemUtil.when(SystemUtil::getMemoryUsage).thenReturn(Optional.of(15));
mockedSystemUtil.when(SystemUtil::getCpuUsage).thenReturn(Optional.of(15));
mockedSystemUtil.when(SystemUtil::getDiscSpaceUsage).thenReturn(Optional.of(15));
method = DefaultSystemInfoService.class.getDeclaredMethod("saveCurrentMonolithSystemInfo");
method.setAccessible(true);
method.invoke(systemInfoService);
}
saveMonolithSystemInfo(15);
TimeUnit.SECONDS.sleep(5);
assertThat(getMyNotifications(false, 100)).size().isZero();
@ -873,7 +861,7 @@ public class NotificationRuleApiTest extends AbstractNotificationApiTest {
rule.setTriggerConfig(triggerConfig);
saveNotificationRule(rule);
method.invoke(systemInfoService);
saveMonolithSystemInfo(15);
await().atMost(TIMEOUT, TimeUnit.SECONDS).until(() -> getMyNotifications(false, 100).size() == 1);
Notification notification = getMyNotifications(false, 100).get(0);
@ -887,7 +875,6 @@ public class NotificationRuleApiTest extends AbstractNotificationApiTest {
triggerConfig.setEntityTypes(Set.of(EntityType.DEVICE));
triggerConfig.setCreated(true);
NotificationRule rule = createNotificationRule(triggerConfig, "Created", "Created", createNotificationTarget(tenantAdminUserId).getId());
notificationRulesCache.evict(tenantId);
assertThat(getMyNotifications(false, 100)).size().isZero();
createDevice("Device 1", "default", "111");
@ -898,7 +885,6 @@ public class NotificationRuleApiTest extends AbstractNotificationApiTest {
rule.setEnabled(false);
saveNotificationRule(rule);
notificationRulesCache.evict(tenantId);
createDevice("Device 2", "default", "222");
TimeUnit.SECONDS.sleep(5);
@ -906,7 +892,6 @@ public class NotificationRuleApiTest extends AbstractNotificationApiTest {
rule.setEnabled(true);
saveNotificationRule(rule);
notificationRulesCache.evict(tenantId);
createDevice("Device 3", "default", "333");
await().atMost(TIMEOUT, TimeUnit.SECONDS)
@ -1067,6 +1052,22 @@ public class NotificationRuleApiTest extends AbstractNotificationApiTest {
}, (notification, r) -> check.accept(notification));
}
private void saveMonolithSystemInfo(int usagePercent) {
try (MockedStatic<SystemUtil> mockedSystemUtil = mockStatic(SystemUtil.class)) {
mockedSystemUtil.when(SystemUtil::getMemoryUsage).thenReturn(Optional.of(usagePercent));
mockedSystemUtil.when(SystemUtil::getCpuUsage).thenReturn(Optional.of(usagePercent));
mockedSystemUtil.when(SystemUtil::getDiscSpaceUsage).thenReturn(Optional.of(usagePercent));
ReflectionTestUtils.invokeMethod(systemInfoService, "saveCurrentMonolithSystemInfo");
}
}
private List<Notification> getResourcesShortageNotifications(String serviceId) throws Exception {
return getMyNotifications(false, 100).stream()
.filter(notification -> notification.getInfo() instanceof ResourcesShortageNotificationInfo info
&& serviceId.equals(info.getServiceId()))
.toList();
}
private PageData<NotificationRequestInfo> findNotificationRequests(EntityType originatorType) {
return notificationRequestService.findNotificationRequestsInfosByTenantIdAndOriginatorType(tenantId, originatorType, new PageLink(100));
}

37
application/src/test/java/org/thingsboard/server/utils/CalculatedFieldUtilsTest.java

@ -4,7 +4,10 @@ package org.thingsboard.server.utils;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.EnumSource;
import org.mockito.junit.jupiter.MockitoExtension;
import org.thingsboard.server.common.data.cf.CalculatedFieldType;
import org.thingsboard.server.common.data.cf.configuration.geofencing.GeofencingPresenceStatus;
import org.thingsboard.server.common.data.id.AssetId;
import org.thingsboard.server.common.data.id.CalculatedFieldId;
@ -19,7 +22,9 @@ import org.thingsboard.server.service.cf.ctx.CalculatedFieldEntityCtxId;
import org.thingsboard.server.service.cf.ctx.state.ArgumentEntry;
import org.thingsboard.server.service.cf.ctx.state.CalculatedFieldCtx;
import org.thingsboard.server.service.cf.ctx.state.CalculatedFieldState;
import org.thingsboard.server.service.cf.ctx.state.ScriptCalculatedFieldState;
import org.thingsboard.server.service.cf.ctx.state.SingleValueArgumentEntry;
import org.thingsboard.server.service.cf.ctx.state.TsRollingArgumentEntry;
import org.thingsboard.server.service.cf.ctx.state.geofencing.GeofencingArgumentEntry;
import org.thingsboard.server.service.cf.ctx.state.geofencing.GeofencingCalculatedFieldState;
import org.thingsboard.server.service.cf.ctx.state.geofencing.GeofencingZoneState;
@ -29,6 +34,7 @@ import org.thingsboard.server.service.cf.ctx.state.propagation.PropagationCalcul
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.UUID;
import static org.assertj.core.api.Assertions.assertThat;
@ -151,4 +157,35 @@ class CalculatedFieldUtilsTest {
assertThat(propagationState.getReadinessStatus()).isNull();
}
@ParameterizedTest
@EnumSource(value = CalculatedFieldType.class, names = {"SCRIPT", "PROPAGATION"})
void toProtoAndFromProto_shouldRestoreTsRollingArgument(CalculatedFieldType type) {
// given
CalculatedFieldEntityCtxId stateId = mock(CalculatedFieldEntityCtxId.class);
given(stateId.tenantId()).willReturn(TENANT_ID);
given(stateId.cfId()).willReturn(CF_ID);
given(stateId.entityId()).willReturn(DEVICE_ID);
TsRollingArgumentEntry rollingArgumentEntry = new TsRollingArgumentEntry(new TreeMap<>(Map.of(1000L, 1.0, 2000L, 0.0)), 2, 604800000L);
CalculatedFieldState state = switch (type) {
case SCRIPT -> new ScriptCalculatedFieldState(DEVICE_ID);
case PROPAGATION -> new PropagationCalculatedFieldState(DEVICE_ID);
default -> throw new IllegalArgumentException("Unexpected CF type: " + type);
};
state.getArguments().put("rollingArgument", rollingArgumentEntry);
// when
CalculatedFieldState restored = CalculatedFieldUtils.fromProto(stateId, toProto(stateId, state));
// then
assertThat(restored).isInstanceOf(state.getClass());
ArgumentEntry restoredArgument = restored.getArguments().get("rollingArgument");
assertThat(restoredArgument).isInstanceOf(TsRollingArgumentEntry.class);
TsRollingArgumentEntry restoredRollingArgument = (TsRollingArgumentEntry) restoredArgument;
assertThat(restoredRollingArgument.getLimit()).isEqualTo(2);
assertThat(restoredRollingArgument.getTimeWindow()).isEqualTo(604800000L);
assertThat(restoredRollingArgument.getTsRecords()).isEqualTo(rollingArgumentEntry.getTsRecords());
}
}

7
common/data/src/main/java/org/thingsboard/server/common/data/cf/configuration/AlarmCalculatedFieldConfiguration.java

@ -46,6 +46,13 @@ public class AlarmCalculatedFieldConfiguration implements ArgumentsBasedCalculat
return CalculatedFieldType.ALARM;
}
@Override
public void validate() {
if (arguments != null && arguments.values().stream().anyMatch(Argument::hasTsRollingArgument)) {
throw new IllegalArgumentException("Calculated field with type: '" + getType() + "' doesn't support TS_ROLLING arguments.");
}
}
@Override
public Output getOutput() {
return null;

2
common/data/src/main/java/org/thingsboard/server/common/data/cf/configuration/Argument.java

@ -35,7 +35,7 @@ public class Argument {
}
public boolean hasTsRollingArgument() {
return ArgumentType.TS_ROLLING.equals(refEntityKey.getType());
return refEntityKey != null && ArgumentType.TS_ROLLING.equals(refEntityKey.getType());
}
}

8
common/data/src/main/java/org/thingsboard/server/common/data/cf/configuration/SimpleCalculatedFieldConfiguration.java

@ -19,4 +19,12 @@ public class SimpleCalculatedFieldConfiguration extends BaseCalculatedFieldConfi
return CalculatedFieldType.SIMPLE;
}
@Override
public void validate() {
super.validate();
if (arguments.values().stream().anyMatch(Argument::hasTsRollingArgument)) {
throw new IllegalArgumentException("Calculated field with type: '" + getType() + "' doesn't support TS_ROLLING arguments.");
}
}
}

40
common/data/src/test/java/org/thingsboard/server/common/data/cf/configuration/AlarmCalculatedFieldConfigurationTest.java

@ -0,0 +1,40 @@
// SPDX-FileCopyrightText: Copyright The Thingsboard Authors
// SPDX-License-Identifier: Apache-2.0
package org.thingsboard.server.common.data.cf.configuration;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.EnumSource;
import org.thingsboard.server.common.data.cf.CalculatedFieldType;
import java.util.Map;
import static org.assertj.core.api.Assertions.assertThatCode;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
public class AlarmCalculatedFieldConfigurationTest {
@Test
void validateShouldThrowWhenTsRollingArgumentIsUsed() {
var cfg = new AlarmCalculatedFieldConfiguration();
Argument argument = new Argument();
argument.setRefEntityKey(new ReferencedEntityKey("key", ArgumentType.TS_ROLLING, null));
cfg.setArguments(Map.of("arg", argument));
assertThatThrownBy(cfg::validate)
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("Calculated field with type: '" + CalculatedFieldType.ALARM + "' doesn't support TS_ROLLING arguments.");
}
@ParameterizedTest
@EnumSource(value = ArgumentType.class, names = {"ATTRIBUTE", "TS_LATEST"})
void validateShouldPassWhenNonRollingArgumentIsUsed(ArgumentType argumentType) {
var cfg = new AlarmCalculatedFieldConfiguration();
Argument argument = new Argument();
argument.setRefEntityKey(new ReferencedEntityKey("key", argumentType, null));
cfg.setArguments(Map.of("arg", argument));
assertThatCode(cfg::validate).doesNotThrowAnyException();
}
}

40
common/data/src/test/java/org/thingsboard/server/common/data/cf/configuration/SimpleCalculatedFieldConfigurationTest.java

@ -0,0 +1,40 @@
// SPDX-FileCopyrightText: Copyright The Thingsboard Authors
// SPDX-License-Identifier: Apache-2.0
package org.thingsboard.server.common.data.cf.configuration;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.EnumSource;
import org.thingsboard.server.common.data.cf.CalculatedFieldType;
import java.util.Map;
import static org.assertj.core.api.Assertions.assertThatCode;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
public class SimpleCalculatedFieldConfigurationTest {
@Test
void validateShouldThrowWhenTsRollingArgumentIsUsed() {
var cfg = new SimpleCalculatedFieldConfiguration();
Argument argument = new Argument();
argument.setRefEntityKey(new ReferencedEntityKey("key", ArgumentType.TS_ROLLING, null));
cfg.setArguments(Map.of("arg", argument));
assertThatThrownBy(cfg::validate)
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("Calculated field with type: '" + CalculatedFieldType.SIMPLE + "' doesn't support TS_ROLLING arguments.");
}
@ParameterizedTest
@EnumSource(value = ArgumentType.class, names = {"ATTRIBUTE", "TS_LATEST"})
void validateShouldPassWhenNonRollingArgumentIsUsed(ArgumentType argumentType) {
var cfg = new SimpleCalculatedFieldConfiguration();
Argument argument = new Argument();
argument.setRefEntityKey(new ReferencedEntityKey("key", argumentType, null));
cfg.setArguments(Map.of("arg", argument));
assertThatCode(cfg::validate).doesNotThrowAnyException();
}
}

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

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

Loading…
Cancel
Save