diff --git a/application/src/main/java/org/thingsboard/server/service/edge/EdgeEntityTenantChecker.java b/application/src/main/java/org/thingsboard/server/service/edge/EdgeEntityTenantChecker.java new file mode 100644 index 0000000000..d497fede3e --- /dev/null +++ b/application/src/main/java/org/thingsboard/server/service/edge/EdgeEntityTenantChecker.java @@ -0,0 +1,78 @@ +// SPDX-FileCopyrightText: Copyright The Thingsboard Authors +// SPDX-License-Identifier: Apache-2.0 +package org.thingsboard.server.service.edge; + +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.stereotype.Component; +import org.thingsboard.server.common.data.HasTenantId; +import org.thingsboard.server.common.data.id.EntityId; +import org.thingsboard.server.common.data.id.TenantId; +import org.thingsboard.server.dao.entity.EntityDaoRegistry; +import org.thingsboard.server.dao.entity.EntityService; +import org.thingsboard.server.exception.DataValidationException; +import org.thingsboard.server.queue.util.TbCoreComponent; + +/** + * Checks that entities referenced by edge messages belong to the edge's tenant. + */ +@Slf4j +@Component +@TbCoreComponent +@RequiredArgsConstructor +public class EdgeEntityTenantChecker { + + private final EntityService entityService; + private final EntityDaoRegistry entityDaoRegistry; + + /** + * Returns true if the entity exists and belongs to the tenant. + * Uses the entity services, so cached and tenant-scoped lookups are used where available. + */ + public boolean isTenantEntity(TenantId tenantId, EntityId entityId) { + if (entityId == null) { + return false; + } + try { + return entityService.fetchEntity(tenantId, entityId) + .map(entity -> entity instanceof HasTenantId hasTenantId && tenantId.equals(hasTenantId.getTenantId())) + .orElse(false); + } catch (IllegalArgumentException e) { + log.warn("[{}] Unsupported entity type of {}", tenantId, entityId); + return false; + } + } + + /** + * Loads the entity regardless of its tenant, so that an id of another tenant's entity is detected. + * Returns null if the entity doesn't exist, throws if it belongs to a different tenant. + */ + @SuppressWarnings("unchecked") + public T findTenantEntity(TenantId tenantId, EntityId entityId) { + Object entity = findEntity(tenantId, entityId); + if (entity instanceof HasTenantId hasTenantId && !tenantId.equals(hasTenantId.getTenantId())) { + throw new DataValidationException(entityId.getEntityType() + " " + entityId.getId() + " belongs to a different tenant!"); + } + return (T) entity; + } + + /** + * Returns the tenant of the entity regardless of the given tenant, or null if the entity doesn't exist. + */ + public TenantId findEntityTenantId(TenantId tenantId, EntityId entityId) { + return findEntity(tenantId, entityId) instanceof HasTenantId hasTenantId ? hasTenantId.getTenantId() : null; + } + + private Object findEntity(TenantId tenantId, EntityId entityId) { + if (entityId == null) { + return null; + } + try { + return entityDaoRegistry.getDao(entityId.getEntityType()).findById(tenantId, entityId.getId()); + } catch (IllegalArgumentException e) { + log.warn("[{}] Unsupported entity type of {}", tenantId, entityId); + return null; + } + } + +} diff --git a/application/src/main/java/org/thingsboard/server/service/edge/EdgeMsgSummaryUtils.java b/application/src/main/java/org/thingsboard/server/service/edge/EdgeMsgSummaryUtils.java index 97b4a68dd1..051a5409b0 100644 --- a/application/src/main/java/org/thingsboard/server/service/edge/EdgeMsgSummaryUtils.java +++ b/application/src/main/java/org/thingsboard/server/service/edge/EdgeMsgSummaryUtils.java @@ -7,7 +7,9 @@ import com.google.protobuf.Message; import java.util.Collection; import java.util.List; +import java.util.Map; import java.util.StringJoiner; +import java.util.UUID; import java.util.stream.Collectors; /** @@ -16,27 +18,58 @@ import java.util.stream.Collectors; */ public final class EdgeMsgSummaryUtils { + private static final String MSB = "MSB"; + private static final String LSB = "LSB"; + private EdgeMsgSummaryUtils() { } // e.g. DownlinkMsg[downlinkMsgId=12, deviceUpdateMsg x2, deviceCredentialsUpdateMsg x1] + // e.g. DeviceUpdateMsg[msgType=ENTITY_UPDATED_RPC_MESSAGE, id=1d6f1e2c-...] public static String toSummary(Message msg) { if (msg == null) { return "null"; } + Map fields = msg.getAllFields(); StringJoiner summary = new StringJoiner(", ", msg.getDescriptorForType().getName() + "[", "]"); - msg.getAllFields().forEach((field, value) -> { + fields.forEach((field, value) -> { + String name = field.getName(); if (field.isRepeated()) { - summary.add(field.getName() + " x" + ((List) value).size()); - } else if (field.getJavaType() == FieldDescriptor.JavaType.INT || field.getJavaType() == FieldDescriptor.JavaType.LONG) { - summary.add(field.getName() + "=" + value); - } else if (field.getJavaType() == FieldDescriptor.JavaType.MESSAGE) { - summary.add(field.getName()); + summary.add(name + " x" + ((List) value).size()); + return; + } + switch (field.getJavaType()) { + case INT, LONG -> { + FieldDescriptor lsbField = name.endsWith(MSB) ? findPairField(msg, name, MSB, LSB) : null; + if (lsbField != null && value instanceof Long msb && msg.getField(lsbField) instanceof Long lsb) { + summary.add(name.substring(0, name.length() - MSB.length()) + "=" + new UUID(msb, lsb)); + } else if (!isPrintedWithPair(msg, fields, name)) { + summary.add(name + "=" + value); + } + } + case BOOLEAN, ENUM -> summary.add(name + "=" + value); + case MESSAGE -> summary.add(name); + // strings and bytes may hold entity JSON, credentials or secrets + default -> { + } } }); return summary.toString(); } + // LSB part of an id is printed together with its MSB part + private static boolean isPrintedWithPair(Message msg, Map fields, String name) { + if (!name.endsWith(LSB)) { + return false; + } + FieldDescriptor msbField = findPairField(msg, name, LSB, MSB); + return msbField != null && fields.containsKey(msbField); + } + + private static FieldDescriptor findPairField(Message msg, String name, String suffix, String pairSuffix) { + return msg.getDescriptorForType().findFieldByName(name.substring(0, name.length() - suffix.length()) + pairSuffix); + } + public static String toSummary(Collection msgs) { return msgs.stream().map(EdgeMsgSummaryUtils::toSummary).collect(Collectors.joining(", ", "[", "]")); } diff --git a/application/src/main/java/org/thingsboard/server/service/edge/rpc/processor/BaseEdgeProcessor.java b/application/src/main/java/org/thingsboard/server/service/edge/rpc/processor/BaseEdgeProcessor.java index e3207f422d..a6072ea341 100644 --- a/application/src/main/java/org/thingsboard/server/service/edge/rpc/processor/BaseEdgeProcessor.java +++ b/application/src/main/java/org/thingsboard/server/service/edge/rpc/processor/BaseEdgeProcessor.java @@ -19,7 +19,6 @@ import org.thingsboard.server.common.data.EntityType; import org.thingsboard.server.common.data.EntityView; import org.thingsboard.server.common.data.HasCustomerId; import org.thingsboard.server.common.data.HasName; -import org.thingsboard.server.common.data.HasTenantId; import org.thingsboard.server.common.data.HasVersion; import org.thingsboard.server.common.data.StringUtils; import org.thingsboard.server.common.data.HasOwnerId; @@ -63,7 +62,6 @@ import org.thingsboard.server.common.msg.TbMsg; import org.thingsboard.server.common.msg.TbMsgDataType; import org.thingsboard.server.common.msg.TbMsgMetaData; import org.thingsboard.server.dao.edge.EdgeSynchronizationManager; -import org.thingsboard.server.dao.entity.EntityDaoRegistry; import org.thingsboard.server.dao.model.ModelConstants; import org.thingsboard.server.exception.DataValidationException; import org.thingsboard.server.gen.edge.v1.UpdateMsgType; @@ -71,6 +69,7 @@ import org.thingsboard.server.gen.transport.TransportProtos; import org.thingsboard.server.queue.TbQueueCallback; import org.thingsboard.server.queue.TbQueueMsgMetadata; import org.thingsboard.server.service.edge.EdgeContextComponent; +import org.thingsboard.server.service.edge.EdgeEntityTenantChecker; import org.thingsboard.server.service.executors.DbCallbackExecutorService; import org.thingsboard.server.service.security.permission.OwnersCacheService; import org.thingsboard.server.service.state.DefaultDeviceStateService; @@ -96,7 +95,7 @@ public abstract class BaseEdgeProcessor implements EdgeProcessor { protected EdgeContextComponent edgeCtx; @Autowired - protected EntityDaoRegistry entityDaoRegistry; + protected EdgeEntityTenantChecker edgeEntityTenantChecker; @Autowired protected EdgeSynchronizationManager edgeSynchronizationManager; @@ -420,20 +419,17 @@ public abstract class BaseEdgeProcessor implements EdgeProcessor { return customerId; } - protected boolean isEntityExists(TenantId tenantId, EntityId entityId) { - return tenantId.equals(findEntityTenantId(tenantId, entityId)); + protected boolean isTenantEntity(TenantId tenantId, EntityId entityId) { + return edgeEntityTenantChecker.isTenantEntity(tenantId, entityId); } - protected void checkEntityTenant(TenantId tenantId, EntityId entityId) { - TenantId entityTenantId = findEntityTenantId(tenantId, entityId); - if (entityTenantId != null && !tenantId.equals(entityTenantId)) { - throw new DataValidationException(entityId.getEntityType() + " " + entityId.getId() + " belongs to a different tenant!"); - } + // returns the existing entity of the tenant or null, throws if the id belongs to another tenant's entity + protected T findTenantEntity(TenantId tenantId, EntityId entityId) { + return edgeEntityTenantChecker.findTenantEntity(tenantId, entityId); } private TenantId findEntityTenantId(TenantId tenantId, EntityId entityId) { - Object entity = entityDaoRegistry.getDao(entityId.getEntityType()).findById(tenantId, entityId.getId()); - return entity instanceof HasTenantId hasTenantId ? hasTenantId.getTenantId() : null; + return edgeEntityTenantChecker.findEntityTenantId(tenantId, entityId); } protected void createRelationFromEdge(TenantId tenantId, EdgeId edgeId, EntityId entityId) { @@ -503,7 +499,7 @@ public abstract class BaseEdgeProcessor implements EdgeProcessor { protected void changeOwnerIfRequired(TenantId tenantId, CustomerId customerId, EntityId entityId) throws ThingsboardException { EntityId newOwnerId = getOwnerId(tenantId, customerId); - if (!isEntityExists(tenantId, newOwnerId)) { + if (!isTenantEntity(tenantId, newOwnerId)) { throw new DataValidationException("Owner " + newOwnerId + " belongs to a different tenant!"); } EntityId currentOwnerId; @@ -565,21 +561,23 @@ public abstract class BaseEdgeProcessor implements EdgeProcessor { } protected void safeAddEntityToGroup(TenantId tenantId, EntityGroupId entityGroupId, EntityId entityId) { - if (entityGroupId != null && !ModelConstants.NULL_UUID.equals(entityGroupId.getId())) { - EntityGroup entityGroup = edgeCtx.getEntityGroupService().findEntityGroupById(tenantId, entityGroupId); - if (entityGroup != null && isEntityExists(tenantId, entityGroup.getOwnerId())) { - edgeCtx.getEntityGroupService().addEntityToEntityGroup(tenantId, entityGroupId, entityId); - } + if (entityGroupId != null && !ModelConstants.NULL_UUID.equals(entityGroupId.getId()) && findTenantEntityGroup(tenantId, entityGroupId) != null) { + edgeCtx.getEntityGroupService().addEntityToEntityGroup(tenantId, entityGroupId, entityId); } } protected void safeRemoveEntityFromGroup(TenantId tenantId, EntityGroupId entityGroupId, EntityId entityId) { - EntityGroup entityGroup = edgeCtx.getEntityGroupService().findEntityGroupById(tenantId, entityGroupId); - if (entityGroup != null && isEntityExists(tenantId, entityGroup.getOwnerId())) { + if (findTenantEntityGroup(tenantId, entityGroupId) != null) { edgeCtx.getEntityGroupService().removeEntityFromEntityGroup(tenantId, entityGroupId, entityId); } } + // returns the entity group if it is owned by the tenant or its customer, otherwise null + private EntityGroup findTenantEntityGroup(TenantId tenantId, EntityGroupId entityGroupId) { + EntityGroup entityGroup = edgeCtx.getEntityGroupService().findEntityGroupById(tenantId, entityGroupId); + return entityGroup != null && isTenantEntity(tenantId, entityGroup.getOwnerId()) ? entityGroup : null; + } + protected boolean isSaveRequired(HasVersion current, HasVersion updated) { if (current != null) { current.setVersion(null); diff --git a/application/src/main/java/org/thingsboard/server/service/edge/rpc/processor/ai/BaseAiModelProcessor.java b/application/src/main/java/org/thingsboard/server/service/edge/rpc/processor/ai/BaseAiModelProcessor.java index c99514ff8d..78b5803c7c 100644 --- a/application/src/main/java/org/thingsboard/server/service/edge/rpc/processor/ai/BaseAiModelProcessor.java +++ b/application/src/main/java/org/thingsboard/server/service/edge/rpc/processor/ai/BaseAiModelProcessor.java @@ -34,10 +34,9 @@ public abstract class BaseAiModelProcessor extends BaseEdgeProcessor { throw new RuntimeException("[{" + tenantId + "}] aiModelUpdateMsg for aiModel {" + aiModelId + "} cannot be converted to aiModel"); } - checkEntityTenant(tenantId, aiModelId); + AiModel aiModelById = findTenantEntity(tenantId, aiModelId); aiModel.setTenantId(tenantId); - Optional aiModelById = edgeCtx.getAiModelService().findAiModelById(tenantId, aiModelId); - if (aiModelById.isEmpty()) { + if (aiModelById == null) { aiModel.setCreatedTime(Uuids.unixTimestamp(aiModelId.getId())); isCreated = true; aiModel.setId(null); diff --git a/application/src/main/java/org/thingsboard/server/service/edge/rpc/processor/alarm/BaseAlarmProcessor.java b/application/src/main/java/org/thingsboard/server/service/edge/rpc/processor/alarm/BaseAlarmProcessor.java index 39162e287b..5bfff3a3a1 100644 --- a/application/src/main/java/org/thingsboard/server/service/edge/rpc/processor/alarm/BaseAlarmProcessor.java +++ b/application/src/main/java/org/thingsboard/server/service/edge/rpc/processor/alarm/BaseAlarmProcessor.java @@ -44,13 +44,13 @@ public abstract class BaseAlarmProcessor extends BaseEdgeProcessor { if (alarm == null) { throw new RuntimeException("[{" + tenantId + "}] alarmUpdateMsg {" + alarmUpdateMsg + "} cannot be converted to alarm"); } - if (alarm.getOriginator() == null || !isEntityExists(tenantId, alarm.getOriginator())) { + if (alarm.getOriginator() == null || !isTenantEntity(tenantId, alarm.getOriginator())) { log.warn("[{}] Originator not found for the alarm msg {}", tenantId, alarmUpdateMsg); return Futures.immediateFuture(null); } alarm.setTenantId(tenantId); try { - checkEntityTenant(tenantId, alarmId); + findTenantEntity(tenantId, alarmId); switch (alarmUpdateMsg.getMsgType()) { case ENTITY_CREATED_RPC_MESSAGE: edgeCtx.getAlarmService().createAlarm(AlarmCreateOrUpdateActiveRequest.fromAlarm(alarm, null, alarmId)); diff --git a/application/src/main/java/org/thingsboard/server/service/edge/rpc/processor/apikey/BaseApiKeyProcessor.java b/application/src/main/java/org/thingsboard/server/service/edge/rpc/processor/apikey/BaseApiKeyProcessor.java index 5446e9f737..4ed9c7d637 100644 --- a/application/src/main/java/org/thingsboard/server/service/edge/rpc/processor/apikey/BaseApiKeyProcessor.java +++ b/application/src/main/java/org/thingsboard/server/service/edge/rpc/processor/apikey/BaseApiKeyProcessor.java @@ -25,13 +25,12 @@ public abstract class BaseApiKeyProcessor extends BaseEdgeProcessor { throw new RuntimeException("[{" + tenantId + "}] apiKeyUpdateMsg for apiKey {" + apiKeyId + "} cannot be converted to apiKey"); } - checkEntityTenant(tenantId, apiKeyId); + ApiKey existingApiKey = findTenantEntity(tenantId, apiKeyId); apiKey.setTenantId(tenantId); - if (apiKey.getUserId() == null || !isEntityExists(tenantId, apiKey.getUserId())) { + if (apiKey.getUserId() == null || !isTenantEntity(tenantId, apiKey.getUserId())) { throw new DataValidationException("API key is referencing to non-existent user!"); } - ApiKey existingApiKey = edgeCtx.getApiKeyService().findApiKeyById(tenantId, apiKeyId); if (existingApiKey == null) { apiKey.setCreatedTime(Uuids.unixTimestamp(apiKeyId.getId())); isCreated = true; diff --git a/application/src/main/java/org/thingsboard/server/service/edge/rpc/processor/asset/BaseAssetProcessor.java b/application/src/main/java/org/thingsboard/server/service/edge/rpc/processor/asset/BaseAssetProcessor.java index b8422e0feb..bea145b5af 100644 --- a/application/src/main/java/org/thingsboard/server/service/edge/rpc/processor/asset/BaseAssetProcessor.java +++ b/application/src/main/java/org/thingsboard/server/service/edge/rpc/processor/asset/BaseAssetProcessor.java @@ -36,9 +36,8 @@ public abstract class BaseAssetProcessor extends BaseEdgeProcessor { if (asset == null) { throw new RuntimeException("[{" + tenantId + "}] assetUpdateMsg {" + assetUpdateMsg + " } cannot be converted to asset"); } - checkEntityTenant(tenantId, assetId); + Asset assetById = findTenantEntity(tenantId, assetId); asset.setTenantId(tenantId); - Asset assetById = edgeCtx.getAssetService().findAssetById(tenantId, assetId); if (assetById == null) { created = true; asset.setId(null); diff --git a/application/src/main/java/org/thingsboard/server/service/edge/rpc/processor/asset/profile/BaseAssetProfileProcessor.java b/application/src/main/java/org/thingsboard/server/service/edge/rpc/processor/asset/profile/BaseAssetProfileProcessor.java index 80d6695e2f..39c1aa7700 100644 --- a/application/src/main/java/org/thingsboard/server/service/edge/rpc/processor/asset/profile/BaseAssetProfileProcessor.java +++ b/application/src/main/java/org/thingsboard/server/service/edge/rpc/processor/asset/profile/BaseAssetProfileProcessor.java @@ -31,9 +31,8 @@ public abstract class BaseAssetProfileProcessor extends BaseEdgeProcessor { if (assetProfile == null) { throw new RuntimeException("[{" + tenantId + "}] assetProfileUpdateMsg {" + assetProfileUpdateMsg + "} cannot be converted to asset profile"); } - checkEntityTenant(tenantId, assetProfileId); + AssetProfile assetProfileById = findTenantEntity(tenantId, assetProfileId); assetProfile.setTenantId(tenantId); - AssetProfile assetProfileById = edgeCtx.getAssetProfileService().findAssetProfileById(tenantId, assetProfileId); if (assetProfileById == null) { created = true; assetProfile.setId(null); diff --git a/application/src/main/java/org/thingsboard/server/service/edge/rpc/processor/cf/BaseCalculatedFieldProcessor.java b/application/src/main/java/org/thingsboard/server/service/edge/rpc/processor/cf/BaseCalculatedFieldProcessor.java index 4fafd78a12..dd1db3a6f3 100644 --- a/application/src/main/java/org/thingsboard/server/service/edge/rpc/processor/cf/BaseCalculatedFieldProcessor.java +++ b/application/src/main/java/org/thingsboard/server/service/edge/rpc/processor/cf/BaseCalculatedFieldProcessor.java @@ -32,19 +32,18 @@ public abstract class BaseCalculatedFieldProcessor extends BaseEdgeProcessor { throw new RuntimeException("[{" + tenantId + "}] calculatedFieldUpdateMsg {" + calculatedFieldUpdateMsg + " } cannot be converted to calculatedField"); } - checkEntityTenant(tenantId, calculatedFieldId); + CalculatedField calculatedFieldById = findTenantEntity(tenantId, calculatedFieldId); calculatedField.setTenantId(tenantId); - if (calculatedField.getEntityId() == null || !isEntityExists(tenantId, calculatedField.getEntityId())) { + if (calculatedField.getEntityId() == null || !isTenantEntity(tenantId, calculatedField.getEntityId())) { throw new DataValidationException("Calculated field is referencing to non-existent entity!"); } if (calculatedField.getConfiguration() != null) { for (EntityId referencedEntityId : calculatedField.getConfiguration().getReferencedEntities()) { - if (!isEntityExists(tenantId, referencedEntityId)) { + if (!isTenantEntity(tenantId, referencedEntityId)) { throw new DataValidationException("Calculated field argument is referencing to non-existent entity!"); } } } - CalculatedField calculatedFieldById = edgeCtx.getCalculatedFieldService().findById(tenantId, calculatedFieldId); if (calculatedFieldById == null) { calculatedField.setCreatedTime(Uuids.unixTimestamp(calculatedFieldId.getId())); isCreated = true; diff --git a/application/src/main/java/org/thingsboard/server/service/edge/rpc/processor/dashboard/BaseDashboardProcessor.java b/application/src/main/java/org/thingsboard/server/service/edge/rpc/processor/dashboard/BaseDashboardProcessor.java index 601506c8d7..3de8ccf770 100644 --- a/application/src/main/java/org/thingsboard/server/service/edge/rpc/processor/dashboard/BaseDashboardProcessor.java +++ b/application/src/main/java/org/thingsboard/server/service/edge/rpc/processor/dashboard/BaseDashboardProcessor.java @@ -31,9 +31,8 @@ public abstract class BaseDashboardProcessor extends BaseEdgeProcessor { if (dashboard == null) { throw new RuntimeException("[{" + tenantId + "}] dashboardUpdateMsg {" + dashboardUpdateMsg + "} cannot be converted to dashboard"); } - checkEntityTenant(tenantId, dashboardId); + Dashboard dashboardById = findTenantEntity(tenantId, dashboardId); dashboard.setTenantId(tenantId); - Dashboard dashboardById = edgeCtx.getDashboardService().findDashboardById(tenantId, dashboardId); if (dashboardById == null) { created = true; dashboard.setId(null); diff --git a/application/src/main/java/org/thingsboard/server/service/edge/rpc/processor/device/BaseDeviceProcessor.java b/application/src/main/java/org/thingsboard/server/service/edge/rpc/processor/device/BaseDeviceProcessor.java index 9c9a6a2052..2e64895fa3 100644 --- a/application/src/main/java/org/thingsboard/server/service/edge/rpc/processor/device/BaseDeviceProcessor.java +++ b/application/src/main/java/org/thingsboard/server/service/edge/rpc/processor/device/BaseDeviceProcessor.java @@ -42,9 +42,8 @@ public abstract class BaseDeviceProcessor extends BaseEdgeProcessor { if (device == null) { throw new RuntimeException("[{" + tenantId + "}] deviceUpdateMsg {" + deviceUpdateMsg + "} cannot be converted to device"); } - checkEntityTenant(tenantId, deviceId); + Device deviceById = findTenantEntity(tenantId, deviceId); device.setTenantId(tenantId); - Device deviceById = edgeCtx.getDeviceService().findDeviceById(tenantId, deviceId); if (deviceById == null) { created = true; device.setId(null); diff --git a/application/src/main/java/org/thingsboard/server/service/edge/rpc/processor/device/DeviceEdgeProcessor.java b/application/src/main/java/org/thingsboard/server/service/edge/rpc/processor/device/DeviceEdgeProcessor.java index 4fe3f5a5fd..896f502189 100644 --- a/application/src/main/java/org/thingsboard/server/service/edge/rpc/processor/device/DeviceEdgeProcessor.java +++ b/application/src/main/java/org/thingsboard/server/service/edge/rpc/processor/device/DeviceEdgeProcessor.java @@ -52,7 +52,6 @@ import org.thingsboard.server.queue.TbQueueCallback; import org.thingsboard.server.queue.TbQueueMsgMetadata; import org.thingsboard.server.queue.util.TbCoreComponent; import org.thingsboard.server.service.edge.EdgeMsgConstructorUtils; -import org.thingsboard.server.service.edge.EdgeMsgSummaryUtils; import java.util.UUID; @@ -101,7 +100,7 @@ public class DeviceEdgeProcessor extends BaseDeviceProcessor implements DevicePr @Override public ListenableFuture processDeviceCredentialsMsgFromEdge(TenantId tenantId, EdgeId edgeId, DeviceCredentialsUpdateMsg deviceCredentialsUpdateMsg) { - log.debug("[{}] Executing processDeviceCredentialsMsgFromEdge, deviceCredentialsUpdateMsg [{}]", tenantId, EdgeMsgSummaryUtils.toSummary(deviceCredentialsUpdateMsg)); + log.debug("[{}][{}] Executing processDeviceCredentialsMsgFromEdge", tenantId, edgeId); try { edgeSynchronizationManager.getEdgeId().set(edgeId); @@ -197,7 +196,7 @@ public class DeviceEdgeProcessor extends BaseDeviceProcessor implements DevicePr SettableFuture futureToSet = SettableFuture.create(); UUID requestUuid = new UUID(deviceRpcCallMsg.getRequestUuidMSB(), deviceRpcCallMsg.getRequestUuidLSB()); DeviceId deviceId = new DeviceId(new UUID(deviceRpcCallMsg.getDeviceIdMSB(), deviceRpcCallMsg.getDeviceIdLSB())); - if (!isEntityExists(tenantId, deviceId)) { + if (!isTenantEntity(tenantId, deviceId)) { log.warn("[{}] Skipping RPC response because device doesn't exist, {}", tenantId, deviceRpcCallMsg); return Futures.immediateFuture(null); } @@ -230,7 +229,7 @@ public class DeviceEdgeProcessor extends BaseDeviceProcessor implements DevicePr private ListenableFuture processDeviceRpcRequestFromEdge(TenantId tenantId, Edge edge, DeviceRpcCallMsg deviceRpcCallMsg) { DeviceId deviceId = new DeviceId(new UUID(deviceRpcCallMsg.getDeviceIdMSB(), deviceRpcCallMsg.getDeviceIdLSB())); - if (!isEntityExists(tenantId, deviceId)) { + if (!isTenantEntity(tenantId, deviceId)) { log.warn("[{}] Skipping RPC request because device doesn't exist, {}", tenantId, deviceRpcCallMsg); return Futures.immediateFuture(null); } diff --git a/application/src/main/java/org/thingsboard/server/service/edge/rpc/processor/device/profile/BaseDeviceProfileProcessor.java b/application/src/main/java/org/thingsboard/server/service/edge/rpc/processor/device/profile/BaseDeviceProfileProcessor.java index c299ee2487..dd71635b80 100644 --- a/application/src/main/java/org/thingsboard/server/service/edge/rpc/processor/device/profile/BaseDeviceProfileProcessor.java +++ b/application/src/main/java/org/thingsboard/server/service/edge/rpc/processor/device/profile/BaseDeviceProfileProcessor.java @@ -31,9 +31,8 @@ public abstract class BaseDeviceProfileProcessor extends BaseEdgeProcessor { if (deviceProfile == null) { throw new RuntimeException("[{" + tenantId + "}] deviceProfileUpdateMsg {" + deviceProfileUpdateMsg + "} cannot be converted to device profile"); } - checkEntityTenant(tenantId, deviceProfileId); + DeviceProfile deviceProfileById = findTenantEntity(tenantId, deviceProfileId); deviceProfile.setTenantId(tenantId); - DeviceProfile deviceProfileById = edgeCtx.getDeviceProfileService().findDeviceProfileById(tenantId, deviceProfileId); if (deviceProfileById == null) { created = true; deviceProfile.setId(null); diff --git a/application/src/main/java/org/thingsboard/server/service/edge/rpc/processor/entityview/BaseEntityViewProcessor.java b/application/src/main/java/org/thingsboard/server/service/edge/rpc/processor/entityview/BaseEntityViewProcessor.java index 006428d688..04bc19623a 100644 --- a/application/src/main/java/org/thingsboard/server/service/edge/rpc/processor/entityview/BaseEntityViewProcessor.java +++ b/application/src/main/java/org/thingsboard/server/service/edge/rpc/processor/entityview/BaseEntityViewProcessor.java @@ -35,12 +35,11 @@ public abstract class BaseEntityViewProcessor extends BaseEdgeProcessor { if (entityView == null) { throw new RuntimeException("[{" + tenantId + "}] entityViewUpdateMsg {" + entityViewUpdateMsg + "} cannot be converted to entity view"); } - checkEntityTenant(tenantId, entityViewId); + EntityView entityViewById = findTenantEntity(tenantId, entityViewId); entityView.setTenantId(tenantId); - if (entityView.getEntityId() == null || !isEntityExists(tenantId, entityView.getEntityId())) { + if (entityView.getEntityId() == null || !isTenantEntity(tenantId, entityView.getEntityId())) { throw new DataValidationException("Entity view is referencing to non-existent entity!"); } - EntityView entityViewById = edgeCtx.getEntityViewService().findEntityViewById(tenantId, entityViewId); if (entityViewById == null) { created = true; entityView.setId(null); diff --git a/application/src/main/java/org/thingsboard/server/service/edge/rpc/processor/relation/BaseRelationProcessor.java b/application/src/main/java/org/thingsboard/server/service/edge/rpc/processor/relation/BaseRelationProcessor.java index 619729928d..0b88435d4e 100644 --- a/application/src/main/java/org/thingsboard/server/service/edge/rpc/processor/relation/BaseRelationProcessor.java +++ b/application/src/main/java/org/thingsboard/server/service/edge/rpc/processor/relation/BaseRelationProcessor.java @@ -24,14 +24,14 @@ public abstract class BaseRelationProcessor extends BaseEdgeProcessor { switch (relationUpdateMsg.getMsgType()) { case ENTITY_CREATED_RPC_MESSAGE: case ENTITY_UPDATED_RPC_MESSAGE: - if (isEntityExists(tenantId, entityRelation.getTo()) && isEntityExists(tenantId, entityRelation.getFrom())) { + if (isTenantEntity(tenantId, entityRelation.getTo()) && isTenantEntity(tenantId, entityRelation.getFrom())) { edgeCtx.getRelationService().saveRelation(tenantId, entityRelation); } else { log.warn("[{}] Skipping relating update msg because from/to entity doesn't exists on edge, {}", tenantId, relationUpdateMsg); } break; case ENTITY_DELETED_RPC_MESSAGE: - if (isEntityExists(tenantId, entityRelation.getTo()) && isEntityExists(tenantId, entityRelation.getFrom())) { + if (isTenantEntity(tenantId, entityRelation.getTo()) && isTenantEntity(tenantId, entityRelation.getFrom())) { edgeCtx.getRelationService().deleteRelation(tenantId, entityRelation); } break; diff --git a/application/src/main/java/org/thingsboard/server/service/edge/rpc/processor/report/BaseReportTemplateProcessor.java b/application/src/main/java/org/thingsboard/server/service/edge/rpc/processor/report/BaseReportTemplateProcessor.java index c059a9974e..2bff1bb889 100644 --- a/application/src/main/java/org/thingsboard/server/service/edge/rpc/processor/report/BaseReportTemplateProcessor.java +++ b/application/src/main/java/org/thingsboard/server/service/edge/rpc/processor/report/BaseReportTemplateProcessor.java @@ -29,9 +29,8 @@ public abstract class BaseReportTemplateProcessor extends BaseEdgeProcessor { if (reportTemplate == null) { throw new RuntimeException("[{" + tenantId + "}] reportTemplateUpdateMsg {" + reportTemplateUpdateMsg + "} cannot be converted to report template"); } - checkEntityTenant(tenantId, reportTemplateId); + ReportTemplate reportTemplateById = findTenantEntity(tenantId, reportTemplateId); reportTemplate.setTenantId(tenantId); - ReportTemplate reportTemplateById = edgeCtx.getReportTemplateService().findReportTemplateById(tenantId, reportTemplateId); if (reportTemplateById == null) { created = true; reportTemplate.setId(null); diff --git a/application/src/main/java/org/thingsboard/server/service/edge/rpc/processor/resource/BaseResourceProcessor.java b/application/src/main/java/org/thingsboard/server/service/edge/rpc/processor/resource/BaseResourceProcessor.java index c2c6c526de..f7fe050938 100644 --- a/application/src/main/java/org/thingsboard/server/service/edge/rpc/processor/resource/BaseResourceProcessor.java +++ b/application/src/main/java/org/thingsboard/server/service/edge/rpc/processor/resource/BaseResourceProcessor.java @@ -31,9 +31,8 @@ public abstract class BaseResourceProcessor extends BaseEdgeProcessor { throw new RuntimeException("[{" + tenantId + "}] resourceUpdateMsg {" + resourceUpdateMsg + " } cannot be converted to resource"); } boolean created = false; - checkEntityTenant(tenantId, tbResourceId); + TbResource resourceById = findTenantEntity(tenantId, tbResourceId); resource.setTenantId(tenantId); - TbResource resourceById = edgeCtx.getResourceService().findResourceById(tenantId, tbResourceId); if (resourceById == null) { resource.setCreatedTime(Uuids.unixTimestamp(tbResourceId.getId())); created = true; diff --git a/application/src/main/java/org/thingsboard/server/service/edge/rpc/processor/rule/BaseRuleChainProcessor.java b/application/src/main/java/org/thingsboard/server/service/edge/rpc/processor/rule/BaseRuleChainProcessor.java index cb09e97bc5..e7f5cbed3c 100644 --- a/application/src/main/java/org/thingsboard/server/service/edge/rpc/processor/rule/BaseRuleChainProcessor.java +++ b/application/src/main/java/org/thingsboard/server/service/edge/rpc/processor/rule/BaseRuleChainProcessor.java @@ -28,8 +28,7 @@ public class BaseRuleChainProcessor extends BaseEdgeProcessor { protected Pair saveOrUpdateRuleChain(TenantId tenantId, RuleChainId ruleChainId, RuleChainUpdateMsg ruleChainUpdateMsg, RuleChainType ruleChainType) { boolean created = false; - checkEntityTenant(tenantId, ruleChainId); - RuleChain ruleChainFromDb = edgeCtx.getRuleChainService().findRuleChainById(tenantId, ruleChainId); + RuleChain ruleChainFromDb = findTenantEntity(tenantId, ruleChainId); if (ruleChainFromDb == null) { created = true; } @@ -61,7 +60,7 @@ public class BaseRuleChainProcessor extends BaseEdgeProcessor { if (ruleChainMetadata == null) { throw new RuntimeException("[{" + tenantId + "}] ruleChainMetadataUpdateMsg {" + ruleChainMetadataUpdateMsg + "} cannot be converted to rule chain metadata"); } - if (ruleChainMetadata.getRuleChainId() == null || !isEntityExists(tenantId, ruleChainMetadata.getRuleChainId())) { + if (ruleChainMetadata.getRuleChainId() == null || !isTenantEntity(tenantId, ruleChainMetadata.getRuleChainId())) { throw new DataValidationException("Rule chain metadata is referencing to non-existent rule chain!"); } if (!ruleChainMetadata.getNodes().isEmpty()) { diff --git a/application/src/main/java/org/thingsboard/server/service/edge/rpc/processor/scheduler/BaseSchedulerEventProcessor.java b/application/src/main/java/org/thingsboard/server/service/edge/rpc/processor/scheduler/BaseSchedulerEventProcessor.java index 166216bdea..5c5a6e7b78 100644 --- a/application/src/main/java/org/thingsboard/server/service/edge/rpc/processor/scheduler/BaseSchedulerEventProcessor.java +++ b/application/src/main/java/org/thingsboard/server/service/edge/rpc/processor/scheduler/BaseSchedulerEventProcessor.java @@ -31,10 +31,9 @@ public abstract class BaseSchedulerEventProcessor extends BaseEdgeProcessor { if (schedulerEvent == null) { throw new RuntimeException("[{" + tenantId + "}] schedulerEventUpdateMsg {" + schedulerEventUpdateMsg + "} cannot be converted to scheduler event"); } - checkEntityTenant(tenantId, schedulerEventId); + SchedulerEvent existingSchedulerEvent = findTenantEntity(tenantId, schedulerEventId); schedulerEvent.setTenantId(tenantId); checkReportConfig(tenantId, schedulerEvent); - SchedulerEvent existingSchedulerEvent = edgeCtx.getSchedulerEventService().findSchedulerEventById(tenantId, schedulerEventId); if (existingSchedulerEvent == null) { created = true; schedulerEvent.setId(null); @@ -58,8 +57,8 @@ public abstract class BaseSchedulerEventProcessor extends BaseEdgeProcessor { private void checkReportConfig(TenantId tenantId, SchedulerEvent schedulerEvent) { if (GENERATE_REPORT.equals(schedulerEvent.getType())) { ReportConfig reportConfig = JacksonUtil.treeToValue(schedulerEvent.getConfiguration(), ReportConfig.class); - if (reportConfig == null || reportConfig.getReportTemplateId() == null || !isEntityExists(tenantId, reportConfig.getReportTemplateId()) - || reportConfig.getUserId() == null || !isEntityExists(tenantId, reportConfig.getUserId())) { + if (reportConfig == null || reportConfig.getReportTemplateId() == null || !isTenantEntity(tenantId, reportConfig.getReportTemplateId()) + || reportConfig.getUserId() == null || !isTenantEntity(tenantId, reportConfig.getUserId())) { throw new DataValidationException("Scheduler event is referencing to non-existent report template or user!"); } } diff --git a/application/src/main/java/org/thingsboard/server/service/edge/rpc/processor/telemetry/BaseTelemetryProcessor.java b/application/src/main/java/org/thingsboard/server/service/edge/rpc/processor/telemetry/BaseTelemetryProcessor.java index 3332de3aad..04d7939917 100644 --- a/application/src/main/java/org/thingsboard/server/service/edge/rpc/processor/telemetry/BaseTelemetryProcessor.java +++ b/application/src/main/java/org/thingsboard/server/service/edge/rpc/processor/telemetry/BaseTelemetryProcessor.java @@ -109,7 +109,7 @@ public abstract class BaseTelemetryProcessor extends BaseEdgeProcessor { log.trace("[{}] processTelemetryMsg [{}]", tenantId, entityData); List> result = new ArrayList<>(); EntityId entityId = constructEntityId(entityData.getEntityType(), entityData.getEntityIdMSB(), entityData.getEntityIdLSB()); - if (entityId != null && isEntityExists(tenantId, entityId)) { + if (entityId != null && isTenantEntity(tenantId, entityId)) { if ((entityData.hasPostAttributesMsg() || entityData.hasPostTelemetryMsg() || entityData.hasAttributesUpdatedMsg())) { Pair pair = getBaseMsgMetadataAndCustomerId(tenantId, entityId); TbMsgMetaData metaData = pair.getKey(); diff --git a/application/src/main/java/org/thingsboard/server/service/edge/rpc/processor/tenant/TenantProfileEdgeProcessor.java b/application/src/main/java/org/thingsboard/server/service/edge/rpc/processor/tenant/TenantProfileEdgeProcessor.java index 6fad0e2187..9432be7b3e 100644 --- a/application/src/main/java/org/thingsboard/server/service/edge/rpc/processor/tenant/TenantProfileEdgeProcessor.java +++ b/application/src/main/java/org/thingsboard/server/service/edge/rpc/processor/tenant/TenantProfileEdgeProcessor.java @@ -5,6 +5,7 @@ package org.thingsboard.server.service.edge.rpc.processor.tenant; import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Component; import org.thingsboard.server.common.data.EdgeUtils; +import org.thingsboard.server.common.data.Tenant; import org.thingsboard.server.common.data.TenantProfile; import org.thingsboard.server.common.data.edge.EdgeEvent; import org.thingsboard.server.common.data.edge.EdgeEventActionType; @@ -27,6 +28,11 @@ public class TenantProfileEdgeProcessor extends BaseEdgeProcessor { public DownlinkMsg convertEdgeEventToDownlink(EdgeEvent edgeEvent, EdgeVersion edgeVersion) { TenantProfileId tenantProfileId = new TenantProfileId(edgeEvent.getEntityId()); if (EdgeEventActionType.UPDATED.equals(edgeEvent.getAction())) { + // tenant profile updates are pushed to all edges, send only the profile of the edge's tenant + Tenant tenant = edgeCtx.getTenantService().findTenantById(edgeEvent.getTenantId()); + if (tenant == null || !tenantProfileId.equals(tenant.getTenantProfileId())) { + return null; + } TenantProfile tenantProfile = edgeCtx.getTenantProfileService().findTenantProfileById(edgeEvent.getTenantId(), tenantProfileId); if (tenantProfile != null) { UpdateMsgType msgType = getUpdateMsgType(edgeEvent.getAction()); diff --git a/application/src/main/java/org/thingsboard/server/service/edge/rpc/processor/user/UserEdgeProcessor.java b/application/src/main/java/org/thingsboard/server/service/edge/rpc/processor/user/UserEdgeProcessor.java index 02aa113900..d0119b5acb 100644 --- a/application/src/main/java/org/thingsboard/server/service/edge/rpc/processor/user/UserEdgeProcessor.java +++ b/application/src/main/java/org/thingsboard/server/service/edge/rpc/processor/user/UserEdgeProcessor.java @@ -38,7 +38,6 @@ import org.thingsboard.server.gen.edge.v1.UserCredentialsUpdateMsg; import org.thingsboard.server.gen.edge.v1.UserUpdateMsg; import org.thingsboard.server.queue.util.TbCoreComponent; import org.thingsboard.server.service.edge.EdgeMsgConstructorUtils; -import org.thingsboard.server.service.edge.EdgeMsgSummaryUtils; import java.util.List; import java.util.UUID; @@ -87,7 +86,7 @@ public class UserEdgeProcessor extends BaseUserProcessor implements UserProcesso @Override public ListenableFuture processUserCredentialsMsgFromEdge(TenantId tenantId, Edge edge, UserCredentialsUpdateMsg userCredentialsUpdateMsg) { - log.debug("[{}] Executing processUserCredentialsMsgFromEdge, userCredentialsUpdateMsg [{}]", tenantId, EdgeMsgSummaryUtils.toSummary(userCredentialsUpdateMsg)); + log.debug("[{}][{}] Executing processUserCredentialsMsgFromEdge", tenantId, edge.getId()); try { edgeSynchronizationManager.getEdgeId().set(edge.getId()); diff --git a/application/src/main/java/org/thingsboard/server/service/edge/rpc/sync/DefaultEdgeRequestsService.java b/application/src/main/java/org/thingsboard/server/service/edge/rpc/sync/DefaultEdgeRequestsService.java index 0d1025f462..c5fab0f2f7 100644 --- a/application/src/main/java/org/thingsboard/server/service/edge/rpc/sync/DefaultEdgeRequestsService.java +++ b/application/src/main/java/org/thingsboard/server/service/edge/rpc/sync/DefaultEdgeRequestsService.java @@ -33,7 +33,6 @@ import org.thingsboard.server.common.data.Device; import org.thingsboard.server.common.data.EdgeUtils; import org.thingsboard.server.common.data.EntityType; import org.thingsboard.server.common.data.EntityView; -import org.thingsboard.server.common.data.HasTenantId; import org.thingsboard.server.common.data.User; import org.thingsboard.server.common.data.asset.Asset; import org.thingsboard.server.common.data.edge.Edge; @@ -106,12 +105,14 @@ import org.thingsboard.server.gen.edge.v1.SendSmsUplinkMsg; import org.thingsboard.server.gen.edge.v1.UserCredentialsRequestMsg; import org.thingsboard.server.gen.edge.v1.WidgetBundleTypesRequestMsg; import org.thingsboard.server.queue.util.TbCoreComponent; +import org.thingsboard.server.service.edge.EdgeEntityTenantChecker; import org.thingsboard.server.service.entitiy.entityview.TbEntityViewService; import org.thingsboard.server.service.executors.DbCallbackExecutorService; import org.thingsboard.server.service.executors.NotificationExecutorService; import org.thingsboard.server.service.mail.EdgeMailRequest; import org.thingsboard.server.service.mail.MailExecutorService; import org.thingsboard.server.service.notification.EdgeNotificationRequest; +import org.thingsboard.server.service.security.permission.OwnersCacheService; import org.thingsboard.server.service.sms.EdgeSmsRequest; import org.thingsboard.server.service.sms.SmsExecutorService; import org.thingsboard.server.service.state.DefaultDeviceStateService; @@ -158,6 +159,12 @@ public class DefaultEdgeRequestsService implements EdgeRequestsService { @Autowired private EntityService entityService; + @Autowired + private EdgeEntityTenantChecker edgeEntityTenantChecker; + + @Autowired + private OwnersCacheService ownersCacheService; + @Autowired private TbEntityViewService entityViewService; @@ -575,7 +582,7 @@ public class DefaultEdgeRequestsService implements EdgeRequestsService { log.warn("[{}][{}] Entity group {} is not assigned to edge, skipping request", tenantId, edge.getId(), entityGroupId); return Futures.immediateFuture(null); } - return syncEntityGroupEntities(tenantId, edge, entityGroupId, entityGroupEntitiesRequestMsg); + return syncEntityGroupEntities(tenantId, edge, entityGroup); }, dbCallbackExecutorService); } return Futures.immediateFuture(null); @@ -591,19 +598,8 @@ public class DefaultEdgeRequestsService implements EdgeRequestsService { if (publicCustomer == null || !publicCustomer.isPublic()) { return false; } - EntityId publicCustomerOwnerId = publicCustomer.getOwnerId(); - if (tenantId.equals(publicCustomerOwnerId)) { - return true; - } - EntityId ownerId = edge.getOwnerId(); - while (ownerId != null && EntityType.CUSTOMER.equals(ownerId.getEntityType())) { - if (ownerId.equals(publicCustomerOwnerId)) { - return true; - } - Customer customer = findCustomer(tenantId, new CustomerId(ownerId.getId())); - ownerId = customer != null ? customer.getOwnerId() : null; - } - return false; + // the edge's owner chain (customer, parent customers, tenant) + return ownersCacheService.getOwners(tenantId, edge.getId(), edge).contains(publicCustomer.getOwnerId()); } private Customer findCustomer(TenantId tenantId, CustomerId customerId) { @@ -614,19 +610,19 @@ public class DefaultEdgeRequestsService implements EdgeRequestsService { .orElse(null); } - private ListenableFuture syncEntityGroupEntities(TenantId tenantId, Edge edge, EntityGroupId entityGroupId, EntityGroupRequestMsg entityGroupEntitiesRequestMsg) { + private ListenableFuture syncEntityGroupEntities(TenantId tenantId, Edge edge, EntityGroup entityGroup) { + EntityGroupId entityGroupId = entityGroup.getId(); ListenableFuture> entityIdsFuture; try { // TODO: refactor this to pagination entityIdsFuture = entityGroupService.findAllEntityIdsAsync(edge.getTenantId(), entityGroupId, new PageLink(Integer.MAX_VALUE)); } catch (IncorrectParameterException e) { - log.warn("[{}] Entity group not found to process entityGroupEntitiesRequestMsg {}", tenantId, entityGroupEntitiesRequestMsg, e); + log.warn("[{}] Entity group {} not found to process entity group entities request", tenantId, entityGroupId, e); return Futures.immediateFuture(null); } return Futures.transformAsync(entityIdsFuture, entityIds -> { if (entityIds != null && !entityIds.isEmpty()) { - EntityType groupType = EntityType.valueOf(entityGroupEntitiesRequestMsg.getType()); - return switch (groupType) { + return switch (entityGroup.getType()) { case DEVICE -> syncDevices(edge, entityIds, entityGroupId); case ASSET -> syncAssets(edge, entityIds, entityGroupId); case ENTITY_VIEW -> syncEntityViews(edge, entityIds, entityGroupId); @@ -635,7 +631,7 @@ public class DefaultEdgeRequestsService implements EdgeRequestsService { default -> Futures.immediateFuture(null); }; } else { - log.trace("No entities found for the requested entity group {} [{}]", entityGroupId.getId(), entityGroupEntitiesRequestMsg.getType()); + log.trace("No entities found for the requested entity group {} [{}]", entityGroupId.getId(), entityGroup.getType()); return Futures.immediateFuture(null); } }, dbCallbackExecutorService); @@ -987,18 +983,11 @@ public class DefaultEdgeRequestsService implements EdgeRequestsService { } private boolean isTenantEntity(TenantId tenantId, EntityId entityId) { - try { - boolean tenantEntity = entityService.fetchEntity(tenantId, entityId) - .map(entity -> entity instanceof HasTenantId hasTenantId && tenantId.equals(hasTenantId.getTenantId())) - .orElse(false); - if (!tenantEntity) { - log.warn("[{}] Entity {} not found, skipping request", tenantId, entityId); - } - return tenantEntity; - } catch (IllegalArgumentException e) { - log.warn("[{}] Unsupported entity {}, skipping request", tenantId, entityId); - return false; + boolean tenantEntity = edgeEntityTenantChecker.isTenantEntity(tenantId, entityId); + if (!tenantEntity) { + log.warn("[{}] Entity {} not found, skipping request", tenantId, entityId); } + return tenantEntity; } private ListenableFuture saveEdgeEvent(TenantId tenantId, diff --git a/application/src/test/java/org/thingsboard/server/edge/AbstractEdgeTest.java b/application/src/test/java/org/thingsboard/server/edge/AbstractEdgeTest.java index 75a8b8c6ee..2b2232ecc9 100644 --- a/application/src/test/java/org/thingsboard/server/edge/AbstractEdgeTest.java +++ b/application/src/test/java/org/thingsboard/server/edge/AbstractEdgeTest.java @@ -663,7 +663,8 @@ abstract public class AbstractEdgeTest extends AbstractControllerTest { protected void sendUplinkMsgAndVerifyNoDownlink(Consumer customizer) throws Exception { edgeImitator.expectMessageAmount(1); sendUplinkMsgAndWaitForResponse(customizer); - Assert.assertFalse(edgeImitator.waitForMessages(5)); + // edge events are polled every second, so 2 seconds cover a full poll cycle + Assert.assertFalse(edgeImitator.waitForMessages(2)); } protected Device saveDevice(String deviceName, String type) { diff --git a/application/src/test/java/org/thingsboard/server/edge/AlarmEdgeTest.java b/application/src/test/java/org/thingsboard/server/edge/AlarmEdgeTest.java index ea88e7ad47..1954d0c5bd 100644 --- a/application/src/test/java/org/thingsboard/server/edge/AlarmEdgeTest.java +++ b/application/src/test/java/org/thingsboard/server/edge/AlarmEdgeTest.java @@ -299,4 +299,40 @@ public class AlarmEdgeTest extends AbstractEdgeTest { doGet("/api/alarm/" + alarm.getUuidId()).andExpect(status().isNotFound()); } + @Test + public void testSendAlarmCommentWithIdOfCommentOfAnotherAlarmToCloud() throws Exception { + Device device = saveDevice("Alarm Comment Device", "default"); + Alarm firstAlarm = saveAlarm(device, "first alarm"); + Alarm secondAlarm = saveAlarm(device, "second alarm"); + + AlarmComment alarmComment = new AlarmComment(); + alarmComment.setComment(new TextNode("Original comment")); + alarmComment.setAlarmId(firstAlarm.getId()); + alarmComment = doPost("/api/alarm/" + firstAlarm.getUuidId() + "/comment", alarmComment, AlarmComment.class); + + AlarmComment edgeAlarmComment = new AlarmComment(); + edgeAlarmComment.setId(alarmComment.getId()); + edgeAlarmComment.setCreatedTime(alarmComment.getCreatedTime()); + edgeAlarmComment.setAlarmId(secondAlarm.getId()); + edgeAlarmComment.setComment(new TextNode("Changed comment")); + sendUplinkMsgAndWaitForResponse(uplinkMsgBuilder -> uplinkMsgBuilder.addAlarmCommentUpdateMsg(AlarmCommentUpdateMsg.newBuilder() + .setMsgType(UpdateMsgType.ENTITY_UPDATED_RPC_MESSAGE) + .setEntity(JacksonUtil.toString(edgeAlarmComment)) + .build())); + + PageData firstAlarmComments = doGetTyped("/api/alarm/" + firstAlarm.getUuidId() + "/comment?page=0&pageSize=10", new TypeReference<>() {}); + Assert.assertEquals(1, firstAlarmComments.getTotalElements()); + Assert.assertEquals(alarmComment.getComment(), firstAlarmComments.getData().get(0).getComment()); + PageData secondAlarmComments = doGetTyped("/api/alarm/" + secondAlarm.getUuidId() + "/comment?page=0&pageSize=10", new TypeReference<>() {}); + Assert.assertEquals(0, secondAlarmComments.getTotalElements()); + } + + private Alarm saveAlarm(Device device, String type) { + Alarm alarm = new Alarm(); + alarm.setOriginator(device.getId()); + alarm.setType(type); + alarm.setSeverity(AlarmSeverity.MINOR); + return doPost("/api/alarm", alarm, Alarm.class); + } + } diff --git a/application/src/test/java/org/thingsboard/server/edge/CalculatedFieldEdgeTest.java b/application/src/test/java/org/thingsboard/server/edge/CalculatedFieldEdgeTest.java index 2377d035c3..f6c34f1ffa 100644 --- a/application/src/test/java/org/thingsboard/server/edge/CalculatedFieldEdgeTest.java +++ b/application/src/test/java/org/thingsboard/server/edge/CalculatedFieldEdgeTest.java @@ -270,4 +270,19 @@ public class CalculatedFieldEdgeTest extends AbstractEdgeTest { Assert.assertNull(calculatedFieldService.findById(tenantId, calculatedField.getId())); } + @Test + public void testSendCalculatedFieldDeleteForCalculatedFieldOfDifferentTenantToCloud() throws Exception { + Device device = saveDifferentTenantDevice(); + CalculatedField calculatedField = createSimpleCalculatedField(device.getId(), new SimpleCalculatedFieldConfiguration()); + calculatedField.setTenantId(differentTenantId); + loginDifferentTenant(); + CalculatedField savedCalculatedField = doPost("/api/calculatedField", calculatedField, CalculatedField.class); + loginTenantAdmin(); + + sendUplinkMsgAndWaitForResponse(uplinkMsgBuilder -> uplinkMsgBuilder.addCalculatedFieldUpdateMsg( + EdgeMsgConstructorUtils.constructCalculatedFieldDeleteMsg(savedCalculatedField.getId()))); + + Assert.assertNotNull(calculatedFieldService.findById(differentTenantId, savedCalculatedField.getId())); + } + } diff --git a/application/src/test/java/org/thingsboard/server/edge/DeviceEdgeTest.java b/application/src/test/java/org/thingsboard/server/edge/DeviceEdgeTest.java index 55b116a125..db600a0d17 100644 --- a/application/src/test/java/org/thingsboard/server/edge/DeviceEdgeTest.java +++ b/application/src/test/java/org/thingsboard/server/edge/DeviceEdgeTest.java @@ -39,6 +39,7 @@ import org.thingsboard.server.common.data.group.EntityGroup; import org.thingsboard.server.common.data.id.DeviceId; import org.thingsboard.server.common.data.id.EdgeId; import org.thingsboard.server.common.data.id.RpcId; +import org.thingsboard.server.common.data.id.TenantId; import org.thingsboard.server.common.data.ota.OtaPackageType; import org.thingsboard.server.common.data.rpc.Rpc; import org.thingsboard.server.common.data.rpc.RpcStatus; @@ -756,6 +757,18 @@ public class DeviceEdgeTest extends AbstractEdgeTest { doGet("/api/rpc/persistent/" + unknownRpcId.getId()).andExpect(status().isNotFound()); } + @Test + public void testRpcV2StatusForRpcOfDifferentTenantFromEdge() throws Exception { + Device device = saveDifferentTenantDevice(); + Rpc rpc = savePersistentRpc(differentTenantId, device, RpcStatus.QUEUED); + + sendRpcStatusUplink(device, rpc.getId(), RpcStatus.SUCCESSFUL, "{\"result\":\"ok\"}"); + + Rpc rpcAfterUplink = rpcService.findById(differentTenantId, rpc.getId()); + Assert.assertEquals(RpcStatus.QUEUED, rpcAfterUplink.getStatus()); + Assert.assertNull(rpcAfterUplink.getResponse()); + } + @Test public void testRpcV2DeleteFromEdge() throws Exception { Device device = saveDeviceOnCloudAndVerifyDeliveryToEdge(); @@ -787,8 +800,12 @@ public class DeviceEdgeTest extends AbstractEdgeTest { } private Rpc savePersistentRpc(Device device, RpcStatus status) throws Exception { + return savePersistentRpc(tenantId, device, status); + } + + private Rpc savePersistentRpc(TenantId rpcTenantId, Device device, RpcStatus status) throws Exception { Rpc rpc = new Rpc(new RpcId(Uuids.timeBased())); - rpc.setTenantId(tenantId); + rpc.setTenantId(rpcTenantId); rpc.setDeviceId(device.getId()); rpc.setExpirationTime(System.currentTimeMillis() + TimeUnit.MINUTES.toMillis(1)); rpc.setRequest(JacksonUtil.newObjectNode().put("method", "test_method")); diff --git a/application/src/test/java/org/thingsboard/server/edge/EntityGroupEdgeTest.java b/application/src/test/java/org/thingsboard/server/edge/EntityGroupEdgeTest.java index 9c54822fbd..e44e60f6e4 100644 --- a/application/src/test/java/org/thingsboard/server/edge/EntityGroupEdgeTest.java +++ b/application/src/test/java/org/thingsboard/server/edge/EntityGroupEdgeTest.java @@ -39,6 +39,7 @@ import org.thingsboard.server.gen.edge.v1.EntityGroupRequestMsg; import org.thingsboard.server.gen.edge.v1.EntityViewUpdateMsg; import org.thingsboard.server.gen.edge.v1.GroupPermissionProto; import org.thingsboard.server.gen.edge.v1.UpdateMsgType; +import org.thingsboard.server.service.edge.EdgeMsgConstructorUtils; import org.thingsboard.server.gen.edge.v1.UserUpdateMsg; import org.thingsboard.server.gen.edge.v1.UplinkMsg; @@ -229,6 +230,23 @@ public class EntityGroupEdgeTest extends AbstractEdgeTest { .setType(EntityType.DEVICE.name()).build())); } + @Test + public void testSendDeviceUpdateWithGroupOfDifferentTenantToCloud() throws Exception { + loginDifferentTenant(); + Device differentTenantDevice = new Device(); + differentTenantDevice.setName("Different Tenant Grouped Device"); + differentTenantDevice.setType("default"); + differentTenantDevice = doPost("/api/device", differentTenantDevice, Device.class); + EntityGroup deviceGroup = saveDifferentTenantGroup(EntityType.DEVICE, differentTenantDevice.getId()); + loginTenantAdmin(); + + Device device = saveDevice("Group Test Device", "default"); + sendUplinkMsgAndWaitForResponse(uplinkMsgBuilder -> uplinkMsgBuilder.addDeviceUpdateMsg( + EdgeMsgConstructorUtils.constructDeviceUpdatedMsg(UpdateMsgType.ENTITY_UPDATED_RPC_MESSAGE, device, deviceGroup.getId()))); + + Assert.assertFalse(findGroupEntityIds(deviceGroup).contains(device.getId())); + } + private EntityGroup saveDifferentTenantGroup(EntityType groupType, EntityId entityId) throws Exception { EntityGroup entityGroup = new EntityGroup(); entityGroup.setType(groupType); diff --git a/application/src/test/java/org/thingsboard/server/edge/RuleChainEdgeTest.java b/application/src/test/java/org/thingsboard/server/edge/RuleChainEdgeTest.java index 1e9e8e7754..1abdafeabb 100644 --- a/application/src/test/java/org/thingsboard/server/edge/RuleChainEdgeTest.java +++ b/application/src/test/java/org/thingsboard/server/edge/RuleChainEdgeTest.java @@ -292,6 +292,29 @@ public class RuleChainEdgeTest extends AbstractEdgeTest { Assert.assertEquals(nodesCount, metaDataAfter.getNodes().size()); } + @Test + public void testSendRuleChainWithIdOfDifferentTenantToCloud() throws Exception { + RuleChainId ruleChainId = getDifferentTenantRootRuleChainId(); + loginDifferentTenant(); + String ruleChainName = doGet("/api/ruleChain/" + ruleChainId.getId(), RuleChain.class).getName(); + loginTenantAdmin(); + + RuleChain edgeRuleChain = new RuleChain(); + edgeRuleChain.setTenantId(tenantId); + edgeRuleChain.setId(ruleChainId); + edgeRuleChain.setName("Changed Rule Chain"); + sendUplinkMsgAndWaitForResponse(uplinkMsgBuilder -> uplinkMsgBuilder.addRuleChainUpdateMsg(RuleChainUpdateMsg.newBuilder() + .setMsgType(UpdateMsgType.ENTITY_UPDATED_RPC_MESSAGE) + .setIdMSB(ruleChainId.getId().getMostSignificantBits()) + .setIdLSB(ruleChainId.getId().getLeastSignificantBits()) + .setEntity(JacksonUtil.toString(edgeRuleChain)) + .build())); + + loginDifferentTenant(); + Assert.assertEquals(ruleChainName, doGet("/api/ruleChain/" + ruleChainId.getId(), RuleChain.class).getName()); + loginTenantAdmin(); + } + private RuleChainId getDifferentTenantRootRuleChainId() throws Exception { loginDifferentTenant(); RuleChain rootRuleChain = doGetTypedWithPageLink("/api/ruleChains?type={type}&", new TypeReference>() {}, diff --git a/application/src/test/java/org/thingsboard/server/edge/SchedulerEventEdgeTest.java b/application/src/test/java/org/thingsboard/server/edge/SchedulerEventEdgeTest.java index 5f00a00ba3..54621799ec 100644 --- a/application/src/test/java/org/thingsboard/server/edge/SchedulerEventEdgeTest.java +++ b/application/src/test/java/org/thingsboard/server/edge/SchedulerEventEdgeTest.java @@ -10,6 +10,7 @@ import org.thingsboard.common.util.JacksonUtil; import org.thingsboard.server.common.data.Customer; import org.thingsboard.server.common.data.id.EntityId; import org.thingsboard.server.common.data.id.SchedulerEventId; +import org.thingsboard.server.common.data.id.UserId; import org.thingsboard.server.common.data.msg.TbMsgType; import org.thingsboard.server.common.data.page.PageData; import org.thingsboard.server.common.data.report.ReportConfig; @@ -316,6 +317,27 @@ public class SchedulerEventEdgeTest extends AbstractEdgeTest { public void testGenerateReportSchedulerEventWithUserOfDifferentTenantToCloud() throws Exception { loginDifferentTenant(); loginTenantAdmin(); + SchedulerEvent schedulerEvent = createGenerateReportSchedulerEvent(savedDifferentTenantUser.getId()); + + edgeImitator.expectResponsesAmount(1); + edgeImitator.sendUplinkMsg(createUplinkMsg(schedulerEvent)); + Assert.assertTrue(edgeImitator.waitForResponses()); + + doGet("/api/schedulerEvent/" + schedulerEvent.getUuidId()).andExpect(status().isNotFound()); + } + + @Test + public void testGenerateReportSchedulerEventToCloud() throws Exception { + SchedulerEvent schedulerEvent = createGenerateReportSchedulerEvent(tenantAdminUserId); + + edgeImitator.expectResponsesAmount(1); + edgeImitator.sendUplinkMsg(createUplinkMsg(schedulerEvent)); + Assert.assertTrue(edgeImitator.waitForResponses()); + + doGet("/api/schedulerEvent/" + schedulerEvent.getUuidId()).andExpect(status().isOk()); + } + + private SchedulerEvent createGenerateReportSchedulerEvent(UserId userId) throws Exception { ReportTemplate reportTemplate = new ReportTemplate(); reportTemplate.setTenantId(tenantId); reportTemplate.setOwnerId(tenantId); @@ -333,18 +355,13 @@ public class SchedulerEventEdgeTest extends AbstractEdgeTest { ReportConfig reportConfig = new ReportConfig(); reportConfig.setReportTemplateId(savedReportTemplate.getId()); - reportConfig.setUserId(savedDifferentTenantUser.getId()); + reportConfig.setUserId(userId); reportConfig.setTimezone("UTC"); SchedulerEvent schedulerEvent = createSchedulerEvent("Edge Report Scheduler Event", tenantId); schedulerEvent.setId(new SchedulerEventId(UUID.randomUUID())); schedulerEvent.setType(GENERATE_REPORT); schedulerEvent.setConfiguration(JacksonUtil.valueToTree(reportConfig)); - - edgeImitator.expectResponsesAmount(1); - edgeImitator.sendUplinkMsg(createUplinkMsg(schedulerEvent)); - Assert.assertTrue(edgeImitator.waitForResponses()); - - doGet("/api/schedulerEvent/" + schedulerEvent.getUuidId()).andExpect(status().isNotFound()); + return schedulerEvent; } } diff --git a/application/src/test/java/org/thingsboard/server/edge/TenantProfileEdgeTest.java b/application/src/test/java/org/thingsboard/server/edge/TenantProfileEdgeTest.java index 5904901d01..94ef371c9c 100644 --- a/application/src/test/java/org/thingsboard/server/edge/TenantProfileEdgeTest.java +++ b/application/src/test/java/org/thingsboard/server/edge/TenantProfileEdgeTest.java @@ -14,6 +14,8 @@ import org.thingsboard.server.common.data.queue.ProcessingStrategyType; import org.thingsboard.server.common.data.queue.Queue; import org.thingsboard.server.common.data.queue.SubmitStrategy; import org.thingsboard.server.common.data.queue.SubmitStrategyType; +import org.thingsboard.server.common.data.tenant.profile.DefaultTenantProfileConfiguration; +import org.thingsboard.server.common.data.tenant.profile.TenantProfileData; import org.thingsboard.server.common.data.tenant.profile.TenantProfileQueueConfiguration; import org.thingsboard.server.dao.service.DaoSqlTest; import org.thingsboard.server.gen.edge.v1.QueueUpdateMsg; @@ -25,6 +27,7 @@ import java.util.List; import java.util.Optional; import static org.assertj.core.api.Assertions.assertThat; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; @DaoSqlTest public class TenantProfileEdgeTest extends AbstractEdgeTest { @@ -55,6 +58,24 @@ public class TenantProfileEdgeTest extends AbstractEdgeTest { loginTenantAdmin(); } + @Test + public void testTenantProfileOfDifferentTenantNotSentToEdge() throws Exception { + loginSysAdmin(); + TenantProfile otherTenantProfile = new TenantProfile(); + otherTenantProfile.setName("Other Tenant Profile Edge Test"); + otherTenantProfile.setProfileData(new TenantProfileData()); + otherTenantProfile.getProfileData().setConfiguration(new DefaultTenantProfileConfiguration()); + otherTenantProfile = doPost("/api/tenantProfile", otherTenantProfile, TenantProfile.class); + + otherTenantProfile.setDescription("Updated other tenant profile"); + edgeImitator.expectMessageAmount(1); + doPost("/api/tenantProfile", otherTenantProfile, TenantProfile.class); + Assert.assertFalse(edgeImitator.waitForMessages(2)); + + doDelete("/api/tenantProfile/" + otherTenantProfile.getUuidId()).andExpect(status().isOk()); + loginTenantAdmin(); + } + @Test public void testIsolatedTenantProfile() throws Exception { loginSysAdmin(); diff --git a/application/src/test/java/org/thingsboard/server/edge/UserEdgeTest.java b/application/src/test/java/org/thingsboard/server/edge/UserEdgeTest.java index 0a0c3bd08b..629e6f9f15 100644 --- a/application/src/test/java/org/thingsboard/server/edge/UserEdgeTest.java +++ b/application/src/test/java/org/thingsboard/server/edge/UserEdgeTest.java @@ -603,8 +603,8 @@ public class UserEdgeTest extends AbstractEdgeTest { private void verifyNoEdgeEvents(UserId userId) { Awaitility.await() - .pollDelay(3, TimeUnit.SECONDS) - .atMost(10, TimeUnit.SECONDS) + .pollDelay(2, TimeUnit.SECONDS) + .atMost(5, TimeUnit.SECONDS) .untilAsserted(() -> { PageData edgeEvents = edgeEventService.findEdgeEvents(tenantId, edge.getId(), 0L, Long.MAX_VALUE, new TimePageLink(1000)); Assert.assertTrue(edgeEvents.getData().stream().noneMatch(edgeEvent -> userId.getId().equals(edgeEvent.getEntityId()))); diff --git a/application/src/test/java/org/thingsboard/server/edge/WidgetEdgeTest.java b/application/src/test/java/org/thingsboard/server/edge/WidgetEdgeTest.java index b648400f4d..52423fca3b 100644 --- a/application/src/test/java/org/thingsboard/server/edge/WidgetEdgeTest.java +++ b/application/src/test/java/org/thingsboard/server/edge/WidgetEdgeTest.java @@ -11,9 +11,12 @@ import org.thingsboard.server.common.data.widget.WidgetType; import org.thingsboard.server.common.data.widget.WidgetsBundle; import org.thingsboard.server.dao.service.DaoSqlTest; import org.thingsboard.server.gen.edge.v1.UpdateMsgType; +import org.thingsboard.server.gen.edge.v1.WidgetBundleTypesRequestMsg; import org.thingsboard.server.gen.edge.v1.WidgetTypeUpdateMsg; import org.thingsboard.server.gen.edge.v1.WidgetsBundleUpdateMsg; +import java.util.List; + import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; @DaoSqlTest @@ -108,4 +111,25 @@ public class WidgetEdgeTest extends AbstractEdgeTest { Assert.assertEquals(savedWidgetsBundle.getUuidId().getLeastSignificantBits(), widgetsBundleUpdateMsg.getIdLSB()); } + @Test + public void testSendWidgetBundleTypesRequestForBundleOfDifferentTenantToCloud() throws Exception { + loginDifferentTenant(); + WidgetsBundle widgetsBundle = new WidgetsBundle(); + widgetsBundle.setTitle("Different Tenant Widget Bundle"); + WidgetsBundle savedWidgetsBundle = doPost("/api/widgetsBundle", widgetsBundle, WidgetsBundle.class); + WidgetType widgetType = new WidgetType(); + widgetType.setName("Different Tenant Widget Type"); + widgetType.setDescriptor(JacksonUtil.newObjectNode().put("key", "value")); + widgetType.setFqn("different_tenant_bundle.type_alias"); + doPost("/api/widgetType", widgetType, WidgetType.class); + doPost("/api/widgetsBundle/" + savedWidgetsBundle.getUuidId() + "/widgetTypeFqns", List.of(widgetType.getFqn())) + .andExpect(status().isOk()); + loginTenantAdmin(); + + sendUplinkMsgAndVerifyNoDownlink(uplinkMsgBuilder -> uplinkMsgBuilder.addWidgetBundleTypesRequestMsg(WidgetBundleTypesRequestMsg.newBuilder() + .setWidgetBundleIdMSB(savedWidgetsBundle.getUuidId().getMostSignificantBits()) + .setWidgetBundleIdLSB(savedWidgetsBundle.getUuidId().getLeastSignificantBits()) + .build())); + } + } diff --git a/application/src/test/java/org/thingsboard/server/service/edge/EdgeMsgSummaryUtilsTest.java b/application/src/test/java/org/thingsboard/server/service/edge/EdgeMsgSummaryUtilsTest.java index 8ab4db4476..d12691f00c 100644 --- a/application/src/test/java/org/thingsboard/server/service/edge/EdgeMsgSummaryUtilsTest.java +++ b/application/src/test/java/org/thingsboard/server/service/edge/EdgeMsgSummaryUtilsTest.java @@ -7,9 +7,11 @@ import org.junit.jupiter.api.Test; import org.thingsboard.server.gen.edge.v1.DeviceCredentialsUpdateMsg; import org.thingsboard.server.gen.edge.v1.DeviceUpdateMsg; import org.thingsboard.server.gen.edge.v1.DownlinkMsg; +import org.thingsboard.server.gen.edge.v1.UpdateMsgType; import org.thingsboard.server.gen.edge.v1.UplinkMsg; import java.util.List; +import java.util.UUID; public class EdgeMsgSummaryUtilsTest { @@ -42,4 +44,19 @@ public class EdgeMsgSummaryUtilsTest { Assertions.assertFalse(summary.contains(SECRET)); } + @Test + public void testEntityMsgSummaryHasTypeAndIdWithoutPayload() { + UUID deviceUuid = UUID.randomUUID(); + DeviceUpdateMsg deviceUpdateMsg = DeviceUpdateMsg.newBuilder() + .setMsgType(UpdateMsgType.ENTITY_UPDATED_RPC_MESSAGE) + .setIdMSB(deviceUuid.getMostSignificantBits()) + .setIdLSB(deviceUuid.getLeastSignificantBits()) + .setEntity("{\"name\":\"" + SECRET + "\"}") + .build(); + + String summary = EdgeMsgSummaryUtils.toSummary(deviceUpdateMsg); + + Assertions.assertEquals("DeviceUpdateMsg[msgType=ENTITY_UPDATED_RPC_MESSAGE, id=" + deviceUuid + "]", summary); + } + } diff --git a/common/data/src/main/java/org/thingsboard/server/common/data/edge/EdgeEventType.java b/common/data/src/main/java/org/thingsboard/server/common/data/edge/EdgeEventType.java index 6d07326bf3..bcb2bb8631 100644 --- a/common/data/src/main/java/org/thingsboard/server/common/data/edge/EdgeEventType.java +++ b/common/data/src/main/java/org/thingsboard/server/common/data/edge/EdgeEventType.java @@ -8,68 +8,78 @@ import org.thingsboard.server.common.data.EntityType; @Getter public enum EdgeEventType { - DASHBOARD(false, EntityType.DASHBOARD), - ASSET(false, EntityType.ASSET), - DEVICE(false, EntityType.DEVICE), - DEVICE_PROFILE(true, EntityType.DEVICE_PROFILE), - ASSET_PROFILE(true, EntityType.ASSET_PROFILE), - ENTITY_VIEW(false, EntityType.ENTITY_VIEW), - ALARM(false, EntityType.ALARM), - ALARM_COMMENT(false, null), - RULE_CHAIN(false, EntityType.RULE_CHAIN), - RULE_CHAIN_METADATA(false, null), - EDGE(false, EntityType.EDGE), - USER(false, EntityType.USER), - CUSTOMER(true, EntityType.CUSTOMER), - RELATION(true, null), - TENANT(true, EntityType.TENANT), - TENANT_PROFILE(true, true, EntityType.TENANT_PROFILE), - WIDGETS_BUNDLE(true, true, EntityType.WIDGETS_BUNDLE), - WIDGET_TYPE(true, true, EntityType.WIDGET_TYPE), - ADMIN_SETTINGS(true, true, EntityType.ADMIN_SETTINGS), - OTA_PACKAGE(true, EntityType.OTA_PACKAGE), - QUEUE(true, true, EntityType.QUEUE), - ENTITY_GROUP(false, EntityType.ENTITY_GROUP), - SCHEDULER_EVENT(false, EntityType.SCHEDULER_EVENT), - WHITE_LABELING(true, true, null), - LOGIN_WHITE_LABELING(true, true, null), - MAIL_TEMPLATES(true, true, null), - CUSTOM_TRANSLATION(true, true, null), - CUSTOM_MENU(true, true, null), - ROLE(true, EntityType.ROLE), - GROUP_PERMISSION(true, EntityType.GROUP_PERMISSION), - CONVERTER(false, EntityType.CONVERTER), - INTEGRATION(false, EntityType.INTEGRATION), - NOTIFICATION_RULE(true, true, EntityType.NOTIFICATION_RULE), - NOTIFICATION_TARGET(true, true, EntityType.NOTIFICATION_TARGET), - NOTIFICATION_TEMPLATE(true, true, EntityType.NOTIFICATION_TEMPLATE), - TB_RESOURCE(true, true, EntityType.TB_RESOURCE), - DEVICE_GROUP_OTA(false, null), - OAUTH2_CLIENT(true, true, EntityType.OAUTH2_CLIENT), - DOMAIN(true, true, EntityType.DOMAIN), - CALCULATED_FIELD(false, EntityType.CALCULATED_FIELD), - ENCRYPTION_KEY(true, null), - SECRET(true, EntityType.SECRET), - REPORT_TEMPLATE(true, EntityType.REPORT_TEMPLATE), - AI_MODEL(true, EntityType.AI_MODEL), - API_KEY(true, EntityType.API_KEY); + DASHBOARD(EdgeEventScope.ASSIGNED_EDGES, EntityType.DASHBOARD), + ASSET(EdgeEventScope.ASSIGNED_EDGES, EntityType.ASSET), + DEVICE(EdgeEventScope.ASSIGNED_EDGES, EntityType.DEVICE), + DEVICE_PROFILE(EdgeEventScope.TENANT_EDGES, EntityType.DEVICE_PROFILE), + ASSET_PROFILE(EdgeEventScope.TENANT_EDGES, EntityType.ASSET_PROFILE), + ENTITY_VIEW(EdgeEventScope.ASSIGNED_EDGES, EntityType.ENTITY_VIEW), + ALARM(EdgeEventScope.ASSIGNED_EDGES, EntityType.ALARM), + ALARM_COMMENT(EdgeEventScope.ASSIGNED_EDGES, null), + RULE_CHAIN(EdgeEventScope.ASSIGNED_EDGES, EntityType.RULE_CHAIN), + RULE_CHAIN_METADATA(EdgeEventScope.ASSIGNED_EDGES, null), + EDGE(EdgeEventScope.ASSIGNED_EDGES, EntityType.EDGE), + USER(EdgeEventScope.ASSIGNED_EDGES, EntityType.USER), + CUSTOMER(EdgeEventScope.TENANT_EDGES, EntityType.CUSTOMER), + RELATION(EdgeEventScope.TENANT_EDGES, null), + TENANT(EdgeEventScope.TENANT_EDGES, EntityType.TENANT), + TENANT_PROFILE(EdgeEventScope.SYSTEM_AND_TENANT_EDGES, EntityType.TENANT_PROFILE), + WIDGETS_BUNDLE(EdgeEventScope.SYSTEM_AND_TENANT_EDGES, EntityType.WIDGETS_BUNDLE), + WIDGET_TYPE(EdgeEventScope.SYSTEM_AND_TENANT_EDGES, EntityType.WIDGET_TYPE), + ADMIN_SETTINGS(EdgeEventScope.SYSTEM_AND_TENANT_EDGES, EntityType.ADMIN_SETTINGS), + OTA_PACKAGE(EdgeEventScope.TENANT_EDGES, EntityType.OTA_PACKAGE), + QUEUE(EdgeEventScope.SYSTEM_AND_TENANT_EDGES, EntityType.QUEUE), + ENTITY_GROUP(EdgeEventScope.ASSIGNED_EDGES, EntityType.ENTITY_GROUP), + SCHEDULER_EVENT(EdgeEventScope.ASSIGNED_EDGES, EntityType.SCHEDULER_EVENT), + WHITE_LABELING(EdgeEventScope.SYSTEM_AND_TENANT_EDGES, null), + LOGIN_WHITE_LABELING(EdgeEventScope.SYSTEM_AND_TENANT_EDGES, null), + MAIL_TEMPLATES(EdgeEventScope.SYSTEM_AND_TENANT_EDGES, null), + CUSTOM_TRANSLATION(EdgeEventScope.SYSTEM_AND_TENANT_EDGES, null), + CUSTOM_MENU(EdgeEventScope.SYSTEM_AND_TENANT_EDGES, null), + ROLE(EdgeEventScope.TENANT_EDGES, EntityType.ROLE), + GROUP_PERMISSION(EdgeEventScope.TENANT_EDGES, EntityType.GROUP_PERMISSION), + CONVERTER(EdgeEventScope.ASSIGNED_EDGES, EntityType.CONVERTER), + INTEGRATION(EdgeEventScope.ASSIGNED_EDGES, EntityType.INTEGRATION), + NOTIFICATION_RULE(EdgeEventScope.SYSTEM_AND_TENANT_EDGES, EntityType.NOTIFICATION_RULE), + NOTIFICATION_TARGET(EdgeEventScope.SYSTEM_AND_TENANT_EDGES, EntityType.NOTIFICATION_TARGET), + NOTIFICATION_TEMPLATE(EdgeEventScope.SYSTEM_AND_TENANT_EDGES, EntityType.NOTIFICATION_TEMPLATE), + TB_RESOURCE(EdgeEventScope.SYSTEM_AND_TENANT_EDGES, EntityType.TB_RESOURCE), + DEVICE_GROUP_OTA(EdgeEventScope.ASSIGNED_EDGES, null), + OAUTH2_CLIENT(EdgeEventScope.SYSTEM_AND_TENANT_EDGES, EntityType.OAUTH2_CLIENT), + DOMAIN(EdgeEventScope.SYSTEM_AND_TENANT_EDGES, EntityType.DOMAIN), + CALCULATED_FIELD(EdgeEventScope.ASSIGNED_EDGES, EntityType.CALCULATED_FIELD), + ENCRYPTION_KEY(EdgeEventScope.TENANT_EDGES, null), + SECRET(EdgeEventScope.TENANT_EDGES, EntityType.SECRET), + REPORT_TEMPLATE(EdgeEventScope.TENANT_EDGES, EntityType.REPORT_TEMPLATE), + AI_MODEL(EdgeEventScope.TENANT_EDGES, EntityType.AI_MODEL), + API_KEY(EdgeEventScope.TENANT_EDGES, EntityType.API_KEY); - // entity is pushed to all edges of its tenant, otherwise only to edges it's assigned to - private final boolean allTenantEdgesRelated; - - // entity can be owned by system tenant, so system level events are pushed to all edges - private final boolean systemLevelSupported; + private final EdgeEventScope scope; private final EntityType entityType; + EdgeEventType(EdgeEventScope scope, EntityType entityType) { + this.scope = scope; + this.entityType = entityType; + } - EdgeEventType(boolean allTenantEdgesRelated, EntityType entityType) { - this(allTenantEdgesRelated, false, entityType); + // entity is pushed to all edges of its tenant, otherwise only to edges it's assigned to + public boolean isAllTenantEdgesRelated() { + return scope != EdgeEventScope.ASSIGNED_EDGES; } - EdgeEventType(boolean allTenantEdgesRelated, boolean systemLevelSupported, EntityType entityType) { - this.allTenantEdgesRelated = allTenantEdgesRelated; - this.systemLevelSupported = systemLevelSupported; - this.entityType = entityType; + // entity can be owned by system tenant, so system level events are pushed to all edges + public boolean isSystemLevelSupported() { + return scope == EdgeEventScope.SYSTEM_AND_TENANT_EDGES; } + + public enum EdgeEventScope { + // only edges the entity is assigned to + ASSIGNED_EDGES, + // all edges of the entity's tenant + TENANT_EDGES, + // all edges of the entity's tenant, or all edges if the entity is owned by system tenant + SYSTEM_AND_TENANT_EDGES + } + } diff --git a/edge-tenant-isolation-summary.md b/edge-tenant-isolation-summary.md new file mode 100644 index 0000000000..f321b15160 --- /dev/null +++ b/edge-tenant-isolation-summary.md @@ -0,0 +1,173 @@ +# Edge tenant isolation: fixes summary + +Confidential: PROD-9075, PROD-9081. Keep out of public PRs, commits and changelogs. + +**Common cause:** messages from an edge were not consistently checked against the edge's own tenant. The cloud took the tenant id from the payload, looked entities up by id without a tenant filter, and didn't validate referenced ids. + +**Merge order:** CE lts-4.2 → PE lts-4.2 → CE lts-4.3 → PE lts-4.3 (merges CE 4.3 and PE 4.2) → CE lts-4.4. CE `lts-4.4` merges CE `lts-4.3` (CE history only); PE-only fixes reach CE 4.4 as separate hand-written CE commits, never through a PE merge. Fixes in 4.2 reach later branches through the regular merges. Later sections list only what is new on that branch. + +--- + +## PR matrix + +Merge in this order. Each PR already contains the previous one in its chain, and every PR and forward merge (CE 4.2 → CE 4.3 → CE 4.4, CE 4.2 → PE 4.2 → PE 4.3, CE 4.3 → PE 4.3) was checked to merge without conflicts against upstream as of 2026-10-27. + +| # | Repo | Version | PR | Branch → base | Head | Contains | After merge | +|---|---|---|---|---|---|---|---| +| 1 | CE | 4.2 | [#16451](https://github.com/thingsboard/thingsboard/pull/16451) | `fix/edge-uplink-msgs-processing-lts-4.2` → `lts-4.2` | `728e0016ad3` | CE 4.2 fixes | Merge CE `lts-4.2` into PE `lts-4.2` and CE `lts-4.3` | +| 2 | PE | 4.2 | [#5279](https://github.com/thingsboard/thingsboard-pe/pull/5279) | `pe-fix/edge-uplink-msgs-processing-lts-4.2` → `lts-4.2` | `4b08f3bdec3` | #1 + PE group/owner checks | Merge PE `lts-4.2` into PE `lts-4.3` | +| 3 | CE | 4.3 | [#16452](https://github.com/thingsboard/thingsboard/pull/16452) | `fix/edge-uplink-msgs-processing-lts-4.3` → `lts-4.3` | `92140de0792` | #1 + user, API key, AI model, delete paths | Merge CE `lts-4.3` into PE `lts-4.3` and CE `lts-4.4` | +| 4 | PE | 4.3 | [#5280](https://github.com/thingsboard/thingsboard-pe/pull/5280) | `pe-fix/edge-uplink-msgs-processing-lts-4.3` → `lts-4.3` | `15125d8909d` | #2 + #3 + user group removal, report templates, scheduler events | — (4.4 is CE only; never merge PE into CE) | +| 5 | CE | 4.4 | [#16453](https://github.com/thingsboard/thingsboard/pull/16453) | `fix/edge-uplink-msgs-processing-lts-4.4` → `lts-4.4` | `dcb9c6dada2` | #3 + group/owner, user group removal, report templates, scheduler events (written as CE commits) | — | + +--- + +## CE lts-4.2 + +Branch `fix/edge-uplink-msgs-processing-lts-4.2`. Edge test suite: 121/121 pass, and each new test fails without its fix. + +| # | Area | Processors / paths | Issue | Fix | Tests | Status | +|---|---|---|---|---|---|---| +| 1 | Request messages | `DefaultEdgeRequestsService`: user credentials, device credentials, attributes, relations, rule chain metadata, widget bundle types | Requested ids were not checked against the edge's tenant, so the response could contain another tenant's data | `isTenantEntity` check before queuing the response. Widget bundles: own tenant or system tenant only | `UserEdgeTest`, `DeviceEdgeTest`, `RelationEdgeTest`, `RuleChainEdgeTest` (`…RequestFor…OfDifferentTenant…`) | Fixed | +| 2 | Entities with a tenant | device, device profile, asset, asset profile, dashboard, entity view, resource, calculated field, rule chain | Tenant taken from the payload; an id from another tenant could be created or overwritten | `checkEntityTenant` rejects foreign ids; tenant forced; validator runs against the edge's tenant; rule chain id taken from the message | `DeviceEdgeTest`, `DashboardEdgeTest`, `ResourceEdgeTest` (`…OfDifferentTenant…`, `…WithSystemTenantId…`) | Fixed | +| 3 | References | entity view target; calculated field entity and arguments; rule chain metadata target | Referenced entities were not checked against the edge's tenant | Must belong to the edge's tenant (`isEntityExists`) | `EntityViewEdgeTest`, `CalculatedFieldEdgeTest`, `RuleChainEdgeTest` | Fixed | +| 4 | Telemetry | attributes update/post, telemetry post, attribute delete | Target entity was only checked to exist | Target must belong to the edge's tenant (shared `isEntityExists`) | `TelemetryEdgeTest` | Fixed | +| 5 | Alarms | alarm, alarm comment | Originator and tenant taken from the payload; comments matched by id only | Originator in the edge's tenant; tenant forced; alarm id checked; comment must belong to an alarm of the edge's tenant | `AlarmEdgeTest` | Fixed | +| 6 | Relations | create, delete | Delete had no tenant check; create used an unscoped check | Both ends must belong to the edge's tenant | `RelationEdgeTest` | Fixed | +| 7 | Device RPC | status, response, request | RPC/device ids not checked | RPC and device must belong to the edge's tenant | covered by the existing RPC tests | Fixed | +| 8 | Unassign on delete | asset, dashboard, entity view, rule chain, calculated field, device (device: explicit guard added for consistency; the tenant-scoped `findDeviceById` already returns null for a foreign device) | Entity tenant not checked | Tenant guard | covered by the existing delete tests | Fixed | +| 9 | System-context events | `BaseEdgeProcessor.processActionForAllEdges`, `EdgeEventType`, `UserEdgeProcessor` | Events about tenant users raised without a tenant (auth flows, sysadmin actions) were queued for every active edge | `EdgeEventType.systemLevelSupported` (11 system-ownable types) and `allEdgesRelated` renamed to `allTenantEdgesRelated`. In system context: system-level types are broadcast, other types go to the entity's own tenant or are skipped. A user is sent only to edges of its own tenant | `UserEdgeTest`: `testUserActivationInDifferentTenant`, `testSysAdminCredentialsUpdate`, `testTenantUserCredentialsUpdate` | Fixed | +| 9a | System-context events, edge-assigned types | `BaseEdgeProcessor.processEntityNotification` (edge-assigned branch) | Where users are edge-assigned (PE, CE 4.4), credentials updated in system context (activation, password reset completion) were saved under the system tenant and never delivered to the user's edges | The notification is re-processed under the entity's own tenant; skipped when the entity has no tenant | `UserEdgeTest.testTenantUserCredentialsUpdate` (fails on plain PE 4.2) | Fixed | +| 10 | Email / SMS / notifications | `processSendEmailMsg`, `processSendSmsMsg`, `processSendNotificationMsg` | Recipients and content aren't restricted | Left to the planned "smart send" work; tenant-profile limits apply on PaaS | — | Not changed | +| 11 | Alarm comment author | alarm comment | Author user id taken from the payload | No cross-tenant write; left as is | — | Not changed | +| 12 | Rule node configurations | rule chain metadata | Node configs saved as sent | They run in the edge's own tenant; left as is | — | Not changed | +| 13 | Widget bundle request | `processWidgetBundleTypesRequestMsg` | — | Fixed in #1 | No dedicated test | Test gap | + +--- + +## PE lts-4.2 (after merging CE 4.2) + +Branch `pe-fix/edge-uplink-msgs-processing-lts-4.2`. Edge suite after the merge: 140/141; the only failure (`testTenantUserCredentialsUpdate`) also failed on plain PE 4.2 and is fixed by CE 4.2 #9a. + +| # | Area | Processors / paths | Issue | Fix | Tests | Status | +|---|---|---|---|---|---|---| +| 1 | Entity groups | add to group (`safeAddEntityToGroup`); remove from group on delete (device, asset, dashboard, entity view) | Group id from the edge not checked | Group owner (tenant or its customer) must belong to the edge's tenant (`safeRemoveEntityFromGroup`) | `EntityGroupEdgeTest.testSendDeviceDeleteFromGroupOfDifferentTenantToCloud` | Fixed | +| 2 | Owner change | `changeOwnerIfRequired` | Target customer taken from the payload | Rejected unless the owner belongs to the edge's tenant | `DeviceEdgeTest.testSendDeviceUpdateWithCustomerOfDifferentTenantToCloud` | Fixed | +| 3 | Entity group entities request | `processEntityGroupEntitiesRequest` | Group looked up without tenant check (members already re-filtered) | Skipped unless the group owner belongs to the edge's tenant | `EntityGroupEdgeTest.testSendEntityGroupEntitiesRequestForGroupOfDifferentTenantToCloud` (regression only) | Fixed | +| 4 | Scheduler events, report templates | — | No uplink processors in PE 4.2 (they exist on PE 4.3, see CE 4.4 #6–#7) | — | — | N/A | + +--- + +## CE lts-4.3 (after merging 4.2) + +| # | Area | Processors / paths | Issue | Planned fix | Status | +|---|---|---|---|---|---| +| 1 | User uplink | `BaseUserProcessor`: user save/update/delete, credentials | Tenant and authority taken from the payload; user ids from other tenants accepted | Tenant forced; authorities limited to tenant admin and customer user; cross-tenant user ids rejected | Fixed (#16432/#16433) | +| 2 | User credentials id | `BaseUserProcessor.updateUserCredentials` | Credentials record id from the payload is not checked | New `UserService.findUserCredentialsById`; skipped if the record belongs to a different user. Test: `UserEdgeTest.testSendUserCredentialsWithIdOfDifferentTenantUserToCloud` | Fixed | +| 3 | Authority test | `UserEdgeTest` | Test covers only SYS_ADMIN, which the validator also rejects | `testSendUserWithTokenAuthorityFromEdgeToCloud` (REFRESH_TOKEN) | Fixed | +| 4 | API keys | `BaseApiKeyProcessor` | Tenant and user taken from the payload; lookup by id unscoped | Foreign id rejected; tenant forced; user must be in the edge's tenant; tenant guard on delete. `internal`/`permissions` don't exist on 4.3 (see 4.4). Test: `ApiKeyEdgeTest.testSendApiKeyForUserOfDifferentTenantToCloud` | Fixed | +| 5 | AI models | `BaseAiModelProcessor` | Tenant taken from the payload; lookup by id unscoped | Foreign id rejected; tenant forced. Test: `AiModelEdgeTest.testSendAiModelWithTenantIdOfDifferentTenantToCloud` | Fixed | +| 6 | User downlink with API keys | `UserEdgeProcessor` ADDED/UPDATED | Also carries API keys | Covered by CE 4.2 #9; verify after merge | Verify | +| 7 | Edge credentials visibility | `EdgeController.getEdgeById` | Edge credentials visible to customer users with access to the edge | Product decision | Open | +| 8 | New event types | `EdgeEventType` entries added in 4.3 | — | `AI_MODEL`, `API_KEY`: not system-level (system-owned internal keys are skipped) | Fixed | +| 9 | Delete paths | asset, dashboard, entity view deletes really delete on 4.3 | Tenant guard inside `deleteAsset`, `deleteDashboard`, `deleteEntityView` | Fixed | +| 10 | Device delete | `BaseDeviceProcessor.deleteDevice` | Looked like an unguarded real delete | Not a gap: `findDeviceById` with a tenant id uses `findDeviceByTenantIdAndId`, so a foreign device is not found. Regression test `DeviceEdgeTest.testSendDeviceDeleteForDeviceOfDifferentTenantToCloud` (from 4.2) | OK | + +--- + +## PE lts-4.3 (after merging CE 4.3) + +| # | Area | Planned fix | Status | +|---|---|---|---| +| 1 | PE-only items from PE 4.2 | Merged PE 4.2 (`077ea1f16e2`); group removal on delete uses `safeRemoveEntityFromGroup`, while the edge ≥ 4.3.0 branch still deletes | Done | +| 2 | CE 4.3 items on PE code paths | Merged CE 4.3 (`6b66b550fca`); `REPORT_TEMPLATE` is not system-level (tenant/customer owned only) | Done | +| 3 | Device delete | Not a gap (see CE 4.3 #10); merged CE 4.3 `73f1933c680` and PE 4.2 `10ce7c7a3d7`, pushed to nm-pe | Done | + +--- + +## CE lts-4.4 (after merging CE 4.3) + +Branch `fix/edge-uplink-msgs-processing-lts-4.4` from `tb-ce/lts-4.4`. CE 4.3 merged as usual (CE history only). PE-only changes are written by hand as a new CE commit; nothing is merged or cherry-picked from PE. + +| # | Area | Issue | Fix | Tests | Status | +|---|---|---|---|---|---| +| 0 | API keys | `internal`/`permissions` exist on 4.4 | No change needed: `ApiKeyServiceImpl.saveApiKey` clears both for keys not owned by the system tenant, and the tenant is forced; system-tenant (internal) keys are rejected by `checkEntityTenant` and skipped on delete | `ApiKeyEdgeTest.testSendInternalApiKeyWithPermissionsToCloud` | OK | +| 1 | Delete paths | Edge deletes really delete | Asset, dashboard, entity view, API key, calculated field, user: guarded. Device: tenant-scoped lookup. AI model: `deleteByTenantIdAndId` | — | OK | +| 2 | Tests | Message constructors take an extra entity group argument | `null` passed in the new tests | — | Done | +| 3 | New event types | — | None new on 4.4; white labeling, login white labeling, mail templates, custom translation and custom menu are system-level | — | Done | +| 4 | Entity groups / owner (PE features on 4.4) | Same as PE 4.2 #1–#3 | `safeAddEntityToGroup` and `safeRemoveEntityFromGroup` check the group owner; `changeOwnerIfRequired` rejects foreign owners; group entities request checks the group owner | `EntityGroupEdgeTest` (device and user group removal, group entities request), `DeviceEdgeTest.testSendDeviceUpdateWithCustomerOfDifferentTenantToCloud` | Fixed | +| 5 | User removal from group | `UserEdgeProcessor` removed users from any group by id (also on PE 4.3) | `safeRemoveEntityFromGroup` | `EntityGroupEdgeTest.testSendUserDeleteFromGroupOfDifferentTenantToCloud` | Fixed (4.4; PE 4.3 `95d3e3aed0e`, `bbd0eff9832`) | +| 6 | Report templates | Uplink processor (also on PE 4.3): tenant from payload, lookup by id only, delete unguarded | `checkEntityTenant`, tenant forced, delete guard; customer is checked by the validator once the tenant is forced | `ReportTemplateEdgeTest` (`…WithTenantIdOfDifferentTenant…`, `…UpdateAndDeleteOfDifferentTenant…`) | Fixed (4.4; PE 4.3 `95d3e3aed0e`, `bbd0eff9832`) | +| 7 | Scheduler events | Uplink processor (also on PE 4.3): tenant from payload, lookup by id only; `GENERATE_REPORT` config could name another tenant's report template or user (the controller checks both) | `checkEntityTenant`, tenant forced, report template and user must belong to the edge's tenant; unassign guarded | `SchedulerEventEdgeTest` (`…WithTenantIdOfDifferentTenant…`, `…GenerateReport…WithUserOfDifferentTenant…`) | Fixed (4.4; PE 4.3 `95d3e3aed0e`, `bbd0eff9832`) | +| 8 | Build | lts-4.4 compiled locally this time | — | — | Note | + +--- + +## Follow-up: external user uplink review (2026-10-28) + +The review read upstream CE `lts-4.3` / `lts-4.4` before our PRs and didn't know about the PE repo. Status against our branches: + +| Review # | Finding | Status | +|---|---|---| +| 1 | Edge creates a system admin / admin in another tenant | Fixed upstream (`98c3aad861a`) | +| 2 | Credentials record id of another user reused | Fixed (CE 4.3 #2) | +| 2 | Credentials overwrite across tenants | Fixed upstream | +| 3 | Edge requests any user's credentials | Fixed (CE 4.2 #1, `isTenantEntity` in `processUserCredentialsRequestMsg`) | +| 4, 5 | Delete / edit users across tenants | Fixed upstream | +| A, B | Owner change / group membership across tenants (4.4, PE 4.3) | Fixed (CE 4.4 #4–#5, PE 4.3 `95d3e3aed0e`) | + +Remaining items, in fix order (customer-level items are deferred, see below). All are pushed and merged forward: PE 4.2 `a900b576169`, PE 4.3 `864f0d82aa1`, CE 4.4 `78541941f9f` (on CE 4.4, #1 re-applied by hand in `rpc/session/EdgeGrpcSession` and `EdgeUplinkMessageDispatcher`, which replace the deleted `rpc/EdgeGrpcSession`): + +| # | Branch | Issue | Review # | Decision | Status | +|---|---|---|---|---|---| +| 1 | CE 4.2 | Edge secret, msg bodies and credentials in edge failure notifications and logs | 7 | Replace msg bodies with type/id/count summaries (`EdgeMsgSummaryUtils`); drop the secret; redact device credentials logs. TRACE logs and non-credential entity JSON in processor logs left as is | Pushed `46ea9dbd883`; `DeviceEdgeTest`, `UserEdgeTest` pass | +| 2 | CE 4.2 | Activation/reset tokens sent to edges with user credentials | 8 | Strip `activateToken`, `resetToken` and their expiry from the credentials downlink; keep the hash (needed for local login). Shared constructor, so it covers PE and 4.3+ after merges | Pushed `728e0016ad3` | +| 2a | CE 4.2 | `additionalInfo` (password history hashes) still sent to edges | 8 | Leave as is: the edge already has the current hash, old hashes add little and the edge uses them for its password-reuse check. The credentials uplink must not overwrite the cloud's history (see #3) | Won't fix | +| 3 | CE 4.3 | Credentials uplink accepts reset/activation tokens, `failedLoginAttempts`, `additionalInfo`; saved with validation off | 2 | Merge instead of replace: only `password` and `enabled` from the edge, the rest stays as on cloud; password history updated on change (`UserService.updatePasswordHistory` made public). Activation: edge `enabled=true` clears the cloud's activation token; edge pending activation (not enabled, has token) makes the cloud generate its own token if it has none. Also restored the `@Test` on `UserEdgeTest.testSendUserCredentialsRequestForUserOfDifferentTenantToCloud`, lost in the CE 4.2 → 4.3 merge (missing on PE 4.3 and CE 4.4 too) | Pushed `6af0dd38ce3`, `2b7830a03fc`; `UserEdgeTest` 15/15, new test fails without the fix | +| 4 | CE 4.3 | User, user credentials, API key and AI model msgs in logs and in exception texts (which reach the failure notification) | 7 | Same approach as #1: ids (user, API key, AI model) or `EdgeMsgSummaryUtils` summaries instead of msg bodies; no msg content in exceptions; TRACE left as is | Pushed `02e854f79b7`; `UserEdgeTest`, `ApiKeyEdgeTest`, `AiModelEdgeTest` pass | +| 5 | CE 4.3 | Duplicate email in another tenant blocks the edge's user uplink and reveals that the email exists | 9 | Check the email across the platform (`findUserByEmail`, same case handling as `saveUser`) and rename as for same-tenant duplicates. Same on Citus: `tb_user` is a reference table, uniqueness enforced cluster-wide. The "email exists" hint isn't new (user creation via REST gives the same error) | Pushed `0475763bba7`; `UserEdgeTest` 16/16, new test fails without the fix | + +### Deferred: customer-level isolation + +Tracked in [EDGE-122](https://thingsboard-portal.atlassian.net/browse/EDGE-122) (work scope, decisions and known gaps); linked to PROD-9081. + +All of these stay inside the edge's own tenant: a customer-owned/assigned edge acting on tenant-level or other customers' data. Put aside on 2026-10-29. + +**Customer-level isolation must be addressed separately**, as its own task and PR chain, not as part of this tenant isolation work: + +- **Different scope.** PROD-9075/9081 and these PRs cover tenant isolation: an edge of tenant A can't read or change tenant B's data. Customer-level isolation is the next level down: an edge assigned to (CE) or owned by (PE) customer X must not change tenant-level data (tenant admins, tenant groups) or data of customer Y in the same tenant. +- **Why it matters.** A customer edge often runs at the customer's site. A stolen edge or extracted credentials currently allow creating a `TENANT_ADMIN`, setting a tenant admin's password, editing or deleting other customers' users, adding a user to the Tenant Administrators group (PE), and offline cracking of tenant admin hashes. A compromise at one customer site can escalate to the whole tenant. +- **Needs product decisions first.** It is not a missing check but an undefined access model for customer edges: whether tenant admins may log in locally on customer edges (if not, their hashes stop being sent, which changes current behaviour), whether a customer edge may manage only its own customer's users and only with customer authorities, and whether PE should stop auto-assigning tenant groups to customer-owned edges. +- **Starting point.** The table below and the review leftovers list every known customer-level gap with the options discussed so far. + +| Branch | Issue | Review # | Notes | +|---|---|---|---| +| CE 4.2 | Every edge, including customer-assigned ones, gets all tenant admins with password hashes (`TenantAdminUsersEdgeEventFetcher`) | 8 | Option discussed: don't send tenant admin hashes to customer edges (breaks local login for tenant admins there) | +| PE 4.2 | `DefaultTbEdgeService` auto-assigns Tenant Administrators and Tenant Users groups to every new edge, customer-owned too; moving an edge to a customer keeps them. Customer edges get tenant admin hashes by default | 8 | Configurable in PE (groups can be unassigned). Option discussed: stop auto-assigning tenant groups to customer-owned edges | +| CE 4.3 | Customer edge can create `TENANT_ADMIN` users, and edit, delete or set passwords of tenant admins and other customers' users; customer id taken from the msg (`setCustomerId`) | 2, 4, 5, 6 | Needs "edge customer" checks on create/update/delete/credentials | +| PE 4.3 / CE 4.4 | Customer edge can move users between customers: `changeOwnerIfRequired` runs before `userValidator.validate` | A | Cross-tenant part fixed | +| PE 4.3 / CE 4.4 | Customer edge can add a user to any group of its tenant (e.g. Tenant Administrators); `addEntityToEntityGroup` doesn't check the owner | B | Cross-tenant part fixed; group membership carries permissions in PE | + +### Leftovers from the review (after all PRs) + +Everything from the review that is not fully closed on our branches, by review finding: + +| Review # | What is left | Why / decision | Status | +|---|---|---|---| +| 2 | A customer edge can set a tenant admin's (or another customer's user's) password | Customer-level isolation | Deferred: EDGE-122 | +| 4 | A customer edge can delete tenant admins and other customers' users; on 4.4 / PE 4.3 a delete with an entity group id removes the user from a group of its tenant | Customer-level isolation | Deferred: EDGE-122 | +| 5 | A customer edge can edit tenant admins, including email, then reset their password | Customer-level isolation | Deferred: EDGE-122 | +| 6 | Customer id taken from the msg (`setCustomerId`); a customer edge can create `TENANT_ADMIN` users or users under any customer of the tenant | Customer-level isolation | Deferred: EDGE-122 | +| 7 | TRACE logs still print whole msgs | Developer-only, off in production | Left as is | +| 7 | Non-credential entity JSON (device, asset, dashboard, entity view, relation, rule chain, profiles, calculated field, scheduler event, report template) still in processor ERROR/WARN logs and in "cannot be converted" exception texts, which reach the edge failure notification | No credentials or secrets; same tenant's data | Left as is | +| 8 | Password hashes are still sent to edges (local login needs them); every CE edge gets all tenant admins, PE auto-assigns tenant groups to customer-owned edges | Hash itself is by design; the customer-edge part is customer-level isolation | Deferred: EDGE-122 | +| 8 | Password history (`additionalInfo.userPasswordHistory`) sent to edges | Edge already has the current hash; edge uses the history for its reuse check | Won't fix | +| A | On 4.4 / PE 4.3 `changeOwnerIfRequired` runs before `userValidator.validate`, so a customer edge can move a user to another customer of its tenant | Cross-tenant owners are rejected; customer-level isolation | Deferred: EDGE-122 | +| B | On 4.4 / PE 4.3 a customer edge can add a user to any group of its tenant (e.g. Tenant Administrators); group membership carries permissions in PE | Cross-tenant groups are rejected; customer-level isolation | Deferred: EDGE-122 | +| — | If the edge builds its credentials uplink with the shared `constructUserCredentialsUpdatedMsg`, it no longer sends the activation token, so a user created on the edge and not yet activated shows as activated on the cloud | Display only; needs a check in the edge repo | Open question | +| Other | Upstream `lts-4.4` has 3,444 Java files under BUSL-1.1 (`upstream` = public `thingsboard/thingsboard`), `lts-4.3` has none | Not an edge issue; for product/legal to confirm | Not ours | + +--- + +## PaaS +Same code as PE; follows the PE merges.