From 715430700c72626d1a6d7936212444e8b0e9c903 Mon Sep 17 00:00:00 2001 From: Nikita Mazurenko Date: Wed, 8 Jul 2026 12:59:21 +0300 Subject: [PATCH 001/159] Sync persistent RPC (v2) status Edge->Cloud and delete in both directions --- .../server/controller/RpcV2Controller.java | 36 +++++++++++++++++- .../service/edge/EdgeContextComponent.java | 4 ++ .../service/edge/EdgeMsgConstructorUtils.java | 12 ++++-- .../processor/device/DeviceEdgeProcessor.java | 37 ++++++++++++++++++- .../server/service/rpc/TbRpcService.java | 4 ++ .../server/common/data/rpc/RpcStatus.java | 6 +-- .../server/common/data/rpc/RpcStatusTest.java | 10 ++--- common/edge-api/src/main/proto/edge.proto | 1 + 8 files changed, 96 insertions(+), 14 deletions(-) diff --git a/application/src/main/java/org/thingsboard/server/controller/RpcV2Controller.java b/application/src/main/java/org/thingsboard/server/controller/RpcV2Controller.java index 412e775327..3f7041f863 100644 --- a/application/src/main/java/org/thingsboard/server/controller/RpcV2Controller.java +++ b/application/src/main/java/org/thingsboard/server/controller/RpcV2Controller.java @@ -15,6 +15,7 @@ */ package org.thingsboard.server.controller; +import com.fasterxml.jackson.databind.node.ObjectNode; import com.google.common.util.concurrent.FutureCallback; import io.swagger.v3.oas.annotations.Parameter; import io.swagger.v3.oas.annotations.media.Schema; @@ -24,6 +25,7 @@ import jakarta.annotation.Nullable; import lombok.extern.slf4j.Slf4j; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; +import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; @@ -35,8 +37,13 @@ import org.springframework.web.bind.annotation.RestController; import org.springframework.web.context.request.async.DeferredResult; import org.springframework.web.server.ResponseStatusException; import org.thingsboard.common.util.JacksonUtil; +import org.thingsboard.server.common.data.EdgeUtils; +import org.thingsboard.server.common.data.edge.EdgeEvent; +import org.thingsboard.server.common.data.edge.EdgeEventActionType; +import org.thingsboard.server.common.data.edge.EdgeEventType; import org.thingsboard.server.common.data.exception.ThingsboardException; 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.msg.TbMsgType; @@ -46,12 +53,15 @@ import org.thingsboard.server.common.data.rpc.Rpc; import org.thingsboard.server.common.data.rpc.RpcStatus; import org.thingsboard.server.common.msg.TbMsg; import org.thingsboard.server.common.msg.TbMsgMetaData; +import org.thingsboard.server.common.msg.edge.EdgeHighPriorityMsg; import org.thingsboard.server.common.msg.rpc.RemoveRpcActorMsg; +import org.thingsboard.server.service.rpc.TbRpcService; import org.thingsboard.server.config.annotations.ApiOperation; import org.thingsboard.server.exception.ToErrorResponseEntity; import org.thingsboard.server.queue.util.TbCoreComponent; import org.thingsboard.server.service.security.permission.Operation; +import java.util.List; import java.util.UUID; import static org.thingsboard.server.controller.ControllerConstants.DEVICE_ID; @@ -74,6 +84,9 @@ import static org.thingsboard.server.controller.ControllerConstants.TENANT_OR_CU @Slf4j public class RpcV2Controller extends AbstractRpcController { + @Autowired + private TbRpcService tbRpcService; + private static final String RPC_REQUEST_DESCRIPTION = "Sends the one-way remote-procedure call (RPC) request to device. " + "The RPC call is A JSON that contains the method name ('method'), parameters ('params') and multiple optional fields. " + "See example below. We will review the properties of the RPC call one-by-one below. " + @@ -230,15 +243,19 @@ public class RpcV2Controller extends AbstractRpcController { Rpc rpc = checkRpcId(rpcId, Operation.DELETE); if (rpc != null) { - if (rpc.getStatus().isPushDeleteNotificationToCore()) { + if (rpc.getStatus().isIntermediate()) { RemoveRpcActorMsg removeMsg = new RemoveRpcActorMsg(getTenantId(), rpc.getDeviceId(), rpc.getUuidId()); log.trace("[{}] Forwarding msg {} to queue actor!", rpc.getDeviceId(), rpc); tbClusterService.pushMsgToCore(removeMsg, null); } - rpcService.deleteRpc(getTenantId(), rpcId); + tbRpcService.deleteRpc(getTenantId(), rpcId); rpc.setStatus(RpcStatus.DELETED); + // RPC v2 (persistent) delete/abort propagation Cloud -> Edge for ANY status + // (the actor RemoveRpcActorMsg above only covers non-terminal RPCs). + pushRpcDeleteToEdges(rpc); + TbMsg msg = TbMsg.newMsg() .type(TbMsgType.RPC_DELETED) .originator(rpc.getDeviceId()) @@ -248,4 +265,19 @@ public class RpcV2Controller extends AbstractRpcController { tbClusterService.pushMsgToRuleEngine(getTenantId(), rpc.getDeviceId(), msg, null); } } + + private void pushRpcDeleteToEdges(Rpc rpc) throws ThingsboardException { + List relatedEdgeIds = edgeService.findAllRelatedEdgeIds(getTenantId(), rpc.getDeviceId()); + if (relatedEdgeIds == null || relatedEdgeIds.isEmpty()) { + return; + } + ObjectNode body = JacksonUtil.newObjectNode(); + body.put("requestUUID", rpc.getId().getId().toString()); + body.put("rpcStatus", RpcStatus.DELETED.name()); + for (EdgeId edgeId : relatedEdgeIds) { + EdgeEvent edgeEvent = EdgeUtils.constructEdgeEvent(getTenantId(), edgeId, EdgeEventType.DEVICE, + EdgeEventActionType.RPC_CALL, rpc.getDeviceId(), body); + tbClusterService.onEdgeHighPriorityMsg(new EdgeHighPriorityMsg(getTenantId(), edgeEvent)); + } + } } diff --git a/application/src/main/java/org/thingsboard/server/service/edge/EdgeContextComponent.java b/application/src/main/java/org/thingsboard/server/service/edge/EdgeContextComponent.java index fbb3591bb5..e7885081b1 100644 --- a/application/src/main/java/org/thingsboard/server/service/edge/EdgeContextComponent.java +++ b/application/src/main/java/org/thingsboard/server/service/edge/EdgeContextComponent.java @@ -58,6 +58,7 @@ import org.thingsboard.server.dao.widget.WidgetsBundleService; import org.thingsboard.server.queue.util.TbCoreComponent; import org.thingsboard.server.service.edge.rpc.EdgeEventStorageSettings; import org.thingsboard.server.service.edge.rpc.EdgeRpcService; +import org.thingsboard.server.service.rpc.TbRpcService; import org.thingsboard.server.service.edge.rpc.processor.EdgeProcessor; import org.thingsboard.server.service.edge.rpc.processor.alarm.AlarmProcessor; import org.thingsboard.server.service.edge.rpc.processor.alarm.comment.AlarmCommentProcessor; @@ -134,6 +135,9 @@ public class EdgeContextComponent { @Autowired private DeviceService deviceService; + @Autowired + private TbRpcService tbRpcService; + @Autowired private DomainService domainService; diff --git a/application/src/main/java/org/thingsboard/server/service/edge/EdgeMsgConstructorUtils.java b/application/src/main/java/org/thingsboard/server/service/edge/EdgeMsgConstructorUtils.java index 2417931e0b..0778bd4401 100644 --- a/application/src/main/java/org/thingsboard/server/service/edge/EdgeMsgConstructorUtils.java +++ b/application/src/main/java/org/thingsboard/server/service/edge/EdgeMsgConstructorUtils.java @@ -272,20 +272,23 @@ public class EdgeMsgConstructorUtils { responseBuilder.setResponse(body.get("response").asText()); } builder.setResponseMsg(responseBuilder.build()); - } else { + } else if (body.has("method")) { RpcRequestMsg.Builder requestBuilder = RpcRequestMsg.newBuilder(); requestBuilder.setMethod(body.get("method").asText()); requestBuilder.setParams(body.get("params").asText()); builder.setRequestMsg(requestBuilder.build()); } + // else: status-only message (rpcStatus set in constructDeviceRpcMsg) carries neither request nor response body return builder.build(); } private static DeviceRpcCallMsg.Builder constructDeviceRpcMsg(UUID deviceId, JsonNode body) { DeviceRpcCallMsg.Builder builder = DeviceRpcCallMsg.newBuilder() .setDeviceIdMSB(deviceId.getMostSignificantBits()) - .setDeviceIdLSB(deviceId.getLeastSignificantBits()) - .setRequestId(body.get("requestId").asInt()); + .setDeviceIdLSB(deviceId.getLeastSignificantBits()); + if (body.get("requestId") != null) { + builder.setRequestId(body.get("requestId").asInt()); + } if (body.get("oneway") != null) { builder.setOneway(body.get("oneway").asBoolean()); } @@ -312,6 +315,9 @@ public class EdgeMsgConstructorUtils { if (body.get("sessionId") != null) { builder.setSessionId(body.get("sessionId").asText()); } + if (body.get("rpcStatus") != null) { + builder.setRpcStatus(body.get("rpcStatus").asText()); + } return builder; } 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 dab3efd911..ed8e948f5a 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 @@ -22,6 +22,7 @@ import com.google.common.util.concurrent.SettableFuture; import lombok.extern.slf4j.Slf4j; import org.springframework.data.util.Pair; import org.springframework.stereotype.Component; +import com.fasterxml.jackson.databind.JsonNode; import org.thingsboard.common.util.JacksonUtil; import org.thingsboard.server.common.data.DataConstants; import org.thingsboard.server.common.data.Device; @@ -37,7 +38,10 @@ import org.thingsboard.server.common.data.id.DeviceId; import org.thingsboard.server.common.data.id.EdgeId; import org.thingsboard.server.common.data.id.TenantId; import org.thingsboard.server.common.data.msg.TbMsgType; +import org.thingsboard.server.common.data.id.RpcId; +import org.thingsboard.server.common.data.rpc.Rpc; import org.thingsboard.server.common.data.rpc.RpcError; +import org.thingsboard.server.common.data.rpc.RpcStatus; import org.thingsboard.server.common.data.security.DeviceCredentials; import org.thingsboard.server.common.msg.TbMsg; import org.thingsboard.server.common.msg.TbMsgDataType; @@ -138,7 +142,10 @@ public class DeviceEdgeProcessor extends BaseDeviceProcessor implements DevicePr @Override public ListenableFuture processDeviceRpcCallFromEdge(TenantId tenantId, Edge edge, DeviceRpcCallMsg deviceRpcCallMsg) { log.trace("[{}] processDeviceRpcCallFromEdge [{}]", tenantId, deviceRpcCallMsg); - if (deviceRpcCallMsg.hasResponseMsg()) { + if (deviceRpcCallMsg.hasRpcStatus()) { + // RPC v2 (persistent) status update from the edge - update the cloud Rpc entity (same id == request UUID). + return processDeviceRpcStatusFromEdge(tenantId, deviceRpcCallMsg); + } else if (deviceRpcCallMsg.hasResponseMsg()) { return processDeviceRpcResponseFromEdge(tenantId, deviceRpcCallMsg); } else if (deviceRpcCallMsg.hasRequestMsg()) { return processDeviceRpcRequestFromEdge(tenantId, edge, deviceRpcCallMsg); @@ -146,6 +153,34 @@ public class DeviceEdgeProcessor extends BaseDeviceProcessor implements DevicePr return Futures.immediateFuture(null); } + private ListenableFuture processDeviceRpcStatusFromEdge(TenantId tenantId, DeviceRpcCallMsg deviceRpcCallMsg) { + RpcId rpcId = new RpcId(new UUID(deviceRpcCallMsg.getRequestUuidMSB(), deviceRpcCallMsg.getRequestUuidLSB())); + if (RpcStatus.DELETED.name().equals(deviceRpcCallMsg.getRpcStatus())) { + // RPC v2 (persistent) delete/abort propagation Edge -> Cloud: remove the cloud copy. + if (edgeCtx.getTbRpcService().findRpcById(tenantId, rpcId) != null) { + edgeCtx.getTbRpcService().deleteRpc(tenantId, rpcId); + } + return Futures.immediateFuture(null); + } + RpcStatus rpcStatus = RpcStatus.valueOf(deviceRpcCallMsg.getRpcStatus()); + Rpc existingRpc = edgeCtx.getTbRpcService().findRpcById(tenantId, rpcId); + if (existingRpc == null) { + return Futures.immediateFuture(null); + } + if (!existingRpc.getStatus().isIntermediate() && rpcStatus.isIntermediate()) { + // guard against out-of-order status uplinks regressing a terminal RPC (e.g. stale DELIVERED after SUCCESSFUL) + log.debug("[{}][{}] Ignoring stale RPC status [{}] - RPC is already terminal [{}]", + tenantId, rpcId, rpcStatus, existingRpc.getStatus()); + return Futures.immediateFuture(null); + } + JsonNode response = null; + if (deviceRpcCallMsg.hasResponseMsg() && !StringUtils.isEmpty(deviceRpcCallMsg.getResponseMsg().getResponse())) { + response = JacksonUtil.toJsonNode(deviceRpcCallMsg.getResponseMsg().getResponse()); + } + edgeCtx.getTbRpcService().save(tenantId, rpcId, rpcStatus, response); + return Futures.immediateFuture(null); + } + private ListenableFuture processDeviceRpcResponseFromEdge(TenantId tenantId, DeviceRpcCallMsg deviceRpcCallMsg) { SettableFuture futureToSet = SettableFuture.create(); UUID requestUuid = new UUID(deviceRpcCallMsg.getRequestUuidMSB(), deviceRpcCallMsg.getRequestUuidLSB()); diff --git a/application/src/main/java/org/thingsboard/server/service/rpc/TbRpcService.java b/application/src/main/java/org/thingsboard/server/service/rpc/TbRpcService.java index 912e8242c6..de7112b7d0 100644 --- a/application/src/main/java/org/thingsboard/server/service/rpc/TbRpcService.java +++ b/application/src/main/java/org/thingsboard/server/service/rpc/TbRpcService.java @@ -80,4 +80,8 @@ public class TbRpcService { return rpcService.findAllByDeviceIdAndStatus(tenantId, deviceId, rpcStatus, pageLink); } + public void deleteRpc(TenantId tenantId, RpcId rpcId) { + rpcService.deleteRpc(tenantId, rpcId); + } + } diff --git a/common/data/src/main/java/org/thingsboard/server/common/data/rpc/RpcStatus.java b/common/data/src/main/java/org/thingsboard/server/common/data/rpc/RpcStatus.java index b731fbe125..9e07943570 100644 --- a/common/data/src/main/java/org/thingsboard/server/common/data/rpc/RpcStatus.java +++ b/common/data/src/main/java/org/thingsboard/server/common/data/rpc/RpcStatus.java @@ -29,10 +29,10 @@ public enum RpcStatus { DELETED(false); @Getter - private final boolean pushDeleteNotificationToCore; + private final boolean intermediate; - RpcStatus(boolean pushDeleteNotificationToCore) { - this.pushDeleteNotificationToCore = pushDeleteNotificationToCore; + RpcStatus(boolean intermediate) { + this.intermediate = intermediate; } } diff --git a/common/data/src/test/java/org/thingsboard/server/common/data/rpc/RpcStatusTest.java b/common/data/src/test/java/org/thingsboard/server/common/data/rpc/RpcStatusTest.java index 0c0f5a810e..638b486ae2 100644 --- a/common/data/src/test/java/org/thingsboard/server/common/data/rpc/RpcStatusTest.java +++ b/common/data/src/test/java/org/thingsboard/server/common/data/rpc/RpcStatusTest.java @@ -26,20 +26,20 @@ import static org.thingsboard.server.common.data.rpc.RpcStatus.SENT; class RpcStatusTest { - private static final List pushDeleteNotificationToCoreStatuses = List.of( + private static final List intermediateStatuses = List.of( QUEUED, SENT, DELIVERED ); @Test - void isPushDeleteNotificationToCoreStatusTest() { + void isIntermediateStatusTest() { var rpcStatuses = RpcStatus.values(); for (var status : rpcStatuses) { - if (pushDeleteNotificationToCoreStatuses.contains(status)) { - assertThat(status.isPushDeleteNotificationToCore()).isTrue(); + if (intermediateStatuses.contains(status)) { + assertThat(status.isIntermediate()).isTrue(); } else { - assertThat(status.isPushDeleteNotificationToCore()).isFalse(); + assertThat(status.isIntermediate()).isFalse(); } } } diff --git a/common/edge-api/src/main/proto/edge.proto b/common/edge-api/src/main/proto/edge.proto index 520b4ac493..148940196e 100644 --- a/common/edge-api/src/main/proto/edge.proto +++ b/common/edge-api/src/main/proto/edge.proto @@ -390,6 +390,7 @@ message DeviceRpcCallMsg { optional string additionalInfo = 12; optional string serviceId = 13; optional string sessionId = 14; + optional string rpcStatus = 15; } message RpcRequestMsg { From dd369b28326d267c8edb58cac2a02b54d39eca48 Mon Sep 17 00:00:00 2001 From: Nikita Mazurenko Date: Wed, 8 Jul 2026 15:55:34 +0300 Subject: [PATCH 002/159] Move pushRpcDeleteToEdges from controller to service layer --- .../server/controller/RpcV2Controller.java | 27 --------------- .../processor/device/DeviceEdgeProcessor.java | 12 +++++-- .../server/service/rpc/TbRpcService.java | 34 +++++++++++++++++++ 3 files changed, 43 insertions(+), 30 deletions(-) diff --git a/application/src/main/java/org/thingsboard/server/controller/RpcV2Controller.java b/application/src/main/java/org/thingsboard/server/controller/RpcV2Controller.java index 3f7041f863..3e55895db1 100644 --- a/application/src/main/java/org/thingsboard/server/controller/RpcV2Controller.java +++ b/application/src/main/java/org/thingsboard/server/controller/RpcV2Controller.java @@ -15,7 +15,6 @@ */ package org.thingsboard.server.controller; -import com.fasterxml.jackson.databind.node.ObjectNode; import com.google.common.util.concurrent.FutureCallback; import io.swagger.v3.oas.annotations.Parameter; import io.swagger.v3.oas.annotations.media.Schema; @@ -37,13 +36,8 @@ import org.springframework.web.bind.annotation.RestController; import org.springframework.web.context.request.async.DeferredResult; import org.springframework.web.server.ResponseStatusException; import org.thingsboard.common.util.JacksonUtil; -import org.thingsboard.server.common.data.EdgeUtils; -import org.thingsboard.server.common.data.edge.EdgeEvent; -import org.thingsboard.server.common.data.edge.EdgeEventActionType; -import org.thingsboard.server.common.data.edge.EdgeEventType; import org.thingsboard.server.common.data.exception.ThingsboardException; 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.msg.TbMsgType; @@ -53,7 +47,6 @@ import org.thingsboard.server.common.data.rpc.Rpc; import org.thingsboard.server.common.data.rpc.RpcStatus; import org.thingsboard.server.common.msg.TbMsg; import org.thingsboard.server.common.msg.TbMsgMetaData; -import org.thingsboard.server.common.msg.edge.EdgeHighPriorityMsg; import org.thingsboard.server.common.msg.rpc.RemoveRpcActorMsg; import org.thingsboard.server.service.rpc.TbRpcService; import org.thingsboard.server.config.annotations.ApiOperation; @@ -61,7 +54,6 @@ import org.thingsboard.server.exception.ToErrorResponseEntity; import org.thingsboard.server.queue.util.TbCoreComponent; import org.thingsboard.server.service.security.permission.Operation; -import java.util.List; import java.util.UUID; import static org.thingsboard.server.controller.ControllerConstants.DEVICE_ID; @@ -252,10 +244,6 @@ public class RpcV2Controller extends AbstractRpcController { tbRpcService.deleteRpc(getTenantId(), rpcId); rpc.setStatus(RpcStatus.DELETED); - // RPC v2 (persistent) delete/abort propagation Cloud -> Edge for ANY status - // (the actor RemoveRpcActorMsg above only covers non-terminal RPCs). - pushRpcDeleteToEdges(rpc); - TbMsg msg = TbMsg.newMsg() .type(TbMsgType.RPC_DELETED) .originator(rpc.getDeviceId()) @@ -265,19 +253,4 @@ public class RpcV2Controller extends AbstractRpcController { tbClusterService.pushMsgToRuleEngine(getTenantId(), rpc.getDeviceId(), msg, null); } } - - private void pushRpcDeleteToEdges(Rpc rpc) throws ThingsboardException { - List relatedEdgeIds = edgeService.findAllRelatedEdgeIds(getTenantId(), rpc.getDeviceId()); - if (relatedEdgeIds == null || relatedEdgeIds.isEmpty()) { - return; - } - ObjectNode body = JacksonUtil.newObjectNode(); - body.put("requestUUID", rpc.getId().getId().toString()); - body.put("rpcStatus", RpcStatus.DELETED.name()); - for (EdgeId edgeId : relatedEdgeIds) { - EdgeEvent edgeEvent = EdgeUtils.constructEdgeEvent(getTenantId(), edgeId, EdgeEventType.DEVICE, - EdgeEventActionType.RPC_CALL, rpc.getDeviceId(), body); - tbClusterService.onEdgeHighPriorityMsg(new EdgeHighPriorityMsg(getTenantId(), edgeEvent)); - } - } } 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 ed8e948f5a..d9bb0fe310 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 @@ -144,7 +144,7 @@ public class DeviceEdgeProcessor extends BaseDeviceProcessor implements DevicePr log.trace("[{}] processDeviceRpcCallFromEdge [{}]", tenantId, deviceRpcCallMsg); if (deviceRpcCallMsg.hasRpcStatus()) { // RPC v2 (persistent) status update from the edge - update the cloud Rpc entity (same id == request UUID). - return processDeviceRpcStatusFromEdge(tenantId, deviceRpcCallMsg); + return processDeviceRpcStatusFromEdge(tenantId, edge, deviceRpcCallMsg); } else if (deviceRpcCallMsg.hasResponseMsg()) { return processDeviceRpcResponseFromEdge(tenantId, deviceRpcCallMsg); } else if (deviceRpcCallMsg.hasRequestMsg()) { @@ -153,12 +153,18 @@ public class DeviceEdgeProcessor extends BaseDeviceProcessor implements DevicePr return Futures.immediateFuture(null); } - private ListenableFuture processDeviceRpcStatusFromEdge(TenantId tenantId, DeviceRpcCallMsg deviceRpcCallMsg) { + private ListenableFuture processDeviceRpcStatusFromEdge(TenantId tenantId, Edge edge, DeviceRpcCallMsg deviceRpcCallMsg) { RpcId rpcId = new RpcId(new UUID(deviceRpcCallMsg.getRequestUuidMSB(), deviceRpcCallMsg.getRequestUuidLSB())); if (RpcStatus.DELETED.name().equals(deviceRpcCallMsg.getRpcStatus())) { // RPC v2 (persistent) delete/abort propagation Edge -> Cloud: remove the cloud copy. + // Mark the edge-sync context so TbRpcService.deleteRpc does not echo the delete back to edges. if (edgeCtx.getTbRpcService().findRpcById(tenantId, rpcId) != null) { - edgeCtx.getTbRpcService().deleteRpc(tenantId, rpcId); + try { + edgeSynchronizationManager.getEdgeId().set(edge.getId()); + edgeCtx.getTbRpcService().deleteRpc(tenantId, rpcId); + } finally { + edgeSynchronizationManager.getEdgeId().remove(); + } } return Futures.immediateFuture(null); } diff --git a/application/src/main/java/org/thingsboard/server/service/rpc/TbRpcService.java b/application/src/main/java/org/thingsboard/server/service/rpc/TbRpcService.java index de7112b7d0..7489151d11 100644 --- a/application/src/main/java/org/thingsboard/server/service/rpc/TbRpcService.java +++ b/application/src/main/java/org/thingsboard/server/service/rpc/TbRpcService.java @@ -16,12 +16,18 @@ package org.thingsboard.server.service.rpc; import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.node.ObjectNode; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Service; import org.thingsboard.common.util.JacksonUtil; import org.thingsboard.server.cluster.TbClusterService; +import org.thingsboard.server.common.data.EdgeUtils; +import org.thingsboard.server.common.data.edge.EdgeEvent; +import org.thingsboard.server.common.data.edge.EdgeEventActionType; +import org.thingsboard.server.common.data.edge.EdgeEventType; 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.msg.TbMsgType; @@ -31,9 +37,14 @@ import org.thingsboard.server.common.data.rpc.Rpc; import org.thingsboard.server.common.data.rpc.RpcStatus; import org.thingsboard.server.common.msg.TbMsg; import org.thingsboard.server.common.msg.TbMsgMetaData; +import org.thingsboard.server.common.msg.edge.EdgeHighPriorityMsg; +import org.thingsboard.server.dao.edge.EdgeService; +import org.thingsboard.server.dao.edge.EdgeSynchronizationManager; import org.thingsboard.server.dao.rpc.RpcService; import org.thingsboard.server.queue.util.TbCoreComponent; +import java.util.List; + @TbCoreComponent @Service @RequiredArgsConstructor @@ -41,6 +52,8 @@ import org.thingsboard.server.queue.util.TbCoreComponent; public class TbRpcService { private final RpcService rpcService; private final TbClusterService tbClusterService; + private final EdgeService edgeService; + private final EdgeSynchronizationManager edgeSynchronizationManager; public Rpc save(TenantId tenantId, Rpc rpc) { Rpc saved = rpcService.save(rpc); @@ -81,7 +94,28 @@ public class TbRpcService { } public void deleteRpc(TenantId tenantId, RpcId rpcId) { + Rpc rpc = rpcService.findById(tenantId, rpcId); rpcService.deleteRpc(tenantId, rpcId); + // RPC v2 (persistent) delete/abort propagation Cloud -> Edge for ANY status. + // Skipped when the delete originated from an edge (edge-sync context) so it is not echoed back. + if (rpc != null && edgeSynchronizationManager.getEdgeId().get() == null) { + pushRpcDeleteToEdges(tenantId, rpc); + } + } + + private void pushRpcDeleteToEdges(TenantId tenantId, Rpc rpc) { + List relatedEdgeIds = edgeService.findAllRelatedEdgeIds(tenantId, rpc.getDeviceId()); + if (relatedEdgeIds == null || relatedEdgeIds.isEmpty()) { + return; + } + ObjectNode body = JacksonUtil.newObjectNode(); + body.put("requestUUID", rpc.getId().getId().toString()); + body.put("rpcStatus", RpcStatus.DELETED.name()); + for (EdgeId edgeId : relatedEdgeIds) { + EdgeEvent edgeEvent = EdgeUtils.constructEdgeEvent(tenantId, edgeId, EdgeEventType.DEVICE, + EdgeEventActionType.RPC_CALL, rpc.getDeviceId(), body); + tbClusterService.onEdgeHighPriorityMsg(new EdgeHighPriorityMsg(tenantId, edgeEvent)); + } } } From 9f06464c803ff941d8788eb5ec1b6e717273a312 Mon Sep 17 00:00:00 2001 From: Oleksandra Matviienko Date: Mon, 13 Jul 2026 23:19:16 +0200 Subject: [PATCH 003/159] Update tbel to 1.2.11 and add java.util.Formatter sandbox test --- .../service/script/TbelInvokeServiceTest.java | 14 ++++++++++++++ pom.xml | 2 +- 2 files changed, 15 insertions(+), 1 deletion(-) diff --git a/application/src/test/java/org/thingsboard/server/service/script/TbelInvokeServiceTest.java b/application/src/test/java/org/thingsboard/server/service/script/TbelInvokeServiceTest.java index 8618e515c8..7a8d3f68a6 100644 --- a/application/src/test/java/org/thingsboard/server/service/script/TbelInvokeServiceTest.java +++ b/application/src/test/java/org/thingsboard/server/service/script/TbelInvokeServiceTest.java @@ -301,6 +301,20 @@ class TbelInvokeServiceTest extends AbstractTbelInvokeTest { }); } + @Test + void givenForbiddenFormatter_whenInvoking_thenThrowsRuntimeError() throws ExecutionException, InterruptedException { + UUID scriptId = evalScript("new java.util.Formatter(\"/tmp/test.txt\")"); + assertThatThrownBy(() -> invokeScript(scriptId, "{\"temperature\":25}")) + .isInstanceOf(ExecutionException.class) + .cause() + .isInstanceOf(TbScriptException.class) + .asInstanceOf(type(TbScriptException.class)) + .satisfies(ex -> { + assertThat(ex.getErrorCode()).isEqualTo(TbScriptException.ErrorCode.RUNTIME); + assertThat(ex.getCause().getMessage()).contains("could not resolve class: java.util.Formatter"); + }); + } + private void assertThatScriptIsBlocked(UUID scriptId) { assertThatThrownBy(() -> { invokeScriptResultString(scriptId, "{}"); diff --git a/pom.xml b/pom.xml index 7d42f9f1c7..87280de7e1 100755 --- a/pom.xml +++ b/pom.xml @@ -94,7 +94,7 @@ 3.9.5 3.25.5 1.76.0 - 1.2.10 + 1.2.11 1.18.46 1.2.5 1.2.5 From 43851cd3f0236ebf9603ee6f2b297b59c471e98f Mon Sep 17 00:00:00 2001 From: Nikita Mazurenko Date: Fri, 24 Jul 2026 17:08:27 +0300 Subject: [PATCH 004/159] Fix Nashorn Global PropertyMap leak on JS script release --- .../script/NashornJsInvokeServiceTest.java | 85 +++++++++++++++++++ .../script/api/js/NashornJsInvokeService.java | 16 +++- 2 files changed, 97 insertions(+), 4 deletions(-) diff --git a/application/src/test/java/org/thingsboard/server/service/script/NashornJsInvokeServiceTest.java b/application/src/test/java/org/thingsboard/server/service/script/NashornJsInvokeServiceTest.java index 01a5f1b6fc..c76eac8c61 100644 --- a/application/src/test/java/org/thingsboard/server/service/script/NashornJsInvokeServiceTest.java +++ b/application/src/test/java/org/thingsboard/server/service/script/NashornJsInvokeServiceTest.java @@ -17,13 +17,17 @@ package org.thingsboard.server.service.script; import com.google.common.util.concurrent.Futures; import com.google.common.util.concurrent.ListenableFuture; +import delight.nashornsandbox.NashornSandbox; +import delight.nashornsandbox.NashornSandboxes; import lombok.extern.slf4j.Slf4j; import org.junit.Assert; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.test.context.TestPropertySource; +import org.springframework.test.util.ReflectionTestUtils; import org.thingsboard.common.util.TbStopWatch; +import org.thingsboard.script.api.RuleNodeScriptFactory; import org.thingsboard.script.api.ScriptType; import org.thingsboard.script.api.TbScriptException; import org.thingsboard.script.api.js.NashornJsInvokeService; @@ -31,6 +35,7 @@ import org.thingsboard.server.common.data.id.TenantId; import org.thingsboard.server.controller.AbstractControllerTest; import org.thingsboard.server.dao.service.DaoSqlTest; +import javax.script.ScriptEngine; import javax.script.ScriptException; import java.util.ArrayList; import java.util.List; @@ -222,6 +227,86 @@ class NashornJsInvokeServiceTest extends AbstractControllerTest { }); } + @Test + void whenScriptIsReleased_thenGlobalPropertyIsRemoved() throws Exception { + UUID scriptId = evalScript("return msg;"); + String functionName = "invokeInternal_" + scriptId.toString().replace('-', '_'); + assertThat(evalInEngine("this.hasOwnProperty('" + functionName + "')")).hasToString("true"); + + invokeService.release(scriptId).get(); + + // the property must be deleted, not just set to undefined: an abandoned binding keeps + assertThat(evalInEngine("this.hasOwnProperty('" + functionName + "')")).hasToString("false"); + } + + @Test + void givenIifeWrappedEval_whenInvoking_thenResultIsUnchanged() throws Exception { + UUID scriptId = evalScript("return {doubled: msg.temperature * 2};"); + assertThat(invokeScript(scriptId, "{\"temperature\":21}")).contains("\"doubled\":42"); + } + + @Test + void givenIifeWrappedEval_thenImplicitGlobalStateIsStillSharedBetweenScripts() throws Exception { + UUID writer = evalScript("compatSharedState = 777; return msg;"); + UUID reader = evalScript("return {seen: (typeof compatSharedState === 'undefined') ? null : compatSharedState};"); + invokeScript(writer, "{}"); + assertThat(invokeScript(reader, "{}")).contains("\"seen\":777"); + } + + @Test + void givenIifeWrappedEval_thenCompilationErrorUnchanged() { + String badScript = "var a = 1;\nvar b = 2;\nreturn msg.temperature?.value;"; + + String legacyScript = RuleNodeScriptFactory.generateRuleNodeScript("invokeInternal_legacy", badScript, + "msg", "metadata", "msgType"); + NashornSandbox legacySandbox = NashornSandboxes.create(); + legacySandbox.allowNoBraces(false); + legacySandbox.allowLoadFunctions(true); + legacySandbox.setMaxPreparedStatements(30); + int legacyErrorLine = -1; + try { + legacySandbox.eval(legacyScript); + } catch (ScriptException e) { + legacyErrorLine = e.getLineNumber(); + } + assertThat(legacyErrorLine).isGreaterThan(0); + final int expectedLine = legacyErrorLine; + + assertThatThrownBy(() -> evalScript(badScript)) + .isInstanceOf(ExecutionException.class) + .cause() + .isInstanceOf(TbScriptException.class) + .asInstanceOf(type(TbScriptException.class)) + .satisfies(ex -> { + assertThat(ex.getErrorCode()).isEqualTo(TbScriptException.ErrorCode.COMPILATION); + assertThat(ex.getBody()).contains(badScript); + assertThat(ex.getCause()).isInstanceOf(ScriptException.class); + // The IIFE wrapper shifts sandbox-reported line numbers by a constant +2 + // (the beautifier splits the wrapper prefix onto its own lines). Reported + // lines never matched the user's source anyway (the sandbox instrumentation + // already offsets them), so only the small constant shift is tolerated here. + assertThat(((ScriptException) ex.getCause()).getLineNumber()).isBetween(expectedLine, expectedLine + 2); + }); + } + + @Test + void whenInvokingAfterRelease_thenFailsWithNoCompiledScriptFound() throws Exception { + UUID scriptId = evalScript("return msg;"); + invokeScript(scriptId, "{}"); + invokeService.release(scriptId).get(); + assertThatThrownBy(() -> invokeScript(scriptId, "{}")) + .isInstanceOf(ExecutionException.class) + .hasMessageContaining("No compiled script found"); + } + + private Object evalInEngine(String expression) throws Exception { + Object sandbox = ReflectionTestUtils.getField(invokeService, "sandbox"); + if (sandbox != null) { + return ((NashornSandbox) sandbox).eval(expression); + } + return ((ScriptEngine) ReflectionTestUtils.getField(invokeService, "engine")).eval(expression); + } + private void assertThatScriptIsBlocked(UUID scriptId) { assertThatThrownBy(() -> { invokeScript(scriptId, "{}"); diff --git a/common/script/script-api/src/main/java/org/thingsboard/script/api/js/NashornJsInvokeService.java b/common/script/script-api/src/main/java/org/thingsboard/script/api/js/NashornJsInvokeService.java index 1ef2eeb6da..bb95c60481 100644 --- a/common/script/script-api/src/main/java/org/thingsboard/script/api/js/NashornJsInvokeService.java +++ b/common/script/script-api/src/main/java/org/thingsboard/script/api/js/NashornJsInvokeService.java @@ -140,14 +140,21 @@ public class NashornJsInvokeService extends AbstractJsInvokeService { @Override protected ListenableFuture doEval(UUID scriptId, JsScriptInfo scriptInfo, String jsScript) { + // A top-level function declaration creates a non-configurable property on the Nashorn Global + // that can never be deleted, so every eval/release cycle would grow the Global's PropertyMap + // shape history forever. Declaring the function inside an IIFE and assigning it to a global + // property keeps the property configurable, allowing doRelease() to actually delete it. + // The prefix stays on the first line so that script line numbers in errors are unchanged. + String wrappedScript = "this['" + scriptInfo.getFunctionName() + "'] = (function() { " + jsScript + + "\nreturn " + scriptInfo.getFunctionName() + ";\n})();"; return jsExecutor.submit(() -> { try { evalLock.lock(); try { if (useJsSandbox) { - sandbox.eval(jsScript); + sandbox.eval(wrappedScript); } else { - engine.eval(jsScript); + engine.eval(wrappedScript); } } finally { evalLock.unlock(); @@ -182,10 +189,11 @@ public class NashornJsInvokeService extends AbstractJsInvokeService { } protected void doRelease(UUID scriptId, JsScriptInfo scriptInfo) throws ScriptException { + String deleteScript = "delete this['" + scriptInfo.getFunctionName() + "'];"; if (useJsSandbox) { - sandbox.eval(scriptInfo.getFunctionName() + " = undefined;"); + sandbox.eval(deleteScript); } else { - engine.eval(scriptInfo.getFunctionName() + " = undefined;"); + engine.eval(deleteScript); } } From b67fc8dfb1ad1ca22dc076047f8ee37743b894f2 Mon Sep 17 00:00:00 2001 From: Nikita Mazurenko Date: Fri, 24 Jul 2026 17:08:39 +0300 Subject: [PATCH 005/159] Release EdgeGrpcClient channel on failed connect and guard send/disconnect race --- .../thingsboard/edge/rpc/EdgeGrpcClient.java | 146 +++++++++++------- 1 file changed, 92 insertions(+), 54 deletions(-) diff --git a/common/edge-api/src/main/java/org/thingsboard/edge/rpc/EdgeGrpcClient.java b/common/edge-api/src/main/java/org/thingsboard/edge/rpc/EdgeGrpcClient.java index 7e58a2cb9f..f96fe8b38f 100644 --- a/common/edge-api/src/main/java/org/thingsboard/edge/rpc/EdgeGrpcClient.java +++ b/common/edge-api/src/main/java/org/thingsboard/edge/rpc/EdgeGrpcClient.java @@ -86,7 +86,7 @@ public class EdgeGrpcClient implements EdgeRpcClient { private StreamObserver inputStream; - private static final ReentrantLock uplinkMsgLock = new ReentrantLock(); + private final ReentrantLock connectionLock = new ReentrantLock(); @Override public void connect(String edgeKey, @@ -127,19 +127,38 @@ public class EdgeGrpcClient implements EdgeRpcClient { .build()); } - channel = builder.build(); - EdgeRpcServiceGrpc.EdgeRpcServiceStub stub = EdgeRpcServiceGrpc.newStub(channel); - log.info("[{}] Sending a connect request to the TB!", edgeKey); - this.inputStream = stub.withCompression("gzip").handleMsgs(initOutputStream(edgeKey, onUplinkResponse, onEdgeUpdate, onDownlink, onError)); - this.inputStream.onNext(RequestMsg.newBuilder() - .setMsgType(RequestMsgType.CONNECT_RPC_MESSAGE) - .setConnectRequestMsg(ConnectRequestMsg.newBuilder() - .setEdgeRoutingKey(edgeKey) - .setEdgeSecret(edgeSecret) - .setEdgeVersion(getNewestEdgeVersion()) - .setMaxInboundMessageSize(maxInboundMessageSize) - .build()) - .build()); + connectionLock.lock(); + try { + channel = builder.build(); + EdgeRpcServiceGrpc.EdgeRpcServiceStub stub = EdgeRpcServiceGrpc.newStub(channel); + log.info("[{}] Sending a connect request to the TB!", edgeKey); + this.inputStream = stub.withCompression("gzip").handleMsgs(initOutputStream(edgeKey, channel, onUplinkResponse, onEdgeUpdate, onDownlink, onError)); + this.inputStream.onNext(RequestMsg.newBuilder() + .setMsgType(RequestMsgType.CONNECT_RPC_MESSAGE) + .setConnectRequestMsg(ConnectRequestMsg.newBuilder() + .setEdgeRoutingKey(edgeKey) + .setEdgeSecret(edgeSecret) + .setEdgeVersion(getNewestEdgeVersion()) + .setMaxInboundMessageSize(maxInboundMessageSize) + .build()) + .build()); + } catch (RuntimeException e) { + // Release the half-built channel, otherwise every failed reconnect attempt leaks + // its event loops and executors, and the next attempt may not recover at all. + log.error("[{}] Failed to establish the connection, shutting down the channel!", edgeKey, e); + if (channel != null) { + try { + channel.shutdownNow(); + } catch (Exception shutdownEx) { + log.error("[{}] Exception during shutdownNow of the failed channel", edgeKey, shutdownEx); + } + } + channel = null; + inputStream = null; + throw e; + } finally { + connectionLock.unlock(); + } } public static EdgeVersion getNewestEdgeVersion() { @@ -147,6 +166,7 @@ public class EdgeGrpcClient implements EdgeRpcClient { } private StreamObserver initOutputStream(String edgeKey, + ManagedChannel streamChannel, Consumer onUplinkResponse, Consumer onEdgeUpdate, Consumer onDownlink, @@ -166,7 +186,7 @@ public class EdgeGrpcClient implements EdgeRpcClient { } else { log.error("[{}] Failed to establish the connection! Code: {}. Error message: {}.", edgeKey, connectResponseMsg.getResponseCode(), connectResponseMsg.getErrorMsg()); try { - EdgeGrpcClient.this.disconnect(true); + EdgeGrpcClient.this.disconnect(true, streamChannel); } catch (InterruptedException e) { log.error("[{}] Got interruption during disconnect!", edgeKey, e); } @@ -188,7 +208,7 @@ public class EdgeGrpcClient implements EdgeRpcClient { public void onError(Throwable t) { log.warn("[{}] Stream was terminated due to error:", edgeKey, t); try { - EdgeGrpcClient.this.disconnect(true); + EdgeGrpcClient.this.disconnect(true, streamChannel); } catch (InterruptedException e) { log.error("[{}] Got interruption during disconnect!", edgeKey, e); } @@ -204,77 +224,95 @@ public class EdgeGrpcClient implements EdgeRpcClient { @Override public void disconnect(boolean onError) throws InterruptedException { - if (!onError) { - try { - if (inputStream != null) { - inputStream.onCompleted(); + disconnect(onError, null); + } + + private void disconnect(boolean onError, ManagedChannel expectedChannel) throws InterruptedException { + ManagedChannel channelToShutdown; + connectionLock.lock(); + try { + // A terminated stream reports its error asynchronously and may lose the race with a + // reconnect: ignore such stale callbacks instead of tearing down the fresh channel. + if (expectedChannel != null && channel != expectedChannel) { + log.info("The channel was already replaced by a reconnect. Skipping disconnect of the stale channel."); + return; + } + if (!onError) { + try { + if (inputStream != null) { + inputStream.onCompleted(); + } + } catch (Exception e) { + log.error("Exception during onCompleted", e); } - } catch (Exception e) { - log.error("Exception during onCompleted", e); } + // Clear the references under the lock so that no send can start against a stream + // whose channel is shutting down - such a write leaks the compressed ByteBuf. + inputStream = null; + channelToShutdown = channel; + channel = null; + } finally { + connectionLock.unlock(); } - if (channel != null) { - channel.shutdown(); + if (channelToShutdown != null) { + channelToShutdown.shutdown(); int attempt = 0; do { try { - channel.awaitTermination(timeoutSecs, TimeUnit.SECONDS); + channelToShutdown.awaitTermination(timeoutSecs, TimeUnit.SECONDS); } catch (Exception e) { log.error("Channel await termination was interrupted", e); } if (attempt > 5) { log.warn("We had reached maximum of termination attempts. Force closing channel"); try { - channel.shutdownNow(); + channelToShutdown.shutdownNow(); } catch (Exception e) { log.error("Exception during shutdownNow", e); } break; } attempt++; - } while (!channel.isTerminated()); + } while (!channelToShutdown.isTerminated()); } } @Override public void sendUplinkMsg(UplinkMsg msg) { - uplinkMsgLock.lock(); - try { - this.inputStream.onNext(RequestMsg.newBuilder() - .setMsgType(RequestMsgType.UPLINK_RPC_MESSAGE) - .setUplinkMsg(msg) - .build()); - } finally { - uplinkMsgLock.unlock(); - } + sendRequestMsg(RequestMsg.newBuilder() + .setMsgType(RequestMsgType.UPLINK_RPC_MESSAGE) + .setUplinkMsg(msg) + .build()); } @Override public void sendSyncRequestMsg(boolean fullSyncRequired) { - uplinkMsgLock.lock(); - try { - SyncRequestMsg syncRequestMsg = SyncRequestMsg.newBuilder() - .setFullSync(fullSyncRequired) - .build(); - this.inputStream.onNext(RequestMsg.newBuilder() - .setMsgType(RequestMsgType.SYNC_REQUEST_RPC_MESSAGE) - .setSyncRequestMsg(syncRequestMsg) - .build()); - } finally { - uplinkMsgLock.unlock(); - } + SyncRequestMsg syncRequestMsg = SyncRequestMsg.newBuilder() + .setFullSync(fullSyncRequired) + .build(); + sendRequestMsg(RequestMsg.newBuilder() + .setMsgType(RequestMsgType.SYNC_REQUEST_RPC_MESSAGE) + .setSyncRequestMsg(syncRequestMsg) + .build()); } @Override public void sendDownlinkResponseMsg(DownlinkResponseMsg downlinkResponseMsg) { - uplinkMsgLock.lock(); + sendRequestMsg(RequestMsg.newBuilder() + .setMsgType(RequestMsgType.UPLINK_RPC_MESSAGE) + .setDownlinkResponseMsg(downlinkResponseMsg) + .build()); + } + + private void sendRequestMsg(RequestMsg requestMsg) { + connectionLock.lock(); try { - this.inputStream.onNext(RequestMsg.newBuilder() - .setMsgType(RequestMsgType.UPLINK_RPC_MESSAGE) - .setDownlinkResponseMsg(downlinkResponseMsg) - .build()); + if (inputStream == null) { + throw new IllegalStateException("Edge is not connected to the cloud. The message is discarded!"); + } + inputStream.onNext(requestMsg); } finally { - uplinkMsgLock.unlock(); + connectionLock.unlock(); } } From 03df2a333ab0aad89f64d8ff397addcdf81e98e6 Mon Sep 17 00:00:00 2001 From: Nikita Mazurenko Date: Fri, 28 Aug 2026 12:08:27 +0300 Subject: [PATCH 006/159] Keep the edge event check alive when an edge reconnects during session teardown --- .../service/edge/rpc/EdgeGrpcService.java | 192 +++++++++++------- 1 file changed, 115 insertions(+), 77 deletions(-) diff --git a/application/src/main/java/org/thingsboard/server/service/edge/rpc/EdgeGrpcService.java b/application/src/main/java/org/thingsboard/server/service/edge/rpc/EdgeGrpcService.java index e1211c53a7..4de478fe34 100644 --- a/application/src/main/java/org/thingsboard/server/service/edge/rpc/EdgeGrpcService.java +++ b/application/src/main/java/org/thingsboard/server/service/edge/rpc/EdgeGrpcService.java @@ -83,10 +83,11 @@ import java.util.concurrent.ConcurrentMap; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicReference; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; import java.util.function.Consumer; -import java.util.function.Function; +import java.util.function.Predicate; import static org.thingsboard.server.service.state.DefaultDeviceStateService.ACTIVITY_STATE; import static org.thingsboard.server.service.state.DefaultDeviceStateService.LAST_CONNECT_TIME; @@ -310,13 +311,10 @@ public class EdgeGrpcService extends EdgeRpcServiceGrpc.EdgeRpcServiceImplBase i @Override public void deleteEdge(TenantId tenantId, EdgeId edgeId) { - EdgeGrpcSession session = sessions.get(edgeId); - if (session != null && session.isConnected()) { + EdgeGrpcSession toRemove = detachSession(edgeId, EdgeGrpcSession::isConnected); + if (toRemove != null) { log.info("[{}] Closing and removing session for edge [{}]", tenantId, edgeId); - destroySession(session); - session.cleanUp(); - sessions.remove(edgeId); - sessionsById.remove(session.getSessionId()); + sessionsById.remove(toRemove.getSessionId()); final Lock newEventLock = sessionNewEventsLocks.computeIfAbsent(edgeId, id -> new ReentrantLock()); newEventLock.lock(); try { @@ -324,7 +322,9 @@ public class EdgeGrpcService extends EdgeRpcServiceGrpc.EdgeRpcServiceImplBase i } finally { newEventLock.unlock(); } - cancelScheduleEdgeEventsCheck(edgeId); + // destroy is slow (stops the kafka edge event consumer), keep it off the atomic path + destroySession(toRemove); + toRemove.cleanUp(); } } @@ -365,16 +365,12 @@ public class EdgeGrpcService extends EdgeRpcServiceGrpc.EdgeRpcServiceImplBase i Edge edge = edgeGrpcSession.getEdge(); TenantId tenantId = edge.getTenantId(); log.info("[{}][{}] edge [{}] connected successfully.", tenantId, edgeGrpcSession.getSessionId(), edgeId); - if (sessions.containsKey(edgeId)) { - EdgeGrpcSession existing = sessions.get(edgeId); - if (existing != null) { - log.info("[{}][{}] Replacing existing session [{}] for edge [{}]", tenantId, edgeGrpcSession.getSessionId(), existing.getSessionId(), edgeId); - destroySession(existing); - sessionsById.remove(existing.getSessionId()); - } - } - sessions.put(edgeId, edgeGrpcSession); + EdgeGrpcSession replaced = attachSession(edgeId, edgeGrpcSession); sessionsById.put(edgeGrpcSession.getSessionId(), edgeGrpcSession); + if (replaced != null) { + log.info("[{}][{}] Replacing existing session [{}] for edge [{}]", tenantId, edgeGrpcSession.getSessionId(), replaced.getSessionId(), edgeId); + sessionsById.remove(replaced.getSessionId()); + } final Lock newEventLock = sessionNewEventsLocks.computeIfAbsent(edgeId, id -> new ReentrantLock()); newEventLock.lock(); try { @@ -387,9 +383,12 @@ public class EdgeGrpcService extends EdgeRpcServiceGrpc.EdgeRpcServiceImplBase i save(tenantId, edgeId, LAST_CONNECT_TIME, lastConnectTs); edgeIdServiceIdCache.put(edgeId, serviceInfoProvider.getServiceId()); pushRuleEngineMessage(tenantId, edge, lastConnectTs, TbMsgType.CONNECT_EVENT); - cancelScheduleEdgeEventsCheck(edgeId); edgeEventsMigrationProcessed.putIfAbsent(edgeId, Boolean.FALSE); scheduleEdgeEventsCheck(edgeGrpcSession); + if (replaced != null) { + // destroy is slow (stops the kafka edge event consumer), keep it off the atomic path + destroySession(replaced); + } } private void startSyncProcess(TenantId tenantId, EdgeId edgeId, UUID requestId, String requestServiceId) { @@ -451,55 +450,62 @@ public class EdgeGrpcService extends EdgeRpcServiceGrpc.EdgeRpcServiceImplBase i EdgeId edgeId = session.getEdge().getId(); TenantId tenantId = session.getEdge().getTenantId(); - cancelScheduleEdgeEventsCheck(edgeId); - - if (sessions.containsKey(edgeId)) { - ScheduledFuture edgeEventCheckTask = edgeEventProcessingExecutorService.schedule(() -> { + Runnable edgeEventCheck = () -> { + try { + final Lock newEventLock = sessionNewEventsLocks.computeIfAbsent(edgeId, id -> new ReentrantLock()); + newEventLock.lock(); try { - final Lock newEventLock = sessionNewEventsLocks.computeIfAbsent(edgeId, id -> new ReentrantLock()); - newEventLock.lock(); - try { - if (Boolean.TRUE.equals(sessionNewEvents.get(edgeId))) { - log.trace("[{}][{}] set session new events flag to false", tenantId, edgeId.getId()); - sessionNewEvents.put(edgeId, false); - session.processHighPriorityEvents(); - processEdgeEventMigrationIfNeeded(session, edgeId); - if (Boolean.TRUE.equals(edgeEventsMigrationProcessed.get(edgeId))) { - Futures.addCallback(session.processEdgeEvents(), new FutureCallback<>() { - @Override - public void onSuccess(Boolean newEventsAdded) { - if (Boolean.TRUE.equals(newEventsAdded)) { - log.trace("[{}][{}] new events added. set session new events flag to true", tenantId, edgeId.getId()); - sessionNewEvents.put(edgeId, true); - } - scheduleEdgeEventsCheck(session); + if (Boolean.TRUE.equals(sessionNewEvents.get(edgeId))) { + log.trace("[{}][{}] set session new events flag to false", tenantId, edgeId.getId()); + sessionNewEvents.put(edgeId, false); + session.processHighPriorityEvents(); + processEdgeEventMigrationIfNeeded(session, edgeId); + if (Boolean.TRUE.equals(edgeEventsMigrationProcessed.get(edgeId))) { + Futures.addCallback(session.processEdgeEvents(), new FutureCallback<>() { + @Override + public void onSuccess(Boolean newEventsAdded) { + if (Boolean.TRUE.equals(newEventsAdded)) { + log.trace("[{}][{}] new events added. set session new events flag to true", tenantId, edgeId.getId()); + sessionNewEvents.put(edgeId, true); } - - @Override - public void onFailure(Throwable t) { - log.warn("[{}] Failed to process edge events for edge [{}]!", tenantId, session.getEdge().getId().getId(), t); - scheduleEdgeEventsCheck(session); - } - }, ctx.getGrpcCallbackExecutorService()); - } else { - scheduleEdgeEventsCheck(session); - } + scheduleEdgeEventsCheck(session); + } + + @Override + public void onFailure(Throwable t) { + log.warn("[{}] Failed to process edge events for edge [{}]!", tenantId, session.getEdge().getId().getId(), t); + scheduleEdgeEventsCheck(session); + } + }, ctx.getGrpcCallbackExecutorService()); } else { scheduleEdgeEventsCheck(session); } - } finally { - newEventLock.unlock(); + } else { + scheduleEdgeEventsCheck(session); } - } catch (Exception e) { - log.warn("[{}] Failed to process edge events for edge [{}]!", tenantId, session.getEdge().getId().getId(), e); + } finally { + newEventLock.unlock(); } - }, ctx.getEdgeEventStorageSettings().getNoRecordsSleepInterval(), TimeUnit.MILLISECONDS); - sessionEdgeEventChecks.put(edgeId, edgeEventCheckTask); + } catch (Exception e) { + log.warn("[{}] Failed to process edge events for edge [{}]!", tenantId, session.getEdge().getId().getId(), e); + } + }; + + // arm the next check only while this exact session is still the current one, atomically with + // cancelling the previous one, so that a concurrent connect/disconnect can neither lose the + // re-arm nor cancel a check that belongs to a session other than the one it is tearing down + sessions.compute(edgeId, (id, current) -> { + if (current != session) { + log.debug("[{}] Session is not current anymore and edge event check schedule must not be started [{}]", + tenantId, edgeId.getId()); + return current; + } + cancelScheduleEdgeEventsCheck(edgeId); + sessionEdgeEventChecks.put(edgeId, edgeEventProcessingExecutorService.schedule(edgeEventCheck, + ctx.getEdgeEventStorageSettings().getNoRecordsSleepInterval(), TimeUnit.MILLISECONDS)); log.trace("[{}] Check edge event scheduled for edge [{}]", tenantId, edgeId.getId()); - } else { - log.debug("[{}] Session was removed and edge event check schedule must not be started [{}]", - tenantId, edgeId.getId()); - } + return current; + }); } private void processEdgeEventMigrationIfNeeded(EdgeGrpcSession session, EdgeId edgeId) throws Exception { @@ -532,24 +538,20 @@ public class EdgeGrpcService extends EdgeRpcServiceGrpc.EdgeRpcServiceImplBase i private void onEdgeDisconnect(Edge edge, UUID sessionId) { EdgeId edgeId = edge.getId(); log.info("[{}][{}] edge disconnected!", edgeId, sessionId); - EdgeGrpcSession current = sessions.get(edgeId); - if (current != null && current.getSessionId().equals(sessionId)) { - EdgeGrpcSession toRemove = sessions.remove(edgeId); - final Lock newEventLock = sessionNewEventsLocks.computeIfAbsent(edgeId, id -> new ReentrantLock()); - newEventLock.lock(); - try { - sessionNewEvents.remove(edgeId); - } finally { - newEventLock.unlock(); - } - destroySession(toRemove); + EdgeGrpcSession toRemove = detachSession(edgeId, current -> current.getSessionId().equals(sessionId)); + if (toRemove != null) { + // sessionNewEvents is deliberately left as is: clearing it here could wipe the flag a + // reconnecting session has just set, and updateSessionEventsFlag only lifts FALSE, not a + // missing entry, which would leave the check loop idle forever. deleteEdge still clears it sessionsById.remove(sessionId); + edgeIdServiceIdCache.evict(edgeId); TenantId tenantId = toRemove.getEdge().getTenantId(); - save(tenantId, edgeId, ACTIVITY_STATE, false); long lastDisconnectTs = System.currentTimeMillis(); + save(tenantId, edgeId, ACTIVITY_STATE, false); save(tenantId, edgeId, LAST_DISCONNECT_TIME, lastDisconnectTs); - pushRuleEngineMessage(toRemove.getEdge().getTenantId(), edge, lastDisconnectTs, TbMsgType.DISCONNECT_EVENT); - cancelScheduleEdgeEventsCheck(edgeId); + pushRuleEngineMessage(tenantId, edge, lastDisconnectTs, TbMsgType.DISCONNECT_EVENT); + // destroy is slow (stops the kafka edge event consumer), keep it off the atomic path + destroySession(toRemove); } else { log.info("[{}] edge session [{}] is not current anymore. Attempting to destroy it by sessionId.", edgeId, sessionId); EdgeGrpcSession stale = sessionsById.remove(sessionId); @@ -564,7 +566,41 @@ public class EdgeGrpcService extends EdgeRpcServiceGrpc.EdgeRpcServiceImplBase i log.debug("[{}] No session found by sessionId [{}] to destroy", edgeId, sessionId); } } - edgeIdServiceIdCache.evict(edgeId); + } + + /** + * Registers the session as the current one for the edge and cancels the edge event check armed by + * the session it replaces, as a single atomic step. Returns the replaced session, or null if there + * was none - the caller is responsible for destroying it outside of this critical section. + */ + private EdgeGrpcSession attachSession(EdgeId edgeId, EdgeGrpcSession session) { + AtomicReference replaced = new AtomicReference<>(); + sessions.compute(edgeId, (id, current) -> { + replaced.set(current); + cancelScheduleEdgeEventsCheck(edgeId); + return session; + }); + return replaced.get(); + } + + /** + * Detaches the edge's registered session and cancels its edge event check as a single atomic step, + * but only if that session satisfies shouldDetach. Returns the detached session, or null if the + * predicate rejected it - most importantly when another session has taken the edge over in the + * meantime, in which case nothing is touched and a reconnect racing with a teardown cannot lose + * the check it has just armed. The caller destroys the returned session outside the atomic step. + */ + private EdgeGrpcSession detachSession(EdgeId edgeId, Predicate shouldDetach) { + AtomicReference detached = new AtomicReference<>(); + sessions.compute(edgeId, (id, current) -> { + if (current == null || !shouldDetach.test(current)) { + return current; + } + detached.set(current); + cancelScheduleEdgeEventsCheck(edgeId); + return null; + }); + return detached.get(); } private void destroySession(EdgeGrpcSession session) { @@ -686,7 +722,9 @@ public class EdgeGrpcService extends EdgeRpcServiceGrpc.EdgeRpcServiceImplBase i private void cleanupZombieSessions() { try { - tryToDestroyZombieSessions(getZombieSessions(sessions.values()), s -> sessions.remove(s.getEdge().getId())); + // compare-and-remove: the edge may have reconnected since the zombie scan, and that newer + // session must not be evicted by the cleanup of the one it replaced + tryToDestroyZombieSessions(getZombieSessions(sessions.values()), s -> sessions.remove(s.getEdge().getId(), s)); tryToDestroyZombieSessions(getZombieSessions(sessionsById.values()), s -> sessionsById.remove(s.getSessionId())); zombieSessions.removeIf(zombie -> { @@ -715,11 +753,11 @@ public class EdgeGrpcService extends EdgeRpcServiceGrpc.EdgeRpcServiceImplBase i return result; } - private void tryToDestroyZombieSessions(List sessionsToRemove, Function removeFunc) { + private void tryToDestroyZombieSessions(List sessionsToRemove, Consumer removeFunc) { for (EdgeGrpcSession toRemove : sessionsToRemove) { log.info("[{}] Destroying session for edge because edge is not connected", toRemove.getEdge().getId()); if (toRemove.destroy()) { - removeFunc.apply(toRemove); + removeFunc.accept(toRemove); } } } From 1a15b5c94f729e0a7b09b13ca2e4a70b5c73e061 Mon Sep 17 00:00:00 2001 From: dpinkevych Date: Mon, 7 Sep 2026 15:11:49 +0300 Subject: [PATCH 007/159] report every conflicting entity before installing a solution template Only rule chains, profiles and dashboards were checked upfront, so a template with a clashing customer, asset, device or edge died mid install on a DB constraint and had to be rolled back. All of them are validated now, and every conflict is named and reported at once instead of repeating the same sentence per entity type. Rule chains are looked up by exact name and dashboards by exact title, since the paged text search matches with 'contains' and could report a different entity as the conflict. The install dialog also stopped repeating "Failed to install " inside the error details, since it is already shown right above them. --- .../service/iot_hub/DefaultIotHubService.java | 5 +- .../solutions/DefaultSolutionService.java | 147 +++++++++++------- .../iot_hub/DefaultIotHubServiceTest.java | 35 +++++ .../solutions/DefaultSolutionServiceTest.java | 133 ++++++++++++++++ 4 files changed, 262 insertions(+), 58 deletions(-) create mode 100644 application/src/test/java/org/thingsboard/server/service/solutions/DefaultSolutionServiceTest.java diff --git a/application/src/main/java/org/thingsboard/server/service/iot_hub/DefaultIotHubService.java b/application/src/main/java/org/thingsboard/server/service/iot_hub/DefaultIotHubService.java index f7cc08391a..cd90af6f26 100644 --- a/application/src/main/java/org/thingsboard/server/service/iot_hub/DefaultIotHubService.java +++ b/application/src/main/java/org/thingsboard/server/service/iot_hub/DefaultIotHubService.java @@ -952,7 +952,10 @@ public class DefaultIotHubService implements IotHubService { boolean rolledBack = rollbackInstalledItems(user, rollbackIds); result.setSuccess(false); result.setRolledBack(rolledBack); - result.setErrorMessage("Failed to install '" + entry.getName() + "': " + e.getMessage()); + // The dialog already says "Failed to install ''" above the details, so only a + // failing dependency is worth naming here - for the root entry that would just repeat itself. + result.setErrorMessage(entry.isRoot() ? e.getMessage() + : "Failed to install dependency '" + entry.getName() + "': " + e.getMessage()); result.setEntries(resultEntries); result.setMissingItemIds(missingItemIds); return result; diff --git a/application/src/main/java/org/thingsboard/server/service/solutions/DefaultSolutionService.java b/application/src/main/java/org/thingsboard/server/service/solutions/DefaultSolutionService.java index 34e56275e2..d84e681be6 100644 --- a/application/src/main/java/org/thingsboard/server/service/solutions/DefaultSolutionService.java +++ b/application/src/main/java/org/thingsboard/server/service/solutions/DefaultSolutionService.java @@ -32,7 +32,6 @@ import org.thingsboard.server.common.adaptor.JsonConverter; import org.thingsboard.server.common.data.AttributeScope; import org.thingsboard.server.common.data.Dashboard; import org.thingsboard.server.common.data.Customer; -import org.thingsboard.server.common.data.DashboardInfo; import org.thingsboard.server.common.data.DeviceProfile; import org.thingsboard.server.common.data.HasName; import org.thingsboard.server.common.data.alarm.AlarmInfo; @@ -42,7 +41,6 @@ import org.thingsboard.server.common.data.exception.ThingsboardException; import org.thingsboard.server.common.data.iot_hub.SolutionTemplateInstalledItemDescriptor; import org.thingsboard.server.common.data.kv.BaseDeleteTsKvQuery; import org.thingsboard.server.common.data.kv.DeleteTsKvQuery; -import org.thingsboard.server.common.data.page.PageLink; import org.thingsboard.server.common.data.page.TimePageLink; import org.thingsboard.server.common.data.EntityType; import org.thingsboard.server.common.data.StringUtils; @@ -151,12 +149,15 @@ import java.nio.file.SimpleFileVisitor; import java.nio.file.attribute.BasicFileAttributes; import java.time.ZonedDateTime; import java.util.ArrayList; +import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; +import java.util.LinkedHashMap; import java.util.List; import java.util.Map; +import java.util.Objects; import java.util.Set; import java.util.TreeMap; import java.util.concurrent.ExecutorService; @@ -177,6 +178,11 @@ import java.util.zip.ZipInputStream; @Slf4j public class DefaultSolutionService implements SolutionService { + private static final String BLANK_LINE = System.lineSeparator() + System.lineSeparator(); + private static final String CONFLICTS_INTRO = + "Some entities of the solution template already exist. Rename or delete them and install the template again:"; + private static final String RANDOM_NAME_PLACEHOLDER_PREFIX = "$random"; + @Value("${ui.solution_templates.docs_base_url:https://thingsboard.io/docs}") private String docsBaseUrl; @@ -291,71 +297,102 @@ public class DefaultSolutionService implements SolutionService { } } - private SolutionInstallResponse validateSolution(TenantId tenantId, Path tempDir) { - Map> alreadyExistingEntities = new HashMap<>(); - + SolutionInstallResponse validateSolution(TenantId tenantId, Path tempDir) { //TODO: check other entities. List ruleChains = loadListOfEntitiesIfFileExists(tempDir, "rule_chains.json", new TypeReference<>() { }); - if (!ruleChains.isEmpty()) { - for (ReferenceableEntityDefinition ruleChain : ruleChains) { - List savedRuleChains = ruleChainService.findTenantRuleChainsByType(tenantId, RuleChainType.CORE, new PageLink(1, 0, ruleChain.getName())).getData(); - if (savedRuleChains != null && !savedRuleChains.isEmpty()) { - alreadyExistingEntities.computeIfAbsent(EntityType.RULE_CHAIN, key -> new ArrayList<>()).add(savedRuleChains.get(0)); - } - } - } - List deviceProfiles = loadListOfEntitiesIfFileExists(tempDir, "device_profiles.json", new TypeReference<>() { }); deviceProfiles.addAll(loadListOfEntitiesFromDirectory(tempDir, "device_profiles", DeviceProfileDefinition.class)); - // Validate that entities with such name does not exist entities - if (!deviceProfiles.isEmpty()) { - for (DeviceProfile deviceProfile : deviceProfiles) { - DeviceProfile savedProfile = deviceProfileService.findDeviceProfileByName(tenantId, deviceProfile.getName()); - if (savedProfile != null) { - alreadyExistingEntities.computeIfAbsent(EntityType.DEVICE_PROFILE, key -> new ArrayList<>()).add(savedProfile); - } - } - } - List assetProfiles = loadListOfEntitiesIfFileExists(tempDir, "asset_profiles.json", new TypeReference<>() { }); assetProfiles.addAll(loadListOfEntitiesFromDirectory(tempDir, "asset_profiles", AssetProfileDefinition.class)); - // Validate that entities with such name does not exist entities - if (!assetProfiles.isEmpty()) { - for (AssetProfile assetProfile : assetProfiles) { - AssetProfile savedProfile = assetProfileService.findAssetProfileByName(tenantId, assetProfile.getName()); - if (savedProfile != null) { - alreadyExistingEntities.computeIfAbsent(EntityType.ASSET_PROFILE, key -> new ArrayList<>()).add(savedProfile); - } - } - } - + List customers = loadListOfEntitiesIfFileExists(tempDir, "customers.json", new TypeReference<>() { + }); List dashboards = loadListOfEntitiesIfFileExists(tempDir, "dashboards.json", new TypeReference<>() { }); - if (!dashboards.isEmpty()) { - for (DashboardDefinition dashboard : dashboards) { - List savedDashboards = dashboardService.findDashboardsByTenantId(tenantId, new PageLink(1, 0, dashboard.getName())).getData(); - if (savedDashboards != null && !savedDashboards.isEmpty()) { - alreadyExistingEntities.computeIfAbsent(EntityType.DASHBOARD, key -> new ArrayList<>()).add(savedDashboards.get(0)); - } + List assets = loadListOfEntitiesIfFileExists(tempDir, "assets.json", new TypeReference<>() { + }); + List devices = loadListOfEntitiesIfFileExists(tempDir, "devices.json", new TypeReference<>() { + }); + List edges = loadListOfEntitiesIfFileExists(tempDir, "edges.json", new TypeReference<>() { + }); + + // Insertion ordered, so that the reported sections keep the order the entities are provisioned in. + Map> conflicts = new LinkedHashMap<>(); + collectConflicts(conflicts, EntityType.RULE_CHAIN, ruleChains, ReferenceableEntityDefinition::getName, + name -> firstOrNull(ruleChainService.findTenantRuleChainsByTypeAndName(tenantId, RuleChainType.CORE, name))); + collectConflicts(conflicts, EntityType.DEVICE_PROFILE, deviceProfiles, DeviceProfile::getName, + name -> deviceProfileService.findDeviceProfileByName(tenantId, name)); + collectConflicts(conflicts, EntityType.ASSET_PROFILE, assetProfiles, AssetProfile::getName, + name -> assetProfileService.findAssetProfileByName(tenantId, name)); + collectConflicts(conflicts, EntityType.CUSTOMER, customers, CustomerDefinition::getName, + title -> isRandomizedAtInstall(title) ? null : customerService.findCustomerByTenantIdAndTitle(tenantId, title).orElse(null)); + collectConflicts(conflicts, EntityType.DASHBOARD, dashboards, DashboardDefinition::getName, + title -> dashboardService.findFirstDashboardInfoByTenantIdAndName(tenantId, title)); + collectConflicts(conflicts, EntityType.ASSET, assets, AssetDefinition::getName, + name -> assetService.findAssetByTenantIdAndName(tenantId, name)); + collectConflicts(conflicts, EntityType.DEVICE, devices, DeviceDefinition::getName, + name -> deviceService.findDeviceByTenantIdAndName(tenantId, name)); + collectConflicts(conflicts, EntityType.EDGE, edges, EdgeDefinition::getName, + name -> edgeService.findEdgeByTenantIdAndName(tenantId, name)); + + if (conflicts.isEmpty()) { + return null; + } + StringBuilder details = new StringBuilder(CONFLICTS_INTRO).append(BLANK_LINE); + conflicts.forEach((entityType, entities) -> appendConflicts(details, entityType, + entities.stream().map(HasName::getName).map(DefaultSolutionService::quoted).toList())); + + SolutionInstallResponse solutionInstallResponse = new SolutionInstallResponse(); + solutionInstallResponse.setSuccess(false); + solutionInstallResponse.setDetails(details.toString()); + return solutionInstallResponse; + } + + private void collectConflicts(Map> conflicts, EntityType entityType, List definitions, + Function nameExtractor, Function lookup) { + for (T definition : definitions) { + String name = nameExtractor.apply(definition); + if (StringUtils.isEmpty(name)) { + continue; + } + HasName existing = lookup.apply(name); + if (existing != null) { + conflicts.computeIfAbsent(entityType, key -> new ArrayList<>()).add(existing); } } - if (!alreadyExistingEntities.isEmpty()) { - SolutionInstallResponse solutionInstallResponse = new SolutionInstallResponse(); - StringBuilder detailsBuilder = new StringBuilder(); - detailsBuilder.append("## Validation failed").append(System.lineSeparator()).append(System.lineSeparator()); - alreadyExistingEntities.forEach((type, list) -> detailsBuilder.append("The following **").append(getTypeLabel(type)).append("** entities already exist: ") - .append(list.stream().map(HasName::getName).map(name -> "'" + name + "'").collect(Collectors.joining(","))).append(";") - .append(System.lineSeparator()).append(System.lineSeparator())); - solutionInstallResponse.setSuccess(false); - solutionInstallResponse.setDetails(detailsBuilder.toString()); - return solutionInstallResponse; - } else { - return null; + } + + /** + * Only customer titles, user names and attribute values go through {@link #randomize}, so a {@code $random} + * placeholder in a customer title is replaced at install time and there is nothing to check upfront. Names of + * every other entity are used as written, placeholder included, so those are looked up as is - skipping them + * here would let the install die on a DB constraint again. + */ + private static boolean isRandomizedAtInstall(String name) { + return name.contains(RANDOM_NAME_PLACEHOLDER_PREFIX); + } + + /** + * One markdown list item per entity type, so that the names of the conflicting entities are what the user reads, + * instead of the same sentence repeated for every type. + */ + private void appendConflicts(StringBuilder details, EntityType entityType, List conflictDescriptions) { + if (conflictDescriptions.isEmpty()) { + return; } + details.append("- **").append(entityType.getNormalName()).append("**: ") + .append(conflictDescriptions.stream().distinct().collect(Collectors.joining(", "))).append(System.lineSeparator()); + } + + private static String quoted(String value) { + return "'" + value + "'"; + } + + private static T firstOrNull(Collection data) { + return data == null || data.isEmpty() ? null : data.iterator().next(); } private SolutionInstallResponse doInstallSolution(User user, TenantId tenantId, String solutionId, Path tempDir, HttpServletRequest request) { @@ -1450,10 +1487,6 @@ public class DefaultSolutionService implements SolutionService { return String.valueOf(now.toInstant().toEpochMilli()); } - private String getTypeLabel(EntityType type) { - return type.name().toLowerCase().replace('_', ' '); - } - private T loadEntityIfFileExists(Path tempDir, String fileName, Class clazz) { Path filePath = tempDir.resolve("entities").resolve(fileName); if (Files.exists(filePath)) { @@ -1467,7 +1500,7 @@ public class DefaultSolutionService implements SolutionService { Path filePath = tempDir.resolve("entities").resolve(fileName); if (Files.exists(filePath)) { try { - return JacksonUtil.readValue(filePath.toFile(), typeReference); + return Objects.requireNonNullElseGet(JacksonUtil.readValue(filePath.toFile(), typeReference), ArrayList::new); } catch (Exception e) { throw new IllegalArgumentException("Invalid json file " + fileName + " data structure", e); } diff --git a/application/src/test/java/org/thingsboard/server/service/iot_hub/DefaultIotHubServiceTest.java b/application/src/test/java/org/thingsboard/server/service/iot_hub/DefaultIotHubServiceTest.java index c252b58103..bfe0db5750 100644 --- a/application/src/test/java/org/thingsboard/server/service/iot_hub/DefaultIotHubServiceTest.java +++ b/application/src/test/java/org/thingsboard/server/service/iot_hub/DefaultIotHubServiceTest.java @@ -344,6 +344,41 @@ class DefaultIotHubServiceTest { inOrder.verify(service).deleteInstalledItem(user, dep1Item.getId()); } + @Test + void installPlan_rootFails_errorMessageIsNotPrefixedWithTheItemName() throws Exception { + mockTenant(); + HttpServletRequest request = mock(HttpServletRequest.class); + String rootVersionId = UUID.randomUUID().toString(); + InstallPlanEntry root = willInstall(rootVersionId, true); + + when(iotHubInstalledItemService.findInstalledItemIdsByTenantIdAndItemIdIn(eq(tenantId), any())).thenReturn(List.of()); + doThrow(new IllegalStateException("install failed")).when(service).doInstallVersion(eq(user), eq(rootVersionId), any(), any()); + + InstallPlanResult result = service.installPlan(user, new InstallPlan(rootVersionId, List.of(root)), null, request); + + // the install dialog already shows "Failed to install ''" right above these details + assertThat(result.getErrorMessage()).isEqualTo("install failed"); + } + + @Test + void installPlan_dependencyFails_errorMessageNamesTheDependency() throws Exception { + mockTenant(); + HttpServletRequest request = mock(HttpServletRequest.class); + String depVersionId = UUID.randomUUID().toString(); + String rootVersionId = UUID.randomUUID().toString(); + InstallPlanEntry dep = willInstall(depVersionId, false); + InstallPlanEntry root = willInstall(rootVersionId, true); + + when(iotHubInstalledItemService.findInstalledItemIdsByTenantIdAndItemIdIn(eq(tenantId), any())).thenReturn(List.of()); + doThrow(new IllegalStateException("install failed")).when(service).doInstallVersion(eq(user), eq(depVersionId), any(), any()); + + InstallPlanResult result = service.installPlan(user, new InstallPlan(rootVersionId, List.of(dep, root)), null, request); + + // a failing dependency is not the item the dialog names, so it has to be named here + assertThat(result.getErrorMessage()).isEqualTo("Failed to install dependency 'Dep': install failed"); + verify(service, never()).doInstallVersion(eq(user), eq(rootVersionId), any(), any()); + } + @Test void installPlan_rollbackFailure_reportsNotFullyRolledBack() throws Exception { mockTenant(); diff --git a/application/src/test/java/org/thingsboard/server/service/solutions/DefaultSolutionServiceTest.java b/application/src/test/java/org/thingsboard/server/service/solutions/DefaultSolutionServiceTest.java new file mode 100644 index 0000000000..a8c5697a42 --- /dev/null +++ b/application/src/test/java/org/thingsboard/server/service/solutions/DefaultSolutionServiceTest.java @@ -0,0 +1,133 @@ +/** + * Copyright © 2016-2026 The Thingsboard Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.thingsboard.server.service.solutions; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.junit.jupiter.api.io.TempDir; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; +import org.thingsboard.server.common.data.Customer; +import org.thingsboard.server.common.data.DashboardInfo; +import org.thingsboard.server.common.data.Device; +import org.thingsboard.server.common.data.id.TenantId; +import org.thingsboard.server.dao.asset.AssetService; +import org.thingsboard.server.dao.customer.CustomerService; +import org.thingsboard.server.dao.dashboard.DashboardService; +import org.thingsboard.server.dao.device.DeviceService; +import org.thingsboard.server.service.solutions.data.solution.SolutionInstallResponse; + +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.Optional; +import java.util.UUID; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +@ExtendWith(MockitoExtension.class) +class DefaultSolutionServiceTest { + + private static final String CONFLICTS_INTRO = + "Some entities of the solution template already exist. Rename or delete them and install the template again:"; + + private final TenantId tenantId = TenantId.fromUUID(UUID.randomUUID()); + + @Mock + private CustomerService customerService; + @Mock + private DeviceService deviceService; + @Mock + private AssetService assetService; + @Mock + private DashboardService dashboardService; + + @InjectMocks + private DefaultSolutionService service; + + @TempDir + private Path tempDir; + + @Test + void testValidateSolutionNamesEveryConflictingEntity() throws IOException { + writeEntitiesFile("customers.json", "[{\"name\": \"Existing customer\"}, {\"name\": \"Customer $random\"}]"); + writeEntitiesFile("devices.json", "[{\"name\": \"Existing device\"}, {\"name\": \"New device\"}]"); + writeEntitiesFile("assets.json", "[{\"name\": \"New asset\"}]"); + + Customer customer = new Customer(); + customer.setTitle("Existing customer"); + Device device = new Device(); + device.setName("Existing device"); + + when(customerService.findCustomerByTenantIdAndTitle(tenantId, "Existing customer")).thenReturn(Optional.of(customer)); + when(assetService.findAssetByTenantIdAndName(tenantId, "New asset")).thenReturn(null); + when(deviceService.findDeviceByTenantIdAndName(tenantId, "Existing device")).thenReturn(device); + when(deviceService.findDeviceByTenantIdAndName(tenantId, "New device")).thenReturn(null); + + SolutionInstallResponse result = service.validateSolution(tenantId, tempDir); + + assertThat(result).isNotNull(); + assertThat(result.isSuccess()).isFalse(); + assertThat(result.getDetails().lines().toList()) + .containsSubsequence( + CONFLICTS_INTRO, + "- **Customer**: 'Existing customer'", + "- **Device**: 'Existing device'"); + // the randomized customer title and the entities that do not exist yet are not reported + assertThat(result.getDetails()) + .doesNotContain("Customer $random") + .doesNotContain("New device") + .doesNotContain("New asset"); + } + + @Test + void testValidateSolutionReportsConflictingDashboard() throws IOException { + writeEntitiesFile("dashboards.json", "[{\"name\": \"Overview\", \"file\": \"overview.json\"}]"); + + DashboardInfo dashboard = new DashboardInfo(); + dashboard.setTitle("Overview"); + when(dashboardService.findFirstDashboardInfoByTenantIdAndName(tenantId, "Overview")).thenReturn(dashboard); + + SolutionInstallResponse result = service.validateSolution(tenantId, tempDir); + + assertThat(result).isNotNull(); + assertThat(result.getDetails().lines().toList()) + .containsSubsequence(CONFLICTS_INTRO, "- **Dashboard**: 'Overview'"); + } + + @Test + void testValidateSolutionWithoutConflicts() throws IOException { + writeEntitiesFile("devices.json", "[{\"name\": \"New device\"}]"); + when(deviceService.findDeviceByTenantIdAndName(tenantId, "New device")).thenReturn(null); + + assertThat(service.validateSolution(tenantId, tempDir)).isNull(); + } + + @Test + void testValidateSolutionWithoutEntityFiles() { + assertThat(service.validateSolution(tenantId, tempDir)).isNull(); + verifyNoInteractions(customerService, deviceService, assetService, dashboardService); + } + + private void writeEntitiesFile(String fileName, String content) throws IOException { + Path entitiesDir = Files.createDirectories(tempDir.resolve("entities")); + Files.writeString(entitiesDir.resolve(fileName), content); + } + +} From 56866d30c8522842a7d12b2c50e11108debe919c Mon Sep 17 00:00:00 2001 From: dpinkevych Date: Mon, 7 Sep 2026 15:11:49 +0300 Subject: [PATCH 008/159] compose the failed dependency sentence in the dialog, not in the service The service was pre-composing "Failed to install dependency '':", which can never be translated and made the backend depend on the dialog already printing the root item above the details. It now reports the failure itself, and the dialog prefixes a localized sentence when the entry that failed is not the root. --- .../service/iot_hub/DefaultIotHubService.java | 5 +---- .../service/iot_hub/DefaultIotHubServiceTest.java | 15 ++++++++++----- .../iot-hub/iot-hub-install-dialog.component.ts | 6 ++++++ .../src/assets/locale/locale.constant-en_US.json | 1 + 4 files changed, 18 insertions(+), 9 deletions(-) diff --git a/application/src/main/java/org/thingsboard/server/service/iot_hub/DefaultIotHubService.java b/application/src/main/java/org/thingsboard/server/service/iot_hub/DefaultIotHubService.java index cd90af6f26..f7109c3bf2 100644 --- a/application/src/main/java/org/thingsboard/server/service/iot_hub/DefaultIotHubService.java +++ b/application/src/main/java/org/thingsboard/server/service/iot_hub/DefaultIotHubService.java @@ -952,10 +952,7 @@ public class DefaultIotHubService implements IotHubService { boolean rolledBack = rollbackInstalledItems(user, rollbackIds); result.setSuccess(false); result.setRolledBack(rolledBack); - // The dialog already says "Failed to install ''" above the details, so only a - // failing dependency is worth naming here - for the root entry that would just repeat itself. - result.setErrorMessage(entry.isRoot() ? e.getMessage() - : "Failed to install dependency '" + entry.getName() + "': " + e.getMessage()); + result.setErrorMessage(e.getMessage()); result.setEntries(resultEntries); result.setMissingItemIds(missingItemIds); return result; diff --git a/application/src/test/java/org/thingsboard/server/service/iot_hub/DefaultIotHubServiceTest.java b/application/src/test/java/org/thingsboard/server/service/iot_hub/DefaultIotHubServiceTest.java index bfe0db5750..c48e5896a1 100644 --- a/application/src/test/java/org/thingsboard/server/service/iot_hub/DefaultIotHubServiceTest.java +++ b/application/src/test/java/org/thingsboard/server/service/iot_hub/DefaultIotHubServiceTest.java @@ -345,7 +345,7 @@ class DefaultIotHubServiceTest { } @Test - void installPlan_rootFails_errorMessageIsNotPrefixedWithTheItemName() throws Exception { + void installPlan_errorMessageIsTheFailureItselfWithoutAnyPrefix() throws Exception { mockTenant(); HttpServletRequest request = mock(HttpServletRequest.class); String rootVersionId = UUID.randomUUID().toString(); @@ -356,12 +356,12 @@ class DefaultIotHubServiceTest { InstallPlanResult result = service.installPlan(user, new InstallPlan(rootVersionId, List.of(root)), null, request); - // the install dialog already shows "Failed to install ''" right above these details + // the sentence around the failure belongs to the dialog, which localizes it assertThat(result.getErrorMessage()).isEqualTo("install failed"); } @Test - void installPlan_dependencyFails_errorMessageNamesTheDependency() throws Exception { + void installPlan_dependencyFails_failureIsReportedOnTheEntryAndAsTheResultMessage() throws Exception { mockTenant(); HttpServletRequest request = mock(HttpServletRequest.class); String depVersionId = UUID.randomUUID().toString(); @@ -374,8 +374,13 @@ class DefaultIotHubServiceTest { InstallPlanResult result = service.installPlan(user, new InstallPlan(rootVersionId, List.of(dep, root)), null, request); - // a failing dependency is not the item the dialog names, so it has to be named here - assertThat(result.getErrorMessage()).isEqualTo("Failed to install dependency 'Dep': install failed"); + // the dialog names the failing dependency itself, from the entry it finds in the result + assertThat(result.getErrorMessage()).isEqualTo("install failed"); + assertThat(result.getEntries()).anySatisfy(entry -> { + assertThat(entry.getName()).isEqualTo("Dep"); + assertThat(entry.isRoot()).isFalse(); + assertThat(entry.getErrorMessage()).isEqualTo("install failed"); + }); verify(service, never()).doInstallVersion(eq(user), eq(rootVersionId), any(), any()); } diff --git a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-install-dialog.component.ts b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-install-dialog.component.ts index e4816d19ad..c55d708bcb 100644 --- a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-install-dialog.component.ts +++ b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-install-dialog.component.ts @@ -339,6 +339,12 @@ export class TbIotHubInstallDialogComponent extends DialogComponent !entry.root && entry.errorMessage); + if (failedDependency) { + message = this.translate.instant('iot-hub.install-dependency-error', { name: failedDependency.name }) + ' ' + message; + } // A failed cascade rolls back the items installed so far. When something was actually being // installed and the rollback came back partial (rolledBack === false), some entities are left // behind — tell the admin so they know manual cleanup may be needed. The willInstall guard diff --git a/ui-ngx/src/assets/locale/locale.constant-en_US.json b/ui-ngx/src/assets/locale/locale.constant-en_US.json index 98f59ec8a9..aefce04e88 100644 --- a/ui-ngx/src/assets/locale/locale.constant-en_US.json +++ b/ui-ngx/src/assets/locale/locale.constant-en_US.json @@ -3850,6 +3850,7 @@ "goto-main-dashboard": "Go to main dashboard", "install-error-title": "Installation Failed", "install-error-message": "Failed to install '{{name}}'.", + "install-dependency-error": "Failed to install the dependency '{{name}}':", "install-plan-title": "Install '{{name}}' and its dependencies", "install-plan-will-install": "{{count}} item(s) will be installed.", "install-plan-will-update": "{{count}} item(s) already installed and will be skipped.", From 0d275e0d2cf75dca4f50506fe9107e80e3911829 Mon Sep 17 00:00:00 2001 From: dpinkevych Date: Mon, 7 Sep 2026 15:11:49 +0300 Subject: [PATCH 009/159] address review comments on the install validation - rule chains are looked up under the name from the rule chain file, the same source the install uses, instead of the name in rule_chains.json - the details end with a blank line, so the partial rollback warning the dialog appends does not land inside the last list item - an exception without a message falls back to its type, so the failing entry is still named - the dependency prefix is only added when the server sent an error message, since the fallback sentence names the root item --- .../service/iot_hub/DefaultIotHubService.java | 8 +++-- .../solutions/DefaultSolutionService.java | 22 ++++++++++++- .../iot_hub/DefaultIotHubServiceTest.java | 18 ++++++++++ .../solutions/DefaultSolutionServiceTest.java | 33 ++++++++++++++++++- .../iot-hub-install-dialog.component.ts | 10 +++--- 5 files changed, 83 insertions(+), 8 deletions(-) diff --git a/application/src/main/java/org/thingsboard/server/service/iot_hub/DefaultIotHubService.java b/application/src/main/java/org/thingsboard/server/service/iot_hub/DefaultIotHubService.java index f7109c3bf2..1e41211cb2 100644 --- a/application/src/main/java/org/thingsboard/server/service/iot_hub/DefaultIotHubService.java +++ b/application/src/main/java/org/thingsboard/server/service/iot_hub/DefaultIotHubService.java @@ -21,6 +21,7 @@ import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Service; import org.thingsboard.common.util.JacksonUtil; +import org.thingsboard.server.common.data.StringUtils; import org.thingsboard.server.common.data.asset.AssetProfile; import org.thingsboard.server.common.data.Dashboard; import org.thingsboard.server.common.data.DeviceProfile; @@ -947,12 +948,15 @@ public class DefaultIotHubService implements IotHubService { } catch (Exception e) { log.error("[{}] Cascade install failed at entry {} ({}): {}", tenantId, entry.getName(), entry.getVersionId(), e.getMessage(), e); - resultEntry.setErrorMessage(e.getMessage()); + // an exception without a message would leave both the entry and the result blank, + // and the dialog would have nothing to name the failing entry by + String failure = StringUtils.isEmpty(e.getMessage()) ? e.getClass().getSimpleName() : e.getMessage(); + resultEntry.setErrorMessage(failure); resultEntries.add(resultEntry); boolean rolledBack = rollbackInstalledItems(user, rollbackIds); result.setSuccess(false); result.setRolledBack(rolledBack); - result.setErrorMessage(e.getMessage()); + result.setErrorMessage(failure); result.setEntries(resultEntries); result.setMissingItemIds(missingItemIds); return result; diff --git a/application/src/main/java/org/thingsboard/server/service/solutions/DefaultSolutionService.java b/application/src/main/java/org/thingsboard/server/service/solutions/DefaultSolutionService.java index d84e681be6..216960f4fe 100644 --- a/application/src/main/java/org/thingsboard/server/service/solutions/DefaultSolutionService.java +++ b/application/src/main/java/org/thingsboard/server/service/solutions/DefaultSolutionService.java @@ -321,7 +321,7 @@ public class DefaultSolutionService implements SolutionService { // Insertion ordered, so that the reported sections keep the order the entities are provisioned in. Map> conflicts = new LinkedHashMap<>(); - collectConflicts(conflicts, EntityType.RULE_CHAIN, ruleChains, ReferenceableEntityDefinition::getName, + collectConflicts(conflicts, EntityType.RULE_CHAIN, ruleChains, definition -> ruleChainName(tempDir, definition), name -> firstOrNull(ruleChainService.findTenantRuleChainsByTypeAndName(tenantId, RuleChainType.CORE, name))); collectConflicts(conflicts, EntityType.DEVICE_PROFILE, deviceProfiles, DeviceProfile::getName, name -> deviceProfileService.findDeviceProfileByName(tenantId, name)); @@ -345,6 +345,9 @@ public class DefaultSolutionService implements SolutionService { conflicts.forEach((entityType, entities) -> appendConflicts(details, entityType, entities.stream().map(HasName::getName).map(DefaultSolutionService::quoted).toList())); + // the dialog appends its own sentences to these details, so the list has to end with a blank line + details.append(System.lineSeparator()); + SolutionInstallResponse solutionInstallResponse = new SolutionInstallResponse(); solutionInstallResponse.setSuccess(false); solutionInstallResponse.setDetails(details.toString()); @@ -391,6 +394,23 @@ public class DefaultSolutionService implements SolutionService { return "'" + value + "'"; } + /** + * The provisioned rule chain takes its name from the rule chain file, not from the name in rule_chains.json, + * so the conflict has to be looked up under the name the install will actually create. + */ + private String ruleChainName(Path tempDir, ReferenceableEntityDefinition definition) { + if (StringUtils.isEmpty(definition.getFile())) { + return null; + } + Path ruleChainPath = tempDir.resolve("rule_chains").resolve(definition.getFile()); + if (!Files.exists(ruleChainPath)) { + // provisionRuleChains logs and skips such a definition, so there is nothing to validate + return null; + } + JsonNode ruleChain = JacksonUtil.toJsonNode(ruleChainPath).get("ruleChain"); + return ruleChain != null && ruleChain.hasNonNull("name") ? ruleChain.get("name").asText() : null; + } + private static T firstOrNull(Collection data) { return data == null || data.isEmpty() ? null : data.iterator().next(); } diff --git a/application/src/test/java/org/thingsboard/server/service/iot_hub/DefaultIotHubServiceTest.java b/application/src/test/java/org/thingsboard/server/service/iot_hub/DefaultIotHubServiceTest.java index c48e5896a1..e34fd92d3c 100644 --- a/application/src/test/java/org/thingsboard/server/service/iot_hub/DefaultIotHubServiceTest.java +++ b/application/src/test/java/org/thingsboard/server/service/iot_hub/DefaultIotHubServiceTest.java @@ -384,6 +384,24 @@ class DefaultIotHubServiceTest { verify(service, never()).doInstallVersion(eq(user), eq(rootVersionId), any(), any()); } + @Test + void installPlan_failureWithoutMessage_reportsTheExceptionType() throws Exception { + mockTenant(); + HttpServletRequest request = mock(HttpServletRequest.class); + String rootVersionId = UUID.randomUUID().toString(); + InstallPlanEntry root = willInstall(rootVersionId, true); + + when(iotHubInstalledItemService.findInstalledItemIdsByTenantIdAndItemIdIn(eq(tenantId), any())).thenReturn(List.of()); + doThrow(new NullPointerException()).when(service).doInstallVersion(eq(user), eq(rootVersionId), any(), any()); + + InstallPlanResult result = service.installPlan(user, new InstallPlan(rootVersionId, List.of(root)), null, request); + + // the dialog looks the failing entry up by its error message, so it must never be blank + assertThat(result.getErrorMessage()).isEqualTo("NullPointerException"); + assertThat(result.getEntries()).allSatisfy(entry -> + assertThat(entry.getErrorMessage()).isEqualTo("NullPointerException")); + } + @Test void installPlan_rollbackFailure_reportsNotFullyRolledBack() throws Exception { mockTenant(); diff --git a/application/src/test/java/org/thingsboard/server/service/solutions/DefaultSolutionServiceTest.java b/application/src/test/java/org/thingsboard/server/service/solutions/DefaultSolutionServiceTest.java index a8c5697a42..04096c3cc3 100644 --- a/application/src/test/java/org/thingsboard/server/service/solutions/DefaultSolutionServiceTest.java +++ b/application/src/test/java/org/thingsboard/server/service/solutions/DefaultSolutionServiceTest.java @@ -25,15 +25,19 @@ import org.thingsboard.server.common.data.Customer; import org.thingsboard.server.common.data.DashboardInfo; import org.thingsboard.server.common.data.Device; import org.thingsboard.server.common.data.id.TenantId; +import org.thingsboard.server.common.data.rule.RuleChain; +import org.thingsboard.server.common.data.rule.RuleChainType; import org.thingsboard.server.dao.asset.AssetService; import org.thingsboard.server.dao.customer.CustomerService; import org.thingsboard.server.dao.dashboard.DashboardService; import org.thingsboard.server.dao.device.DeviceService; +import org.thingsboard.server.dao.rule.RuleChainService; import org.thingsboard.server.service.solutions.data.solution.SolutionInstallResponse; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; +import java.util.List; import java.util.Optional; import java.util.UUID; @@ -57,6 +61,8 @@ class DefaultSolutionServiceTest { private AssetService assetService; @Mock private DashboardService dashboardService; + @Mock + private RuleChainService ruleChainService; @InjectMocks private DefaultSolutionService service; @@ -89,6 +95,8 @@ class DefaultSolutionServiceTest { CONFLICTS_INTRO, "- **Customer**: 'Existing customer'", "- **Device**: 'Existing device'"); + // the dialog appends its own sentences, so the details have to end with a blank line + assertThat(result.getDetails()).endsWith(System.lineSeparator() + System.lineSeparator()); // the randomized customer title and the entities that do not exist yet are not reported assertThat(result.getDetails()) .doesNotContain("Customer $random") @@ -111,6 +119,23 @@ class DefaultSolutionServiceTest { .containsSubsequence(CONFLICTS_INTRO, "- **Dashboard**: 'Overview'"); } + @Test + void testValidateSolutionUsesTheRuleChainNameFromTheRuleChainFile() throws IOException { + writeEntitiesFile("rule_chains.json", "[{\"name\": \"Name in the definition\", \"file\": \"rc.json\"}]"); + writeFile("rule_chains/rc.json", "{\"ruleChain\": {\"name\": \"Name the install creates\"}}"); + + RuleChain ruleChain = new RuleChain(); + ruleChain.setName("Name the install creates"); + when(ruleChainService.findTenantRuleChainsByTypeAndName(tenantId, RuleChainType.CORE, "Name the install creates")) + .thenReturn(List.of(ruleChain)); + + SolutionInstallResponse result = service.validateSolution(tenantId, tempDir); + + assertThat(result).isNotNull(); + assertThat(result.getDetails().lines().toList()) + .containsSubsequence(CONFLICTS_INTRO, "- **Rule chain**: 'Name the install creates'"); + } + @Test void testValidateSolutionWithoutConflicts() throws IOException { writeEntitiesFile("devices.json", "[{\"name\": \"New device\"}]"); @@ -122,7 +147,13 @@ class DefaultSolutionServiceTest { @Test void testValidateSolutionWithoutEntityFiles() { assertThat(service.validateSolution(tenantId, tempDir)).isNull(); - verifyNoInteractions(customerService, deviceService, assetService, dashboardService); + verifyNoInteractions(customerService, deviceService, assetService, dashboardService, ruleChainService); + } + + private void writeFile(String relativePath, String content) throws IOException { + Path file = tempDir.resolve(relativePath); + Files.createDirectories(file.getParent()); + Files.writeString(file, content); } private void writeEntitiesFile(String fileName, String content) throws IOException { diff --git a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-install-dialog.component.ts b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-install-dialog.component.ts index c55d708bcb..54a8409063 100644 --- a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-install-dialog.component.ts +++ b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-install-dialog.component.ts @@ -338,10 +338,12 @@ export class TbIotHubInstallDialogComponent extends DialogComponent !entry.root && entry.errorMessage); + const serverError = result.errorMessage; + let message = serverError || this.translate.instant('iot-hub.install-error', { name: this.item.name }); + // The title already names the item being installed, so only a failing dependency has to be named + // here - and only when the server reported the failure, since the fallback above names the root. + const failedDependency = serverError + ? (result.entries ?? []).find(entry => !entry.root && entry.errorMessage) : undefined; if (failedDependency) { message = this.translate.instant('iot-hub.install-dependency-error', { name: failedDependency.name }) + ' ' + message; } From b23fe58f2f35d3381996b9dc946b2cbf948be604 Mon Sep 17 00:00:00 2001 From: dpinkevych Date: Mon, 7 Sep 2026 15:12:03 +0300 Subject: [PATCH 010/159] report every conflicting entity before installing a solution template Only rule chains, profiles and dashboards were checked upfront, so a template with a clashing customer, asset, device or edge died mid install on a DB constraint and had to be rolled back. All of them are validated now, and every conflict is named and reported at once instead of repeating the same sentence per entity type. Rule chains are looked up by exact name and dashboards by exact title, since the paged text search matches with 'contains' and could report a different entity as the conflict. The install dialog also stopped repeating "Failed to install " inside the error details, since it is already shown right above them. --- .../service/iot_hub/DefaultIotHubService.java | 5 +- .../solutions/DefaultSolutionService.java | 152 +++++++++++------- .../iot_hub/DefaultIotHubServiceTest.java | 35 ++++ .../solutions/DefaultSolutionServiceTest.java | 133 +++++++++++++++ 4 files changed, 267 insertions(+), 58 deletions(-) create mode 100644 application/src/test/java/org/thingsboard/server/service/solutions/DefaultSolutionServiceTest.java diff --git a/application/src/main/java/org/thingsboard/server/service/iot_hub/DefaultIotHubService.java b/application/src/main/java/org/thingsboard/server/service/iot_hub/DefaultIotHubService.java index eb082c92c8..7f4bdfe089 100644 --- a/application/src/main/java/org/thingsboard/server/service/iot_hub/DefaultIotHubService.java +++ b/application/src/main/java/org/thingsboard/server/service/iot_hub/DefaultIotHubService.java @@ -1011,7 +1011,10 @@ public class DefaultIotHubService implements IotHubService { boolean rolledBack = rollbackInstalledItems(user, rollbackIds); result.setSuccess(false); result.setRolledBack(rolledBack); - result.setErrorMessage("Failed to install '" + entry.getName() + "': " + e.getMessage()); + // The dialog already says "Failed to install ''" above the details, so only a + // failing dependency is worth naming here - for the root entry that would just repeat itself. + result.setErrorMessage(entry.isRoot() ? e.getMessage() + : "Failed to install dependency '" + entry.getName() + "': " + e.getMessage()); result.setEntries(resultEntries); result.setMissingItemIds(missingItemIds); return result; diff --git a/application/src/main/java/org/thingsboard/server/service/solutions/DefaultSolutionService.java b/application/src/main/java/org/thingsboard/server/service/solutions/DefaultSolutionService.java index 2d722e6483..b2c48f22b7 100644 --- a/application/src/main/java/org/thingsboard/server/service/solutions/DefaultSolutionService.java +++ b/application/src/main/java/org/thingsboard/server/service/solutions/DefaultSolutionService.java @@ -32,7 +32,6 @@ import org.thingsboard.server.common.adaptor.JsonConverter; import org.thingsboard.server.common.data.AttributeScope; import org.thingsboard.server.common.data.Dashboard; import org.thingsboard.server.common.data.Customer; -import org.thingsboard.server.common.data.DashboardInfo; import org.thingsboard.server.common.data.DeviceProfile; import org.thingsboard.server.common.data.HasName; import org.thingsboard.server.common.data.alarm.AlarmInfo; @@ -43,7 +42,6 @@ import org.thingsboard.server.common.data.exception.ThingsboardException; import org.thingsboard.server.common.data.iot_hub.SolutionTemplateInstalledItemDescriptor; import org.thingsboard.server.common.data.kv.BaseDeleteTsKvQuery; import org.thingsboard.server.common.data.kv.DeleteTsKvQuery; -import org.thingsboard.server.common.data.page.PageLink; import org.thingsboard.server.common.data.page.TimePageLink; import org.thingsboard.server.common.data.EntityType; import org.thingsboard.server.common.data.StringUtils; @@ -153,12 +151,15 @@ import java.nio.file.SimpleFileVisitor; import java.nio.file.attribute.BasicFileAttributes; import java.time.ZonedDateTime; import java.util.ArrayList; +import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; +import java.util.LinkedHashMap; import java.util.List; import java.util.Map; +import java.util.Objects; import java.util.Set; import java.util.TreeMap; import java.util.concurrent.ExecutorService; @@ -179,6 +180,11 @@ import java.util.zip.ZipInputStream; @Slf4j public class DefaultSolutionService implements SolutionService { + private static final String BLANK_LINE = System.lineSeparator() + System.lineSeparator(); + private static final String CONFLICTS_INTRO = + "Some entities of the solution template already exist. Rename or delete them and install the template again:"; + private static final String RANDOM_NAME_PLACEHOLDER_PREFIX = "$random"; + @Value("${ui.solution_templates.docs_base_url:https://thingsboard.io/docs}") private String docsBaseUrl; @@ -293,71 +299,107 @@ public class DefaultSolutionService implements SolutionService { } } - private SolutionInstallResponse validateSolution(TenantId tenantId, Path tempDir) { - Map> alreadyExistingEntities = new HashMap<>(); - + /** + * Reports every entity of the template that would clash with an entity the tenant already has, naming each + * conflict, before anything is created. Returns {@code null} when the template can be installed as is. + * Package-private so the conflict detection can be unit-tested in isolation. + */ + SolutionInstallResponse validateSolution(TenantId tenantId, Path tempDir) { //TODO: check other entities. List ruleChains = loadListOfEntitiesIfFileExists(tempDir, "rule_chains.json", new TypeReference<>() { }); - if (!ruleChains.isEmpty()) { - for (ReferenceableEntityDefinition ruleChain : ruleChains) { - List savedRuleChains = ruleChainService.findTenantRuleChainsByType(tenantId, RuleChainType.CORE, new PageLink(1, 0, ruleChain.getName())).getData(); - if (savedRuleChains != null && !savedRuleChains.isEmpty()) { - alreadyExistingEntities.computeIfAbsent(EntityType.RULE_CHAIN, key -> new ArrayList<>()).add(savedRuleChains.get(0)); - } - } - } - List deviceProfiles = loadListOfEntitiesIfFileExists(tempDir, "device_profiles.json", new TypeReference<>() { }); deviceProfiles.addAll(loadListOfEntitiesFromDirectory(tempDir, "device_profiles", DeviceProfileDefinition.class)); - // Validate that entities with such name does not exist entities - if (!deviceProfiles.isEmpty()) { - for (DeviceProfile deviceProfile : deviceProfiles) { - DeviceProfile savedProfile = deviceProfileService.findDeviceProfileByName(tenantId, deviceProfile.getName()); - if (savedProfile != null) { - alreadyExistingEntities.computeIfAbsent(EntityType.DEVICE_PROFILE, key -> new ArrayList<>()).add(savedProfile); - } - } - } - List assetProfiles = loadListOfEntitiesIfFileExists(tempDir, "asset_profiles.json", new TypeReference<>() { }); assetProfiles.addAll(loadListOfEntitiesFromDirectory(tempDir, "asset_profiles", AssetProfileDefinition.class)); - // Validate that entities with such name does not exist entities - if (!assetProfiles.isEmpty()) { - for (AssetProfile assetProfile : assetProfiles) { - AssetProfile savedProfile = assetProfileService.findAssetProfileByName(tenantId, assetProfile.getName()); - if (savedProfile != null) { - alreadyExistingEntities.computeIfAbsent(EntityType.ASSET_PROFILE, key -> new ArrayList<>()).add(savedProfile); - } - } - } - + List customers = loadListOfEntitiesIfFileExists(tempDir, "customers.json", new TypeReference<>() { + }); List dashboards = loadListOfEntitiesIfFileExists(tempDir, "dashboards.json", new TypeReference<>() { }); - if (!dashboards.isEmpty()) { - for (DashboardDefinition dashboard : dashboards) { - List savedDashboards = dashboardService.findDashboardsByTenantId(tenantId, new PageLink(1, 0, dashboard.getName())).getData(); - if (savedDashboards != null && !savedDashboards.isEmpty()) { - alreadyExistingEntities.computeIfAbsent(EntityType.DASHBOARD, key -> new ArrayList<>()).add(savedDashboards.get(0)); - } + List assets = loadListOfEntitiesIfFileExists(tempDir, "assets.json", new TypeReference<>() { + }); + List devices = loadListOfEntitiesIfFileExists(tempDir, "devices.json", new TypeReference<>() { + }); + List edges = loadListOfEntitiesIfFileExists(tempDir, "edges.json", new TypeReference<>() { + }); + + // Insertion ordered, so that the reported sections keep the order the entities are provisioned in. + Map> conflicts = new LinkedHashMap<>(); + collectConflicts(conflicts, EntityType.RULE_CHAIN, ruleChains, ReferenceableEntityDefinition::getName, + name -> firstOrNull(ruleChainService.findTenantRuleChainsByTypeAndName(tenantId, RuleChainType.CORE, name))); + collectConflicts(conflicts, EntityType.DEVICE_PROFILE, deviceProfiles, DeviceProfile::getName, + name -> deviceProfileService.findDeviceProfileByName(tenantId, name)); + collectConflicts(conflicts, EntityType.ASSET_PROFILE, assetProfiles, AssetProfile::getName, + name -> assetProfileService.findAssetProfileByName(tenantId, name)); + collectConflicts(conflicts, EntityType.CUSTOMER, customers, CustomerDefinition::getName, + title -> isRandomizedAtInstall(title) ? null : customerService.findCustomerByTenantIdAndTitle(tenantId, title).orElse(null)); + collectConflicts(conflicts, EntityType.DASHBOARD, dashboards, DashboardDefinition::getName, + title -> dashboardService.findFirstDashboardInfoByTenantIdAndName(tenantId, title)); + collectConflicts(conflicts, EntityType.ASSET, assets, AssetDefinition::getName, + name -> assetService.findAssetByTenantIdAndName(tenantId, name)); + collectConflicts(conflicts, EntityType.DEVICE, devices, DeviceDefinition::getName, + name -> deviceService.findDeviceByTenantIdAndName(tenantId, name)); + collectConflicts(conflicts, EntityType.EDGE, edges, EdgeDefinition::getName, + name -> edgeService.findEdgeByTenantIdAndName(tenantId, name)); + + if (conflicts.isEmpty()) { + return null; + } + StringBuilder details = new StringBuilder(CONFLICTS_INTRO).append(BLANK_LINE); + conflicts.forEach((entityType, entities) -> appendConflicts(details, entityType, + entities.stream().map(HasName::getName).map(DefaultSolutionService::quoted).toList())); + + SolutionInstallResponse solutionInstallResponse = new SolutionInstallResponse(); + solutionInstallResponse.setSuccess(false); + solutionInstallResponse.setDetails(details.toString()); + return solutionInstallResponse; + } + + private void collectConflicts(Map> conflicts, EntityType entityType, List definitions, + Function nameExtractor, Function lookup) { + for (T definition : definitions) { + String name = nameExtractor.apply(definition); + if (StringUtils.isEmpty(name)) { + continue; + } + HasName existing = lookup.apply(name); + if (existing != null) { + conflicts.computeIfAbsent(entityType, key -> new ArrayList<>()).add(existing); } } - if (!alreadyExistingEntities.isEmpty()) { - SolutionInstallResponse solutionInstallResponse = new SolutionInstallResponse(); - StringBuilder detailsBuilder = new StringBuilder(); - detailsBuilder.append("## Validation failed").append(System.lineSeparator()).append(System.lineSeparator()); - alreadyExistingEntities.forEach((type, list) -> detailsBuilder.append("The following **").append(getTypeLabel(type)).append("** entities already exist: ") - .append(list.stream().map(HasName::getName).map(name -> "'" + name + "'").collect(Collectors.joining(","))).append(";") - .append(System.lineSeparator()).append(System.lineSeparator())); - solutionInstallResponse.setSuccess(false); - solutionInstallResponse.setDetails(detailsBuilder.toString()); - return solutionInstallResponse; - } else { - return null; + } + + /** + * Only customer titles, user names and attribute values go through {@link #randomize}, so a {@code $random} + * placeholder in a customer title is replaced at install time and there is nothing to check upfront. Names of + * every other entity are used as written, placeholder included, so those are looked up as is - skipping them + * here would let the install die on a DB constraint again. + */ + private static boolean isRandomizedAtInstall(String name) { + return name.contains(RANDOM_NAME_PLACEHOLDER_PREFIX); + } + + /** + * One markdown list item per entity type, so that the names of the conflicting entities are what the user reads, + * instead of the same sentence repeated for every type. + */ + private void appendConflicts(StringBuilder details, EntityType entityType, List conflictDescriptions) { + if (conflictDescriptions.isEmpty()) { + return; } + details.append("- **").append(entityType.getNormalName()).append("**: ") + .append(conflictDescriptions.stream().distinct().collect(Collectors.joining(", "))).append(System.lineSeparator()); + } + + private static String quoted(String value) { + return "'" + value + "'"; + } + + private static T firstOrNull(Collection data) { + return data == null || data.isEmpty() ? null : data.iterator().next(); } private SolutionInstallResponse doInstallSolution(User user, TenantId tenantId, String solutionId, Path tempDir, HttpServletRequest request) { @@ -1455,10 +1497,6 @@ public class DefaultSolutionService implements SolutionService { return String.valueOf(now.toInstant().toEpochMilli()); } - private String getTypeLabel(EntityType type) { - return type.name().toLowerCase().replace('_', ' '); - } - private T loadEntityIfFileExists(Path tempDir, String fileName, Class clazz) { Path filePath = tempDir.resolve("entities").resolve(fileName); if (Files.exists(filePath)) { @@ -1472,7 +1510,7 @@ public class DefaultSolutionService implements SolutionService { Path filePath = tempDir.resolve("entities").resolve(fileName); if (Files.exists(filePath)) { try { - return JacksonUtil.readValue(filePath.toFile(), typeReference); + return Objects.requireNonNullElseGet(JacksonUtil.readValue(filePath.toFile(), typeReference), ArrayList::new); } catch (Exception e) { throw new IllegalArgumentException("Invalid json file " + fileName + " data structure", e); } diff --git a/application/src/test/java/org/thingsboard/server/service/iot_hub/DefaultIotHubServiceTest.java b/application/src/test/java/org/thingsboard/server/service/iot_hub/DefaultIotHubServiceTest.java index c252b58103..bfe0db5750 100644 --- a/application/src/test/java/org/thingsboard/server/service/iot_hub/DefaultIotHubServiceTest.java +++ b/application/src/test/java/org/thingsboard/server/service/iot_hub/DefaultIotHubServiceTest.java @@ -344,6 +344,41 @@ class DefaultIotHubServiceTest { inOrder.verify(service).deleteInstalledItem(user, dep1Item.getId()); } + @Test + void installPlan_rootFails_errorMessageIsNotPrefixedWithTheItemName() throws Exception { + mockTenant(); + HttpServletRequest request = mock(HttpServletRequest.class); + String rootVersionId = UUID.randomUUID().toString(); + InstallPlanEntry root = willInstall(rootVersionId, true); + + when(iotHubInstalledItemService.findInstalledItemIdsByTenantIdAndItemIdIn(eq(tenantId), any())).thenReturn(List.of()); + doThrow(new IllegalStateException("install failed")).when(service).doInstallVersion(eq(user), eq(rootVersionId), any(), any()); + + InstallPlanResult result = service.installPlan(user, new InstallPlan(rootVersionId, List.of(root)), null, request); + + // the install dialog already shows "Failed to install ''" right above these details + assertThat(result.getErrorMessage()).isEqualTo("install failed"); + } + + @Test + void installPlan_dependencyFails_errorMessageNamesTheDependency() throws Exception { + mockTenant(); + HttpServletRequest request = mock(HttpServletRequest.class); + String depVersionId = UUID.randomUUID().toString(); + String rootVersionId = UUID.randomUUID().toString(); + InstallPlanEntry dep = willInstall(depVersionId, false); + InstallPlanEntry root = willInstall(rootVersionId, true); + + when(iotHubInstalledItemService.findInstalledItemIdsByTenantIdAndItemIdIn(eq(tenantId), any())).thenReturn(List.of()); + doThrow(new IllegalStateException("install failed")).when(service).doInstallVersion(eq(user), eq(depVersionId), any(), any()); + + InstallPlanResult result = service.installPlan(user, new InstallPlan(rootVersionId, List.of(dep, root)), null, request); + + // a failing dependency is not the item the dialog names, so it has to be named here + assertThat(result.getErrorMessage()).isEqualTo("Failed to install dependency 'Dep': install failed"); + verify(service, never()).doInstallVersion(eq(user), eq(rootVersionId), any(), any()); + } + @Test void installPlan_rollbackFailure_reportsNotFullyRolledBack() throws Exception { mockTenant(); diff --git a/application/src/test/java/org/thingsboard/server/service/solutions/DefaultSolutionServiceTest.java b/application/src/test/java/org/thingsboard/server/service/solutions/DefaultSolutionServiceTest.java new file mode 100644 index 0000000000..a8c5697a42 --- /dev/null +++ b/application/src/test/java/org/thingsboard/server/service/solutions/DefaultSolutionServiceTest.java @@ -0,0 +1,133 @@ +/** + * Copyright © 2016-2026 The Thingsboard Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.thingsboard.server.service.solutions; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.junit.jupiter.api.io.TempDir; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; +import org.thingsboard.server.common.data.Customer; +import org.thingsboard.server.common.data.DashboardInfo; +import org.thingsboard.server.common.data.Device; +import org.thingsboard.server.common.data.id.TenantId; +import org.thingsboard.server.dao.asset.AssetService; +import org.thingsboard.server.dao.customer.CustomerService; +import org.thingsboard.server.dao.dashboard.DashboardService; +import org.thingsboard.server.dao.device.DeviceService; +import org.thingsboard.server.service.solutions.data.solution.SolutionInstallResponse; + +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.Optional; +import java.util.UUID; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +@ExtendWith(MockitoExtension.class) +class DefaultSolutionServiceTest { + + private static final String CONFLICTS_INTRO = + "Some entities of the solution template already exist. Rename or delete them and install the template again:"; + + private final TenantId tenantId = TenantId.fromUUID(UUID.randomUUID()); + + @Mock + private CustomerService customerService; + @Mock + private DeviceService deviceService; + @Mock + private AssetService assetService; + @Mock + private DashboardService dashboardService; + + @InjectMocks + private DefaultSolutionService service; + + @TempDir + private Path tempDir; + + @Test + void testValidateSolutionNamesEveryConflictingEntity() throws IOException { + writeEntitiesFile("customers.json", "[{\"name\": \"Existing customer\"}, {\"name\": \"Customer $random\"}]"); + writeEntitiesFile("devices.json", "[{\"name\": \"Existing device\"}, {\"name\": \"New device\"}]"); + writeEntitiesFile("assets.json", "[{\"name\": \"New asset\"}]"); + + Customer customer = new Customer(); + customer.setTitle("Existing customer"); + Device device = new Device(); + device.setName("Existing device"); + + when(customerService.findCustomerByTenantIdAndTitle(tenantId, "Existing customer")).thenReturn(Optional.of(customer)); + when(assetService.findAssetByTenantIdAndName(tenantId, "New asset")).thenReturn(null); + when(deviceService.findDeviceByTenantIdAndName(tenantId, "Existing device")).thenReturn(device); + when(deviceService.findDeviceByTenantIdAndName(tenantId, "New device")).thenReturn(null); + + SolutionInstallResponse result = service.validateSolution(tenantId, tempDir); + + assertThat(result).isNotNull(); + assertThat(result.isSuccess()).isFalse(); + assertThat(result.getDetails().lines().toList()) + .containsSubsequence( + CONFLICTS_INTRO, + "- **Customer**: 'Existing customer'", + "- **Device**: 'Existing device'"); + // the randomized customer title and the entities that do not exist yet are not reported + assertThat(result.getDetails()) + .doesNotContain("Customer $random") + .doesNotContain("New device") + .doesNotContain("New asset"); + } + + @Test + void testValidateSolutionReportsConflictingDashboard() throws IOException { + writeEntitiesFile("dashboards.json", "[{\"name\": \"Overview\", \"file\": \"overview.json\"}]"); + + DashboardInfo dashboard = new DashboardInfo(); + dashboard.setTitle("Overview"); + when(dashboardService.findFirstDashboardInfoByTenantIdAndName(tenantId, "Overview")).thenReturn(dashboard); + + SolutionInstallResponse result = service.validateSolution(tenantId, tempDir); + + assertThat(result).isNotNull(); + assertThat(result.getDetails().lines().toList()) + .containsSubsequence(CONFLICTS_INTRO, "- **Dashboard**: 'Overview'"); + } + + @Test + void testValidateSolutionWithoutConflicts() throws IOException { + writeEntitiesFile("devices.json", "[{\"name\": \"New device\"}]"); + when(deviceService.findDeviceByTenantIdAndName(tenantId, "New device")).thenReturn(null); + + assertThat(service.validateSolution(tenantId, tempDir)).isNull(); + } + + @Test + void testValidateSolutionWithoutEntityFiles() { + assertThat(service.validateSolution(tenantId, tempDir)).isNull(); + verifyNoInteractions(customerService, deviceService, assetService, dashboardService); + } + + private void writeEntitiesFile(String fileName, String content) throws IOException { + Path entitiesDir = Files.createDirectories(tempDir.resolve("entities")); + Files.writeString(entitiesDir.resolve(fileName), content); + } + +} From 811713c338eb4e91619c549dabf92cbffdf16f7f Mon Sep 17 00:00:00 2001 From: dpinkevych Date: Mon, 7 Sep 2026 15:12:03 +0300 Subject: [PATCH 011/159] compose the failed dependency sentence in the dialog, not in the service The service was pre-composing "Failed to install dependency '':", which can never be translated and made the backend depend on the dialog already printing the root item above the details. It now reports the failure itself, and the dialog prefixes a localized sentence when the entry that failed is not the root. --- .../service/iot_hub/DefaultIotHubService.java | 5 +---- .../service/solutions/DefaultSolutionService.java | 5 ----- .../service/iot_hub/DefaultIotHubServiceTest.java | 15 ++++++++++----- .../iot-hub/iot-hub-install-dialog.component.ts | 6 ++++++ .../src/assets/locale/locale.constant-en_US.json | 1 + 5 files changed, 18 insertions(+), 14 deletions(-) diff --git a/application/src/main/java/org/thingsboard/server/service/iot_hub/DefaultIotHubService.java b/application/src/main/java/org/thingsboard/server/service/iot_hub/DefaultIotHubService.java index 7f4bdfe089..db3f1d4549 100644 --- a/application/src/main/java/org/thingsboard/server/service/iot_hub/DefaultIotHubService.java +++ b/application/src/main/java/org/thingsboard/server/service/iot_hub/DefaultIotHubService.java @@ -1011,10 +1011,7 @@ public class DefaultIotHubService implements IotHubService { boolean rolledBack = rollbackInstalledItems(user, rollbackIds); result.setSuccess(false); result.setRolledBack(rolledBack); - // The dialog already says "Failed to install ''" above the details, so only a - // failing dependency is worth naming here - for the root entry that would just repeat itself. - result.setErrorMessage(entry.isRoot() ? e.getMessage() - : "Failed to install dependency '" + entry.getName() + "': " + e.getMessage()); + result.setErrorMessage(e.getMessage()); result.setEntries(resultEntries); result.setMissingItemIds(missingItemIds); return result; diff --git a/application/src/main/java/org/thingsboard/server/service/solutions/DefaultSolutionService.java b/application/src/main/java/org/thingsboard/server/service/solutions/DefaultSolutionService.java index b2c48f22b7..4c09f16e4c 100644 --- a/application/src/main/java/org/thingsboard/server/service/solutions/DefaultSolutionService.java +++ b/application/src/main/java/org/thingsboard/server/service/solutions/DefaultSolutionService.java @@ -299,11 +299,6 @@ public class DefaultSolutionService implements SolutionService { } } - /** - * Reports every entity of the template that would clash with an entity the tenant already has, naming each - * conflict, before anything is created. Returns {@code null} when the template can be installed as is. - * Package-private so the conflict detection can be unit-tested in isolation. - */ SolutionInstallResponse validateSolution(TenantId tenantId, Path tempDir) { //TODO: check other entities. diff --git a/application/src/test/java/org/thingsboard/server/service/iot_hub/DefaultIotHubServiceTest.java b/application/src/test/java/org/thingsboard/server/service/iot_hub/DefaultIotHubServiceTest.java index bfe0db5750..c48e5896a1 100644 --- a/application/src/test/java/org/thingsboard/server/service/iot_hub/DefaultIotHubServiceTest.java +++ b/application/src/test/java/org/thingsboard/server/service/iot_hub/DefaultIotHubServiceTest.java @@ -345,7 +345,7 @@ class DefaultIotHubServiceTest { } @Test - void installPlan_rootFails_errorMessageIsNotPrefixedWithTheItemName() throws Exception { + void installPlan_errorMessageIsTheFailureItselfWithoutAnyPrefix() throws Exception { mockTenant(); HttpServletRequest request = mock(HttpServletRequest.class); String rootVersionId = UUID.randomUUID().toString(); @@ -356,12 +356,12 @@ class DefaultIotHubServiceTest { InstallPlanResult result = service.installPlan(user, new InstallPlan(rootVersionId, List.of(root)), null, request); - // the install dialog already shows "Failed to install ''" right above these details + // the sentence around the failure belongs to the dialog, which localizes it assertThat(result.getErrorMessage()).isEqualTo("install failed"); } @Test - void installPlan_dependencyFails_errorMessageNamesTheDependency() throws Exception { + void installPlan_dependencyFails_failureIsReportedOnTheEntryAndAsTheResultMessage() throws Exception { mockTenant(); HttpServletRequest request = mock(HttpServletRequest.class); String depVersionId = UUID.randomUUID().toString(); @@ -374,8 +374,13 @@ class DefaultIotHubServiceTest { InstallPlanResult result = service.installPlan(user, new InstallPlan(rootVersionId, List.of(dep, root)), null, request); - // a failing dependency is not the item the dialog names, so it has to be named here - assertThat(result.getErrorMessage()).isEqualTo("Failed to install dependency 'Dep': install failed"); + // the dialog names the failing dependency itself, from the entry it finds in the result + assertThat(result.getErrorMessage()).isEqualTo("install failed"); + assertThat(result.getEntries()).anySatisfy(entry -> { + assertThat(entry.getName()).isEqualTo("Dep"); + assertThat(entry.isRoot()).isFalse(); + assertThat(entry.getErrorMessage()).isEqualTo("install failed"); + }); verify(service, never()).doInstallVersion(eq(user), eq(rootVersionId), any(), any()); } diff --git a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-install-dialog.component.ts b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-install-dialog.component.ts index 7de5717b66..78a36c074c 100644 --- a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-install-dialog.component.ts +++ b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-install-dialog.component.ts @@ -345,6 +345,12 @@ export class TbIotHubInstallDialogComponent extends DialogComponent !entry.root && entry.errorMessage); + if (failedDependency) { + message = this.translate.instant('iot-hub.install-dependency-error', { name: failedDependency.name }) + ' ' + message; + } // A failed cascade rolls back the items installed so far. When something was actually being // installed and the rollback came back partial (rolledBack === false), some entities are left // behind — tell the admin so they know manual cleanup may be needed. The willInstall guard diff --git a/ui-ngx/src/assets/locale/locale.constant-en_US.json b/ui-ngx/src/assets/locale/locale.constant-en_US.json index 052d7ca046..19d2ac7484 100644 --- a/ui-ngx/src/assets/locale/locale.constant-en_US.json +++ b/ui-ngx/src/assets/locale/locale.constant-en_US.json @@ -4337,6 +4337,7 @@ "goto-main-dashboard": "Go to main dashboard", "install-error-title": "Installation Failed", "install-error-message": "Failed to install '{{name}}'.", + "install-dependency-error": "Failed to install the dependency '{{name}}':", "install-plan-title": "Install '{{name}}' and its dependencies", "install-plan-will-install": "{{count}} item(s) will be installed.", "install-plan-will-update": "{{count}} item(s) already installed and will be skipped.", From a6e3313032ad54ceadf18e2ba446cfe9e7131ac0 Mon Sep 17 00:00:00 2001 From: dpinkevych Date: Mon, 7 Sep 2026 15:12:03 +0300 Subject: [PATCH 012/159] address review comments on the install validation - rule chains are looked up under the name from the rule chain file, the same source the install uses, instead of the name in rule_chains.json - the details end with a blank line, so the partial rollback warning the dialog appends does not land inside the last list item - an exception without a message falls back to its type, so the failing entry is still named - the dependency prefix is only added when the server sent an error message, since the fallback sentence names the root item --- .../service/iot_hub/DefaultIotHubService.java | 8 +++-- .../solutions/DefaultSolutionService.java | 22 ++++++++++++- .../iot_hub/DefaultIotHubServiceTest.java | 18 ++++++++++ .../solutions/DefaultSolutionServiceTest.java | 33 ++++++++++++++++++- .../iot-hub-install-dialog.component.ts | 10 +++--- 5 files changed, 83 insertions(+), 8 deletions(-) diff --git a/application/src/main/java/org/thingsboard/server/service/iot_hub/DefaultIotHubService.java b/application/src/main/java/org/thingsboard/server/service/iot_hub/DefaultIotHubService.java index db3f1d4549..b55173715f 100644 --- a/application/src/main/java/org/thingsboard/server/service/iot_hub/DefaultIotHubService.java +++ b/application/src/main/java/org/thingsboard/server/service/iot_hub/DefaultIotHubService.java @@ -21,6 +21,7 @@ import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Service; import org.thingsboard.common.util.JacksonUtil; +import org.thingsboard.server.common.data.StringUtils; import org.thingsboard.server.common.data.asset.AssetProfile; import org.thingsboard.server.common.data.Dashboard; import org.thingsboard.server.common.data.DeviceProfile; @@ -1006,12 +1007,15 @@ public class DefaultIotHubService implements IotHubService { } catch (Exception e) { log.error("[{}] Cascade install failed at entry {} ({}): {}", tenantId, entry.getName(), entry.getVersionId(), e.getMessage(), e); - resultEntry.setErrorMessage(e.getMessage()); + // an exception without a message would leave both the entry and the result blank, + // and the dialog would have nothing to name the failing entry by + String failure = StringUtils.isEmpty(e.getMessage()) ? e.getClass().getSimpleName() : e.getMessage(); + resultEntry.setErrorMessage(failure); resultEntries.add(resultEntry); boolean rolledBack = rollbackInstalledItems(user, rollbackIds); result.setSuccess(false); result.setRolledBack(rolledBack); - result.setErrorMessage(e.getMessage()); + result.setErrorMessage(failure); result.setEntries(resultEntries); result.setMissingItemIds(missingItemIds); return result; diff --git a/application/src/main/java/org/thingsboard/server/service/solutions/DefaultSolutionService.java b/application/src/main/java/org/thingsboard/server/service/solutions/DefaultSolutionService.java index 4c09f16e4c..c7982ab8fc 100644 --- a/application/src/main/java/org/thingsboard/server/service/solutions/DefaultSolutionService.java +++ b/application/src/main/java/org/thingsboard/server/service/solutions/DefaultSolutionService.java @@ -323,7 +323,7 @@ public class DefaultSolutionService implements SolutionService { // Insertion ordered, so that the reported sections keep the order the entities are provisioned in. Map> conflicts = new LinkedHashMap<>(); - collectConflicts(conflicts, EntityType.RULE_CHAIN, ruleChains, ReferenceableEntityDefinition::getName, + collectConflicts(conflicts, EntityType.RULE_CHAIN, ruleChains, definition -> ruleChainName(tempDir, definition), name -> firstOrNull(ruleChainService.findTenantRuleChainsByTypeAndName(tenantId, RuleChainType.CORE, name))); collectConflicts(conflicts, EntityType.DEVICE_PROFILE, deviceProfiles, DeviceProfile::getName, name -> deviceProfileService.findDeviceProfileByName(tenantId, name)); @@ -347,6 +347,9 @@ public class DefaultSolutionService implements SolutionService { conflicts.forEach((entityType, entities) -> appendConflicts(details, entityType, entities.stream().map(HasName::getName).map(DefaultSolutionService::quoted).toList())); + // the dialog appends its own sentences to these details, so the list has to end with a blank line + details.append(System.lineSeparator()); + SolutionInstallResponse solutionInstallResponse = new SolutionInstallResponse(); solutionInstallResponse.setSuccess(false); solutionInstallResponse.setDetails(details.toString()); @@ -393,6 +396,23 @@ public class DefaultSolutionService implements SolutionService { return "'" + value + "'"; } + /** + * The provisioned rule chain takes its name from the rule chain file, not from the name in rule_chains.json, + * so the conflict has to be looked up under the name the install will actually create. + */ + private String ruleChainName(Path tempDir, ReferenceableEntityDefinition definition) { + if (StringUtils.isEmpty(definition.getFile())) { + return null; + } + Path ruleChainPath = tempDir.resolve("rule_chains").resolve(definition.getFile()); + if (!Files.exists(ruleChainPath)) { + // provisionRuleChains logs and skips such a definition, so there is nothing to validate + return null; + } + JsonNode ruleChain = JacksonUtil.toJsonNode(ruleChainPath).get("ruleChain"); + return ruleChain != null && ruleChain.hasNonNull("name") ? ruleChain.get("name").asText() : null; + } + private static T firstOrNull(Collection data) { return data == null || data.isEmpty() ? null : data.iterator().next(); } diff --git a/application/src/test/java/org/thingsboard/server/service/iot_hub/DefaultIotHubServiceTest.java b/application/src/test/java/org/thingsboard/server/service/iot_hub/DefaultIotHubServiceTest.java index c48e5896a1..e34fd92d3c 100644 --- a/application/src/test/java/org/thingsboard/server/service/iot_hub/DefaultIotHubServiceTest.java +++ b/application/src/test/java/org/thingsboard/server/service/iot_hub/DefaultIotHubServiceTest.java @@ -384,6 +384,24 @@ class DefaultIotHubServiceTest { verify(service, never()).doInstallVersion(eq(user), eq(rootVersionId), any(), any()); } + @Test + void installPlan_failureWithoutMessage_reportsTheExceptionType() throws Exception { + mockTenant(); + HttpServletRequest request = mock(HttpServletRequest.class); + String rootVersionId = UUID.randomUUID().toString(); + InstallPlanEntry root = willInstall(rootVersionId, true); + + when(iotHubInstalledItemService.findInstalledItemIdsByTenantIdAndItemIdIn(eq(tenantId), any())).thenReturn(List.of()); + doThrow(new NullPointerException()).when(service).doInstallVersion(eq(user), eq(rootVersionId), any(), any()); + + InstallPlanResult result = service.installPlan(user, new InstallPlan(rootVersionId, List.of(root)), null, request); + + // the dialog looks the failing entry up by its error message, so it must never be blank + assertThat(result.getErrorMessage()).isEqualTo("NullPointerException"); + assertThat(result.getEntries()).allSatisfy(entry -> + assertThat(entry.getErrorMessage()).isEqualTo("NullPointerException")); + } + @Test void installPlan_rollbackFailure_reportsNotFullyRolledBack() throws Exception { mockTenant(); diff --git a/application/src/test/java/org/thingsboard/server/service/solutions/DefaultSolutionServiceTest.java b/application/src/test/java/org/thingsboard/server/service/solutions/DefaultSolutionServiceTest.java index a8c5697a42..04096c3cc3 100644 --- a/application/src/test/java/org/thingsboard/server/service/solutions/DefaultSolutionServiceTest.java +++ b/application/src/test/java/org/thingsboard/server/service/solutions/DefaultSolutionServiceTest.java @@ -25,15 +25,19 @@ import org.thingsboard.server.common.data.Customer; import org.thingsboard.server.common.data.DashboardInfo; import org.thingsboard.server.common.data.Device; import org.thingsboard.server.common.data.id.TenantId; +import org.thingsboard.server.common.data.rule.RuleChain; +import org.thingsboard.server.common.data.rule.RuleChainType; import org.thingsboard.server.dao.asset.AssetService; import org.thingsboard.server.dao.customer.CustomerService; import org.thingsboard.server.dao.dashboard.DashboardService; import org.thingsboard.server.dao.device.DeviceService; +import org.thingsboard.server.dao.rule.RuleChainService; import org.thingsboard.server.service.solutions.data.solution.SolutionInstallResponse; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; +import java.util.List; import java.util.Optional; import java.util.UUID; @@ -57,6 +61,8 @@ class DefaultSolutionServiceTest { private AssetService assetService; @Mock private DashboardService dashboardService; + @Mock + private RuleChainService ruleChainService; @InjectMocks private DefaultSolutionService service; @@ -89,6 +95,8 @@ class DefaultSolutionServiceTest { CONFLICTS_INTRO, "- **Customer**: 'Existing customer'", "- **Device**: 'Existing device'"); + // the dialog appends its own sentences, so the details have to end with a blank line + assertThat(result.getDetails()).endsWith(System.lineSeparator() + System.lineSeparator()); // the randomized customer title and the entities that do not exist yet are not reported assertThat(result.getDetails()) .doesNotContain("Customer $random") @@ -111,6 +119,23 @@ class DefaultSolutionServiceTest { .containsSubsequence(CONFLICTS_INTRO, "- **Dashboard**: 'Overview'"); } + @Test + void testValidateSolutionUsesTheRuleChainNameFromTheRuleChainFile() throws IOException { + writeEntitiesFile("rule_chains.json", "[{\"name\": \"Name in the definition\", \"file\": \"rc.json\"}]"); + writeFile("rule_chains/rc.json", "{\"ruleChain\": {\"name\": \"Name the install creates\"}}"); + + RuleChain ruleChain = new RuleChain(); + ruleChain.setName("Name the install creates"); + when(ruleChainService.findTenantRuleChainsByTypeAndName(tenantId, RuleChainType.CORE, "Name the install creates")) + .thenReturn(List.of(ruleChain)); + + SolutionInstallResponse result = service.validateSolution(tenantId, tempDir); + + assertThat(result).isNotNull(); + assertThat(result.getDetails().lines().toList()) + .containsSubsequence(CONFLICTS_INTRO, "- **Rule chain**: 'Name the install creates'"); + } + @Test void testValidateSolutionWithoutConflicts() throws IOException { writeEntitiesFile("devices.json", "[{\"name\": \"New device\"}]"); @@ -122,7 +147,13 @@ class DefaultSolutionServiceTest { @Test void testValidateSolutionWithoutEntityFiles() { assertThat(service.validateSolution(tenantId, tempDir)).isNull(); - verifyNoInteractions(customerService, deviceService, assetService, dashboardService); + verifyNoInteractions(customerService, deviceService, assetService, dashboardService, ruleChainService); + } + + private void writeFile(String relativePath, String content) throws IOException { + Path file = tempDir.resolve(relativePath); + Files.createDirectories(file.getParent()); + Files.writeString(file, content); } private void writeEntitiesFile(String fileName, String content) throws IOException { diff --git a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-install-dialog.component.ts b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-install-dialog.component.ts index 78a36c074c..06dbb271e0 100644 --- a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-install-dialog.component.ts +++ b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-install-dialog.component.ts @@ -344,10 +344,12 @@ export class TbIotHubInstallDialogComponent extends DialogComponent !entry.root && entry.errorMessage); + const serverError = result.errorMessage; + let message = serverError || this.translate.instant('iot-hub.install-error', { name: this.item.name }); + // The title already names the item being installed, so only a failing dependency has to be named + // here - and only when the server reported the failure, since the fallback above names the root. + const failedDependency = serverError + ? (result.entries ?? []).find(entry => !entry.root && entry.errorMessage) : undefined; if (failedDependency) { message = this.translate.instant('iot-hub.install-dependency-error', { name: failedDependency.name }) + ' ' + message; } From 6fe4852f9b953e9d73ac009de56031550f4b650a Mon Sep 17 00:00:00 2001 From: dpinkevych Date: Mon, 7 Sep 2026 15:56:03 +0300 Subject: [PATCH 013/159] address the second review pass on the install validation - the dialog no longer mistakes a MISSING plan entry for the failing one: such entries carry an error message of their own with no name, so the lookup now also requires the WILL_INSTALL status - the whole dependency sentence lives in the locale bundle as one key with a name and an error parameter, instead of a fragment glued to the server message, and the partial rollback warning is appended as its own paragraph by the dialog rather than relying on the details ending with a blank line - a rule chain is validated under the type from the rule chain file too, so an EDGE chain is no longer looked up among the CORE ones - names are deduplicated before the lookup rather than when formatting, so a template repeating a name queries once - the entity type and the name come from the definition itself for the five lists that carry both, which removes the pairing hazard - ExceptionUtil.getMessage replaces the hand-rolled fallback, and the single-use firstOrNull helper is inlined - the dashboard check moved after the device one to match the provision order the comment claims, and the unreachable empty-list guard is gone - tests cover both profile types, edges, the rule chain type and its two unresolvable-name branches, the deduplicated lookup and a json file holding null --- .../service/iot_hub/DefaultIotHubService.java | 10 +- .../solutions/DefaultSolutionService.java | 130 ++++++++++-------- .../solutions/DefaultSolutionServiceTest.java | 88 +++++++++++- .../iot-hub-install-dialog.component.ts | 14 +- .../assets/locale/locale.constant-en_US.json | 2 +- 5 files changed, 173 insertions(+), 71 deletions(-) diff --git a/application/src/main/java/org/thingsboard/server/service/iot_hub/DefaultIotHubService.java b/application/src/main/java/org/thingsboard/server/service/iot_hub/DefaultIotHubService.java index 1e41211cb2..f7f5fae4a5 100644 --- a/application/src/main/java/org/thingsboard/server/service/iot_hub/DefaultIotHubService.java +++ b/application/src/main/java/org/thingsboard/server/service/iot_hub/DefaultIotHubService.java @@ -20,8 +20,8 @@ import jakarta.servlet.http.HttpServletRequest; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Service; +import org.thingsboard.common.util.ExceptionUtil; import org.thingsboard.common.util.JacksonUtil; -import org.thingsboard.server.common.data.StringUtils; import org.thingsboard.server.common.data.asset.AssetProfile; import org.thingsboard.server.common.data.Dashboard; import org.thingsboard.server.common.data.DeviceProfile; @@ -948,15 +948,13 @@ public class DefaultIotHubService implements IotHubService { } catch (Exception e) { log.error("[{}] Cascade install failed at entry {} ({}): {}", tenantId, entry.getName(), entry.getVersionId(), e.getMessage(), e); - // an exception without a message would leave both the entry and the result blank, - // and the dialog would have nothing to name the failing entry by - String failure = StringUtils.isEmpty(e.getMessage()) ? e.getClass().getSimpleName() : e.getMessage(); - resultEntry.setErrorMessage(failure); + String failureMessage = ExceptionUtil.getMessage(e); + resultEntry.setErrorMessage(failureMessage); resultEntries.add(resultEntry); boolean rolledBack = rollbackInstalledItems(user, rollbackIds); result.setSuccess(false); result.setRolledBack(rolledBack); - result.setErrorMessage(failure); + result.setErrorMessage(failureMessage); result.setEntries(resultEntries); result.setMissingItemIds(missingItemIds); return result; diff --git a/application/src/main/java/org/thingsboard/server/service/solutions/DefaultSolutionService.java b/application/src/main/java/org/thingsboard/server/service/solutions/DefaultSolutionService.java index 216960f4fe..cdeb9c06af 100644 --- a/application/src/main/java/org/thingsboard/server/service/solutions/DefaultSolutionService.java +++ b/application/src/main/java/org/thingsboard/server/service/solutions/DefaultSolutionService.java @@ -124,6 +124,7 @@ import org.thingsboard.server.service.solutions.data.definition.UserDefinition; import org.thingsboard.server.service.solutions.data.definition.DashboardDefinition; import org.thingsboard.server.service.solutions.data.definition.DeviceProfileDefinition; import org.thingsboard.server.service.solutions.data.definition.EdgeDefinition; +import org.thingsboard.server.service.solutions.data.definition.EntityDefinition; import org.thingsboard.server.service.solutions.data.definition.RelationDefinition; import org.thingsboard.server.service.solutions.data.definition.ReferenceableEntityDefinition; import org.thingsboard.server.service.solutions.data.definition.TenantDefinition; @@ -181,7 +182,7 @@ public class DefaultSolutionService implements SolutionService { private static final String BLANK_LINE = System.lineSeparator() + System.lineSeparator(); private static final String CONFLICTS_INTRO = "Some entities of the solution template already exist. Rename or delete them and install the template again:"; - private static final String RANDOM_NAME_PLACEHOLDER_PREFIX = "$random"; + private static final String RANDOM_PLACEHOLDER = "$random"; @Value("${ui.solution_templates.docs_base_url:https://thingsboard.io/docs}") private String docsBaseUrl; @@ -321,32 +322,23 @@ public class DefaultSolutionService implements SolutionService { // Insertion ordered, so that the reported sections keep the order the entities are provisioned in. Map> conflicts = new LinkedHashMap<>(); - collectConflicts(conflicts, EntityType.RULE_CHAIN, ruleChains, definition -> ruleChainName(tempDir, definition), - name -> firstOrNull(ruleChainService.findTenantRuleChainsByTypeAndName(tenantId, RuleChainType.CORE, name))); + collectRuleChainConflicts(conflicts, tenantId, tempDir, ruleChains); collectConflicts(conflicts, EntityType.DEVICE_PROFILE, deviceProfiles, DeviceProfile::getName, name -> deviceProfileService.findDeviceProfileByName(tenantId, name)); collectConflicts(conflicts, EntityType.ASSET_PROFILE, assetProfiles, AssetProfile::getName, name -> assetProfileService.findAssetProfileByName(tenantId, name)); - collectConflicts(conflicts, EntityType.CUSTOMER, customers, CustomerDefinition::getName, - title -> isRandomizedAtInstall(title) ? null : customerService.findCustomerByTenantIdAndTitle(tenantId, title).orElse(null)); - collectConflicts(conflicts, EntityType.DASHBOARD, dashboards, DashboardDefinition::getName, - title -> dashboardService.findFirstDashboardInfoByTenantIdAndName(tenantId, title)); - collectConflicts(conflicts, EntityType.ASSET, assets, AssetDefinition::getName, - name -> assetService.findAssetByTenantIdAndName(tenantId, name)); - collectConflicts(conflicts, EntityType.DEVICE, devices, DeviceDefinition::getName, - name -> deviceService.findDeviceByTenantIdAndName(tenantId, name)); - collectConflicts(conflicts, EntityType.EDGE, edges, EdgeDefinition::getName, - name -> edgeService.findEdgeByTenantIdAndName(tenantId, name)); + collectConflicts(conflicts, customers, + title -> isRandomizedCustomerTitle(title) ? null : customerService.findCustomerByTenantIdAndTitle(tenantId, title).orElse(null)); + collectConflicts(conflicts, assets, name -> assetService.findAssetByTenantIdAndName(tenantId, name)); + collectConflicts(conflicts, devices, name -> deviceService.findDeviceByTenantIdAndName(tenantId, name)); + collectConflicts(conflicts, dashboards, title -> dashboardService.findFirstDashboardInfoByTenantIdAndName(tenantId, title)); + collectConflicts(conflicts, edges, name -> edgeService.findEdgeByTenantIdAndName(tenantId, name)); if (conflicts.isEmpty()) { return null; } StringBuilder details = new StringBuilder(CONFLICTS_INTRO).append(BLANK_LINE); - conflicts.forEach((entityType, entities) -> appendConflicts(details, entityType, - entities.stream().map(HasName::getName).map(DefaultSolutionService::quoted).toList())); - - // the dialog appends its own sentences to these details, so the list has to end with a blank line - details.append(System.lineSeparator()); + conflicts.forEach((entityType, entities) -> appendConflicts(details, entityType, entities)); SolutionInstallResponse solutionInstallResponse = new SolutionInstallResponse(); solutionInstallResponse.setSuccess(false); @@ -354,65 +346,91 @@ public class DefaultSolutionService implements SolutionService { return solutionInstallResponse; } + /** + * The entity type and the name both come from the definition, so a list can not end up checked against the + * wrong type by mistake. + */ + private void collectConflicts(Map> conflicts, List definitions, + Function lookup) { + Set checked = new HashSet<>(); + for (EntityDefinition definition : definitions) { + if (checked.add(definition.getName())) { + collectConflict(conflicts, definition.getEntityType(), definition.getName(), lookup); + } + } + } + private void collectConflicts(Map> conflicts, EntityType entityType, List definitions, Function nameExtractor, Function lookup) { + Set checked = new HashSet<>(); for (T definition : definitions) { String name = nameExtractor.apply(definition); - if (StringUtils.isEmpty(name)) { + if (checked.add(name)) { + collectConflict(conflicts, entityType, name, lookup); + } + } + } + + private void collectConflict(Map> conflicts, EntityType entityType, String name, + Function lookup) { + if (StringUtils.isEmpty(name)) { + return; + } + HasName existing = lookup.apply(name); + if (existing != null) { + conflicts.computeIfAbsent(entityType, key -> new ArrayList<>()).add(existing); + } + } + + /** + * A rule chain is created from the rule chain file, so both the name and the type of the chain the install will + * produce live there - the name in rule_chains.json is only a reference and the type defaults to CORE. + */ + private void collectRuleChainConflicts(Map> conflicts, TenantId tenantId, Path tempDir, + List definitions) { + Set checked = new HashSet<>(); + for (ReferenceableEntityDefinition definition : definitions) { + if (StringUtils.isEmpty(definition.getFile())) { + continue; + } + Path ruleChainPath = tempDir.resolve("rule_chains").resolve(definition.getFile()); + if (!Files.exists(ruleChainPath)) { + // provisionRuleChains logs and skips such a definition, so there is nothing to validate continue; } - HasName existing = lookup.apply(name); - if (existing != null) { - conflicts.computeIfAbsent(entityType, key -> new ArrayList<>()).add(existing); + JsonNode ruleChain = JacksonUtil.toJsonNode(ruleChainPath).get("ruleChain"); + if (ruleChain == null || !ruleChain.hasNonNull("name")) { + continue; + } + RuleChainType type = ruleChain.hasNonNull("type") + ? RuleChainType.valueOf(ruleChain.get("type").asText()) : RuleChainType.CORE; + String name = ruleChain.get("name").asText(); + if (!checked.add(type + name)) { + continue; } + collectConflict(conflicts, EntityType.RULE_CHAIN, name, + ignored -> ruleChainService.findTenantRuleChainsByTypeAndName(tenantId, type, name) + .stream().findFirst().orElse(null)); } } /** * Only customer titles, user names and attribute values go through {@link #randomize}, so a {@code $random} * placeholder in a customer title is replaced at install time and there is nothing to check upfront. Names of - * every other entity are used as written, placeholder included, so those are looked up as is - skipping them - * here would let the install die on a DB constraint again. + * every other entity are used as written, placeholder included, and must be looked up as is. */ - private static boolean isRandomizedAtInstall(String name) { - return name.contains(RANDOM_NAME_PLACEHOLDER_PREFIX); + private static boolean isRandomizedCustomerTitle(String title) { + return title.contains(RANDOM_PLACEHOLDER); } /** * One markdown list item per entity type, so that the names of the conflicting entities are what the user reads, * instead of the same sentence repeated for every type. */ - private void appendConflicts(StringBuilder details, EntityType entityType, List conflictDescriptions) { - if (conflictDescriptions.isEmpty()) { - return; - } + private void appendConflicts(StringBuilder details, EntityType entityType, List entities) { details.append("- **").append(entityType.getNormalName()).append("**: ") - .append(conflictDescriptions.stream().distinct().collect(Collectors.joining(", "))).append(System.lineSeparator()); - } - - private static String quoted(String value) { - return "'" + value + "'"; - } - - /** - * The provisioned rule chain takes its name from the rule chain file, not from the name in rule_chains.json, - * so the conflict has to be looked up under the name the install will actually create. - */ - private String ruleChainName(Path tempDir, ReferenceableEntityDefinition definition) { - if (StringUtils.isEmpty(definition.getFile())) { - return null; - } - Path ruleChainPath = tempDir.resolve("rule_chains").resolve(definition.getFile()); - if (!Files.exists(ruleChainPath)) { - // provisionRuleChains logs and skips such a definition, so there is nothing to validate - return null; - } - JsonNode ruleChain = JacksonUtil.toJsonNode(ruleChainPath).get("ruleChain"); - return ruleChain != null && ruleChain.hasNonNull("name") ? ruleChain.get("name").asText() : null; - } - - private static T firstOrNull(Collection data) { - return data == null || data.isEmpty() ? null : data.iterator().next(); + .append(entities.stream().map(entity -> "'" + entity.getName() + "'").collect(Collectors.joining(", "))) + .append(System.lineSeparator()); } private SolutionInstallResponse doInstallSolution(User user, TenantId tenantId, String solutionId, Path tempDir, HttpServletRequest request) { diff --git a/application/src/test/java/org/thingsboard/server/service/solutions/DefaultSolutionServiceTest.java b/application/src/test/java/org/thingsboard/server/service/solutions/DefaultSolutionServiceTest.java index 04096c3cc3..d89012057b 100644 --- a/application/src/test/java/org/thingsboard/server/service/solutions/DefaultSolutionServiceTest.java +++ b/application/src/test/java/org/thingsboard/server/service/solutions/DefaultSolutionServiceTest.java @@ -24,13 +24,19 @@ import org.mockito.junit.jupiter.MockitoExtension; import org.thingsboard.server.common.data.Customer; import org.thingsboard.server.common.data.DashboardInfo; import org.thingsboard.server.common.data.Device; +import org.thingsboard.server.common.data.DeviceProfile; +import org.thingsboard.server.common.data.asset.AssetProfile; +import org.thingsboard.server.common.data.edge.Edge; import org.thingsboard.server.common.data.id.TenantId; import org.thingsboard.server.common.data.rule.RuleChain; import org.thingsboard.server.common.data.rule.RuleChainType; +import org.thingsboard.server.dao.asset.AssetProfileService; import org.thingsboard.server.dao.asset.AssetService; import org.thingsboard.server.dao.customer.CustomerService; import org.thingsboard.server.dao.dashboard.DashboardService; +import org.thingsboard.server.dao.device.DeviceProfileService; import org.thingsboard.server.dao.device.DeviceService; +import org.thingsboard.server.dao.edge.EdgeService; import org.thingsboard.server.dao.rule.RuleChainService; import org.thingsboard.server.service.solutions.data.solution.SolutionInstallResponse; @@ -42,6 +48,8 @@ import java.util.Optional; import java.util.UUID; import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoInteractions; import static org.mockito.Mockito.when; @@ -63,6 +71,12 @@ class DefaultSolutionServiceTest { private DashboardService dashboardService; @Mock private RuleChainService ruleChainService; + @Mock + private DeviceProfileService deviceProfileService; + @Mock + private AssetProfileService assetProfileService; + @Mock + private EdgeService edgeService; @InjectMocks private DefaultSolutionService service; @@ -95,8 +109,6 @@ class DefaultSolutionServiceTest { CONFLICTS_INTRO, "- **Customer**: 'Existing customer'", "- **Device**: 'Existing device'"); - // the dialog appends its own sentences, so the details have to end with a blank line - assertThat(result.getDetails()).endsWith(System.lineSeparator() + System.lineSeparator()); // the randomized customer title and the entities that do not exist yet are not reported assertThat(result.getDetails()) .doesNotContain("Customer $random") @@ -136,6 +148,78 @@ class DefaultSolutionServiceTest { .containsSubsequence(CONFLICTS_INTRO, "- **Rule chain**: 'Name the install creates'"); } + @Test + void testValidateSolutionReportsConflictingProfilesAndEdge() throws IOException { + writeEntitiesFile("device_profiles.json", "[{\"name\": \"thermostat\"}]"); + writeEntitiesFile("asset_profiles.json", "[{\"name\": \"building\"}]"); + writeEntitiesFile("edges.json", "[{\"name\": \"Main edge\"}]"); + + DeviceProfile deviceProfile = new DeviceProfile(); + deviceProfile.setName("thermostat"); + AssetProfile assetProfile = new AssetProfile(); + assetProfile.setName("building"); + Edge edge = new Edge(); + edge.setName("Main edge"); + when(deviceProfileService.findDeviceProfileByName(tenantId, "thermostat")).thenReturn(deviceProfile); + when(assetProfileService.findAssetProfileByName(tenantId, "building")).thenReturn(assetProfile); + when(edgeService.findEdgeByTenantIdAndName(tenantId, "Main edge")).thenReturn(edge); + + SolutionInstallResponse result = service.validateSolution(tenantId, tempDir); + + assertThat(result).isNotNull(); + assertThat(result.getDetails().lines().toList()).containsSubsequence( + "- **Device profile**: 'thermostat'", + "- **Asset profile**: 'building'", + "- **Edge**: 'Main edge'"); + } + + @Test + void testValidateSolutionLooksTheSameNameUpOnce() throws IOException { + writeEntitiesFile("devices.json", "[{\"name\": \"Sensor\"}, {\"name\": \"Sensor\"}]"); + + Device device = new Device(); + device.setName("Sensor"); + when(deviceService.findDeviceByTenantIdAndName(tenantId, "Sensor")).thenReturn(device); + + SolutionInstallResponse result = service.validateSolution(tenantId, tempDir); + + assertThat(result.getDetails().lines().toList()).contains("- **Device**: 'Sensor'"); + verify(deviceService, times(1)).findDeviceByTenantIdAndName(tenantId, "Sensor"); + } + + @Test + void testValidateSolutionSkipsRuleChainsWithoutAResolvableName() throws IOException { + writeEntitiesFile("rule_chains.json", "[{\"name\": \"No file\", \"file\": \"missing.json\"}," + + "{\"name\": \"No name inside\", \"file\": \"nameless.json\"}]"); + writeFile("rule_chains/nameless.json", "{\"ruleChain\": {}}"); + + assertThat(service.validateSolution(tenantId, tempDir)).isNull(); + verifyNoInteractions(ruleChainService); + } + + @Test + void testValidateSolutionUsesTheRuleChainTypeFromTheRuleChainFile() throws IOException { + writeEntitiesFile("rule_chains.json", "[{\"name\": \"Edge chain\", \"file\": \"rc.json\"}]"); + writeFile("rule_chains/rc.json", "{\"ruleChain\": {\"name\": \"Edge chain\", \"type\": \"EDGE\"}}"); + + RuleChain ruleChain = new RuleChain(); + ruleChain.setName("Edge chain"); + when(ruleChainService.findTenantRuleChainsByTypeAndName(tenantId, RuleChainType.EDGE, "Edge chain")) + .thenReturn(List.of(ruleChain)); + + SolutionInstallResponse result = service.validateSolution(tenantId, tempDir); + + assertThat(result.getDetails().lines().toList()).contains("- **Rule chain**: 'Edge chain'"); + } + + @Test + void testValidateSolutionTreatsAJsonNullFileAsEmpty() throws IOException { + writeEntitiesFile("devices.json", "null"); + + assertThat(service.validateSolution(tenantId, tempDir)).isNull(); + verifyNoInteractions(deviceService); + } + @Test void testValidateSolutionWithoutConflicts() throws IOException { writeEntitiesFile("devices.json", "[{\"name\": \"New device\"}]"); diff --git a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-install-dialog.component.ts b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-install-dialog.component.ts index 54a8409063..f777a4da31 100644 --- a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-install-dialog.component.ts +++ b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-install-dialog.component.ts @@ -340,19 +340,21 @@ export class TbIotHubInstallDialogComponent extends DialogComponent !entry.root && entry.errorMessage) : undefined; + // The title already names the item being installed, so only a failing dependency has to be named here, and + // only when the server reported the failure - the fallback above names the root. A missing entry carries an + // error message of its own, so the failing one is the entry the cascade actually tried to install. + const failedDependency = serverError ? (result.entries ?? []).find( + entry => !entry.root && entry.errorMessage && entry.status === InstallPlanEntryStatus.WILL_INSTALL) : undefined; if (failedDependency) { - message = this.translate.instant('iot-hub.install-dependency-error', { name: failedDependency.name }) + ' ' + message; + message = this.translate.instant('iot-hub.install-dependency-error', + { name: failedDependency.name, error: message }); } // A failed cascade rolls back the items installed so far. When something was actually being // installed and the rollback came back partial (rolledBack === false), some entities are left // behind — tell the admin so they know manual cleanup may be needed. The willInstall guard // avoids the misleading warning on the "empty plan" failure, where nothing was installed. if (!result.rolledBack && this.planSummary.willInstall > 0) { - message += ' ' + this.translate.instant('iot-hub.install-rollback-partial'); + message += '\n\n' + this.translate.instant('iot-hub.install-rollback-partial'); } this.errorMessage = message; return; diff --git a/ui-ngx/src/assets/locale/locale.constant-en_US.json b/ui-ngx/src/assets/locale/locale.constant-en_US.json index aefce04e88..b5f51fd6d4 100644 --- a/ui-ngx/src/assets/locale/locale.constant-en_US.json +++ b/ui-ngx/src/assets/locale/locale.constant-en_US.json @@ -3850,7 +3850,7 @@ "goto-main-dashboard": "Go to main dashboard", "install-error-title": "Installation Failed", "install-error-message": "Failed to install '{{name}}'.", - "install-dependency-error": "Failed to install the dependency '{{name}}':", + "install-dependency-error": "Failed to install the dependency '{{name}}': {{error}}", "install-plan-title": "Install '{{name}}' and its dependencies", "install-plan-will-install": "{{count}} item(s) will be installed.", "install-plan-will-update": "{{count}} item(s) already installed and will be skipped.", From f8b190691ac09bcd4986313a3ea1c0f857fc5697 Mon Sep 17 00:00:00 2001 From: dpinkevych Date: Mon, 7 Sep 2026 15:56:03 +0300 Subject: [PATCH 014/159] address the second review pass on the install validation - the dialog no longer mistakes a MISSING plan entry for the failing one: such entries carry an error message of their own with no name, so the lookup now also requires the WILL_INSTALL status - the whole dependency sentence lives in the locale bundle as one key with a name and an error parameter, instead of a fragment glued to the server message, and the partial rollback warning is appended as its own paragraph by the dialog rather than relying on the details ending with a blank line - a rule chain is validated under the type from the rule chain file too, so an EDGE chain is no longer looked up among the CORE ones - names are deduplicated before the lookup rather than when formatting, so a template repeating a name queries once - the entity type and the name come from the definition itself for the five lists that carry both, which removes the pairing hazard - ExceptionUtil.getMessage replaces the hand-rolled fallback, and the single-use firstOrNull helper is inlined - the dashboard check moved after the device one to match the provision order the comment claims, and the unreachable empty-list guard is gone - tests cover both profile types, edges, the rule chain type and its two unresolvable-name branches, the deduplicated lookup and a json file holding null --- .../service/iot_hub/DefaultIotHubService.java | 10 +- .../solutions/DefaultSolutionService.java | 130 ++++++++++-------- .../solutions/DefaultSolutionServiceTest.java | 88 +++++++++++- .../iot-hub-install-dialog.component.ts | 14 +- .../assets/locale/locale.constant-en_US.json | 2 +- 5 files changed, 173 insertions(+), 71 deletions(-) diff --git a/application/src/main/java/org/thingsboard/server/service/iot_hub/DefaultIotHubService.java b/application/src/main/java/org/thingsboard/server/service/iot_hub/DefaultIotHubService.java index b55173715f..ab5d438156 100644 --- a/application/src/main/java/org/thingsboard/server/service/iot_hub/DefaultIotHubService.java +++ b/application/src/main/java/org/thingsboard/server/service/iot_hub/DefaultIotHubService.java @@ -20,8 +20,8 @@ import jakarta.servlet.http.HttpServletRequest; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Service; +import org.thingsboard.common.util.ExceptionUtil; import org.thingsboard.common.util.JacksonUtil; -import org.thingsboard.server.common.data.StringUtils; import org.thingsboard.server.common.data.asset.AssetProfile; import org.thingsboard.server.common.data.Dashboard; import org.thingsboard.server.common.data.DeviceProfile; @@ -1007,15 +1007,13 @@ public class DefaultIotHubService implements IotHubService { } catch (Exception e) { log.error("[{}] Cascade install failed at entry {} ({}): {}", tenantId, entry.getName(), entry.getVersionId(), e.getMessage(), e); - // an exception without a message would leave both the entry and the result blank, - // and the dialog would have nothing to name the failing entry by - String failure = StringUtils.isEmpty(e.getMessage()) ? e.getClass().getSimpleName() : e.getMessage(); - resultEntry.setErrorMessage(failure); + String failureMessage = ExceptionUtil.getMessage(e); + resultEntry.setErrorMessage(failureMessage); resultEntries.add(resultEntry); boolean rolledBack = rollbackInstalledItems(user, rollbackIds); result.setSuccess(false); result.setRolledBack(rolledBack); - result.setErrorMessage(failure); + result.setErrorMessage(failureMessage); result.setEntries(resultEntries); result.setMissingItemIds(missingItemIds); return result; diff --git a/application/src/main/java/org/thingsboard/server/service/solutions/DefaultSolutionService.java b/application/src/main/java/org/thingsboard/server/service/solutions/DefaultSolutionService.java index c7982ab8fc..1cd720d1fc 100644 --- a/application/src/main/java/org/thingsboard/server/service/solutions/DefaultSolutionService.java +++ b/application/src/main/java/org/thingsboard/server/service/solutions/DefaultSolutionService.java @@ -126,6 +126,7 @@ import org.thingsboard.server.service.solutions.data.definition.UserDefinition; import org.thingsboard.server.service.solutions.data.definition.DashboardDefinition; import org.thingsboard.server.service.solutions.data.definition.DeviceProfileDefinition; import org.thingsboard.server.service.solutions.data.definition.EdgeDefinition; +import org.thingsboard.server.service.solutions.data.definition.EntityDefinition; import org.thingsboard.server.service.solutions.data.definition.RelationDefinition; import org.thingsboard.server.service.solutions.data.definition.ReferenceableEntityDefinition; import org.thingsboard.server.service.solutions.data.definition.TenantDefinition; @@ -183,7 +184,7 @@ public class DefaultSolutionService implements SolutionService { private static final String BLANK_LINE = System.lineSeparator() + System.lineSeparator(); private static final String CONFLICTS_INTRO = "Some entities of the solution template already exist. Rename or delete them and install the template again:"; - private static final String RANDOM_NAME_PLACEHOLDER_PREFIX = "$random"; + private static final String RANDOM_PLACEHOLDER = "$random"; @Value("${ui.solution_templates.docs_base_url:https://thingsboard.io/docs}") private String docsBaseUrl; @@ -323,32 +324,23 @@ public class DefaultSolutionService implements SolutionService { // Insertion ordered, so that the reported sections keep the order the entities are provisioned in. Map> conflicts = new LinkedHashMap<>(); - collectConflicts(conflicts, EntityType.RULE_CHAIN, ruleChains, definition -> ruleChainName(tempDir, definition), - name -> firstOrNull(ruleChainService.findTenantRuleChainsByTypeAndName(tenantId, RuleChainType.CORE, name))); + collectRuleChainConflicts(conflicts, tenantId, tempDir, ruleChains); collectConflicts(conflicts, EntityType.DEVICE_PROFILE, deviceProfiles, DeviceProfile::getName, name -> deviceProfileService.findDeviceProfileByName(tenantId, name)); collectConflicts(conflicts, EntityType.ASSET_PROFILE, assetProfiles, AssetProfile::getName, name -> assetProfileService.findAssetProfileByName(tenantId, name)); - collectConflicts(conflicts, EntityType.CUSTOMER, customers, CustomerDefinition::getName, - title -> isRandomizedAtInstall(title) ? null : customerService.findCustomerByTenantIdAndTitle(tenantId, title).orElse(null)); - collectConflicts(conflicts, EntityType.DASHBOARD, dashboards, DashboardDefinition::getName, - title -> dashboardService.findFirstDashboardInfoByTenantIdAndName(tenantId, title)); - collectConflicts(conflicts, EntityType.ASSET, assets, AssetDefinition::getName, - name -> assetService.findAssetByTenantIdAndName(tenantId, name)); - collectConflicts(conflicts, EntityType.DEVICE, devices, DeviceDefinition::getName, - name -> deviceService.findDeviceByTenantIdAndName(tenantId, name)); - collectConflicts(conflicts, EntityType.EDGE, edges, EdgeDefinition::getName, - name -> edgeService.findEdgeByTenantIdAndName(tenantId, name)); + collectConflicts(conflicts, customers, + title -> isRandomizedCustomerTitle(title) ? null : customerService.findCustomerByTenantIdAndTitle(tenantId, title).orElse(null)); + collectConflicts(conflicts, assets, name -> assetService.findAssetByTenantIdAndName(tenantId, name)); + collectConflicts(conflicts, devices, name -> deviceService.findDeviceByTenantIdAndName(tenantId, name)); + collectConflicts(conflicts, dashboards, title -> dashboardService.findFirstDashboardInfoByTenantIdAndName(tenantId, title)); + collectConflicts(conflicts, edges, name -> edgeService.findEdgeByTenantIdAndName(tenantId, name)); if (conflicts.isEmpty()) { return null; } StringBuilder details = new StringBuilder(CONFLICTS_INTRO).append(BLANK_LINE); - conflicts.forEach((entityType, entities) -> appendConflicts(details, entityType, - entities.stream().map(HasName::getName).map(DefaultSolutionService::quoted).toList())); - - // the dialog appends its own sentences to these details, so the list has to end with a blank line - details.append(System.lineSeparator()); + conflicts.forEach((entityType, entities) -> appendConflicts(details, entityType, entities)); SolutionInstallResponse solutionInstallResponse = new SolutionInstallResponse(); solutionInstallResponse.setSuccess(false); @@ -356,65 +348,91 @@ public class DefaultSolutionService implements SolutionService { return solutionInstallResponse; } + /** + * The entity type and the name both come from the definition, so a list can not end up checked against the + * wrong type by mistake. + */ + private void collectConflicts(Map> conflicts, List definitions, + Function lookup) { + Set checked = new HashSet<>(); + for (EntityDefinition definition : definitions) { + if (checked.add(definition.getName())) { + collectConflict(conflicts, definition.getEntityType(), definition.getName(), lookup); + } + } + } + private void collectConflicts(Map> conflicts, EntityType entityType, List definitions, Function nameExtractor, Function lookup) { + Set checked = new HashSet<>(); for (T definition : definitions) { String name = nameExtractor.apply(definition); - if (StringUtils.isEmpty(name)) { + if (checked.add(name)) { + collectConflict(conflicts, entityType, name, lookup); + } + } + } + + private void collectConflict(Map> conflicts, EntityType entityType, String name, + Function lookup) { + if (StringUtils.isEmpty(name)) { + return; + } + HasName existing = lookup.apply(name); + if (existing != null) { + conflicts.computeIfAbsent(entityType, key -> new ArrayList<>()).add(existing); + } + } + + /** + * A rule chain is created from the rule chain file, so both the name and the type of the chain the install will + * produce live there - the name in rule_chains.json is only a reference and the type defaults to CORE. + */ + private void collectRuleChainConflicts(Map> conflicts, TenantId tenantId, Path tempDir, + List definitions) { + Set checked = new HashSet<>(); + for (ReferenceableEntityDefinition definition : definitions) { + if (StringUtils.isEmpty(definition.getFile())) { + continue; + } + Path ruleChainPath = tempDir.resolve("rule_chains").resolve(definition.getFile()); + if (!Files.exists(ruleChainPath)) { + // provisionRuleChains logs and skips such a definition, so there is nothing to validate continue; } - HasName existing = lookup.apply(name); - if (existing != null) { - conflicts.computeIfAbsent(entityType, key -> new ArrayList<>()).add(existing); + JsonNode ruleChain = JacksonUtil.toJsonNode(ruleChainPath).get("ruleChain"); + if (ruleChain == null || !ruleChain.hasNonNull("name")) { + continue; + } + RuleChainType type = ruleChain.hasNonNull("type") + ? RuleChainType.valueOf(ruleChain.get("type").asText()) : RuleChainType.CORE; + String name = ruleChain.get("name").asText(); + if (!checked.add(type + name)) { + continue; } + collectConflict(conflicts, EntityType.RULE_CHAIN, name, + ignored -> ruleChainService.findTenantRuleChainsByTypeAndName(tenantId, type, name) + .stream().findFirst().orElse(null)); } } /** * Only customer titles, user names and attribute values go through {@link #randomize}, so a {@code $random} * placeholder in a customer title is replaced at install time and there is nothing to check upfront. Names of - * every other entity are used as written, placeholder included, so those are looked up as is - skipping them - * here would let the install die on a DB constraint again. + * every other entity are used as written, placeholder included, and must be looked up as is. */ - private static boolean isRandomizedAtInstall(String name) { - return name.contains(RANDOM_NAME_PLACEHOLDER_PREFIX); + private static boolean isRandomizedCustomerTitle(String title) { + return title.contains(RANDOM_PLACEHOLDER); } /** * One markdown list item per entity type, so that the names of the conflicting entities are what the user reads, * instead of the same sentence repeated for every type. */ - private void appendConflicts(StringBuilder details, EntityType entityType, List conflictDescriptions) { - if (conflictDescriptions.isEmpty()) { - return; - } + private void appendConflicts(StringBuilder details, EntityType entityType, List entities) { details.append("- **").append(entityType.getNormalName()).append("**: ") - .append(conflictDescriptions.stream().distinct().collect(Collectors.joining(", "))).append(System.lineSeparator()); - } - - private static String quoted(String value) { - return "'" + value + "'"; - } - - /** - * The provisioned rule chain takes its name from the rule chain file, not from the name in rule_chains.json, - * so the conflict has to be looked up under the name the install will actually create. - */ - private String ruleChainName(Path tempDir, ReferenceableEntityDefinition definition) { - if (StringUtils.isEmpty(definition.getFile())) { - return null; - } - Path ruleChainPath = tempDir.resolve("rule_chains").resolve(definition.getFile()); - if (!Files.exists(ruleChainPath)) { - // provisionRuleChains logs and skips such a definition, so there is nothing to validate - return null; - } - JsonNode ruleChain = JacksonUtil.toJsonNode(ruleChainPath).get("ruleChain"); - return ruleChain != null && ruleChain.hasNonNull("name") ? ruleChain.get("name").asText() : null; - } - - private static T firstOrNull(Collection data) { - return data == null || data.isEmpty() ? null : data.iterator().next(); + .append(entities.stream().map(entity -> "'" + entity.getName() + "'").collect(Collectors.joining(", "))) + .append(System.lineSeparator()); } private SolutionInstallResponse doInstallSolution(User user, TenantId tenantId, String solutionId, Path tempDir, HttpServletRequest request) { diff --git a/application/src/test/java/org/thingsboard/server/service/solutions/DefaultSolutionServiceTest.java b/application/src/test/java/org/thingsboard/server/service/solutions/DefaultSolutionServiceTest.java index 04096c3cc3..d89012057b 100644 --- a/application/src/test/java/org/thingsboard/server/service/solutions/DefaultSolutionServiceTest.java +++ b/application/src/test/java/org/thingsboard/server/service/solutions/DefaultSolutionServiceTest.java @@ -24,13 +24,19 @@ import org.mockito.junit.jupiter.MockitoExtension; import org.thingsboard.server.common.data.Customer; import org.thingsboard.server.common.data.DashboardInfo; import org.thingsboard.server.common.data.Device; +import org.thingsboard.server.common.data.DeviceProfile; +import org.thingsboard.server.common.data.asset.AssetProfile; +import org.thingsboard.server.common.data.edge.Edge; import org.thingsboard.server.common.data.id.TenantId; import org.thingsboard.server.common.data.rule.RuleChain; import org.thingsboard.server.common.data.rule.RuleChainType; +import org.thingsboard.server.dao.asset.AssetProfileService; import org.thingsboard.server.dao.asset.AssetService; import org.thingsboard.server.dao.customer.CustomerService; import org.thingsboard.server.dao.dashboard.DashboardService; +import org.thingsboard.server.dao.device.DeviceProfileService; import org.thingsboard.server.dao.device.DeviceService; +import org.thingsboard.server.dao.edge.EdgeService; import org.thingsboard.server.dao.rule.RuleChainService; import org.thingsboard.server.service.solutions.data.solution.SolutionInstallResponse; @@ -42,6 +48,8 @@ import java.util.Optional; import java.util.UUID; import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoInteractions; import static org.mockito.Mockito.when; @@ -63,6 +71,12 @@ class DefaultSolutionServiceTest { private DashboardService dashboardService; @Mock private RuleChainService ruleChainService; + @Mock + private DeviceProfileService deviceProfileService; + @Mock + private AssetProfileService assetProfileService; + @Mock + private EdgeService edgeService; @InjectMocks private DefaultSolutionService service; @@ -95,8 +109,6 @@ class DefaultSolutionServiceTest { CONFLICTS_INTRO, "- **Customer**: 'Existing customer'", "- **Device**: 'Existing device'"); - // the dialog appends its own sentences, so the details have to end with a blank line - assertThat(result.getDetails()).endsWith(System.lineSeparator() + System.lineSeparator()); // the randomized customer title and the entities that do not exist yet are not reported assertThat(result.getDetails()) .doesNotContain("Customer $random") @@ -136,6 +148,78 @@ class DefaultSolutionServiceTest { .containsSubsequence(CONFLICTS_INTRO, "- **Rule chain**: 'Name the install creates'"); } + @Test + void testValidateSolutionReportsConflictingProfilesAndEdge() throws IOException { + writeEntitiesFile("device_profiles.json", "[{\"name\": \"thermostat\"}]"); + writeEntitiesFile("asset_profiles.json", "[{\"name\": \"building\"}]"); + writeEntitiesFile("edges.json", "[{\"name\": \"Main edge\"}]"); + + DeviceProfile deviceProfile = new DeviceProfile(); + deviceProfile.setName("thermostat"); + AssetProfile assetProfile = new AssetProfile(); + assetProfile.setName("building"); + Edge edge = new Edge(); + edge.setName("Main edge"); + when(deviceProfileService.findDeviceProfileByName(tenantId, "thermostat")).thenReturn(deviceProfile); + when(assetProfileService.findAssetProfileByName(tenantId, "building")).thenReturn(assetProfile); + when(edgeService.findEdgeByTenantIdAndName(tenantId, "Main edge")).thenReturn(edge); + + SolutionInstallResponse result = service.validateSolution(tenantId, tempDir); + + assertThat(result).isNotNull(); + assertThat(result.getDetails().lines().toList()).containsSubsequence( + "- **Device profile**: 'thermostat'", + "- **Asset profile**: 'building'", + "- **Edge**: 'Main edge'"); + } + + @Test + void testValidateSolutionLooksTheSameNameUpOnce() throws IOException { + writeEntitiesFile("devices.json", "[{\"name\": \"Sensor\"}, {\"name\": \"Sensor\"}]"); + + Device device = new Device(); + device.setName("Sensor"); + when(deviceService.findDeviceByTenantIdAndName(tenantId, "Sensor")).thenReturn(device); + + SolutionInstallResponse result = service.validateSolution(tenantId, tempDir); + + assertThat(result.getDetails().lines().toList()).contains("- **Device**: 'Sensor'"); + verify(deviceService, times(1)).findDeviceByTenantIdAndName(tenantId, "Sensor"); + } + + @Test + void testValidateSolutionSkipsRuleChainsWithoutAResolvableName() throws IOException { + writeEntitiesFile("rule_chains.json", "[{\"name\": \"No file\", \"file\": \"missing.json\"}," + + "{\"name\": \"No name inside\", \"file\": \"nameless.json\"}]"); + writeFile("rule_chains/nameless.json", "{\"ruleChain\": {}}"); + + assertThat(service.validateSolution(tenantId, tempDir)).isNull(); + verifyNoInteractions(ruleChainService); + } + + @Test + void testValidateSolutionUsesTheRuleChainTypeFromTheRuleChainFile() throws IOException { + writeEntitiesFile("rule_chains.json", "[{\"name\": \"Edge chain\", \"file\": \"rc.json\"}]"); + writeFile("rule_chains/rc.json", "{\"ruleChain\": {\"name\": \"Edge chain\", \"type\": \"EDGE\"}}"); + + RuleChain ruleChain = new RuleChain(); + ruleChain.setName("Edge chain"); + when(ruleChainService.findTenantRuleChainsByTypeAndName(tenantId, RuleChainType.EDGE, "Edge chain")) + .thenReturn(List.of(ruleChain)); + + SolutionInstallResponse result = service.validateSolution(tenantId, tempDir); + + assertThat(result.getDetails().lines().toList()).contains("- **Rule chain**: 'Edge chain'"); + } + + @Test + void testValidateSolutionTreatsAJsonNullFileAsEmpty() throws IOException { + writeEntitiesFile("devices.json", "null"); + + assertThat(service.validateSolution(tenantId, tempDir)).isNull(); + verifyNoInteractions(deviceService); + } + @Test void testValidateSolutionWithoutConflicts() throws IOException { writeEntitiesFile("devices.json", "[{\"name\": \"New device\"}]"); diff --git a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-install-dialog.component.ts b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-install-dialog.component.ts index 06dbb271e0..e4b177f598 100644 --- a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-install-dialog.component.ts +++ b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-install-dialog.component.ts @@ -346,19 +346,21 @@ export class TbIotHubInstallDialogComponent extends DialogComponent !entry.root && entry.errorMessage) : undefined; + // The title already names the item being installed, so only a failing dependency has to be named here, and + // only when the server reported the failure - the fallback above names the root. A missing entry carries an + // error message of its own, so the failing one is the entry the cascade actually tried to install. + const failedDependency = serverError ? (result.entries ?? []).find( + entry => !entry.root && entry.errorMessage && entry.status === InstallPlanEntryStatus.WILL_INSTALL) : undefined; if (failedDependency) { - message = this.translate.instant('iot-hub.install-dependency-error', { name: failedDependency.name }) + ' ' + message; + message = this.translate.instant('iot-hub.install-dependency-error', + { name: failedDependency.name, error: message }); } // A failed cascade rolls back the items installed so far. When something was actually being // installed and the rollback came back partial (rolledBack === false), some entities are left // behind — tell the admin so they know manual cleanup may be needed. The willInstall guard // avoids the misleading warning on the "empty plan" failure, where nothing was installed. if (!result.rolledBack && this.planSummary.willInstall > 0) { - message += ' ' + this.translate.instant('iot-hub.install-rollback-partial'); + message += '\n\n' + this.translate.instant('iot-hub.install-rollback-partial'); } this.errorMessage = message; return; diff --git a/ui-ngx/src/assets/locale/locale.constant-en_US.json b/ui-ngx/src/assets/locale/locale.constant-en_US.json index 19d2ac7484..bcac1a5d1a 100644 --- a/ui-ngx/src/assets/locale/locale.constant-en_US.json +++ b/ui-ngx/src/assets/locale/locale.constant-en_US.json @@ -4337,7 +4337,7 @@ "goto-main-dashboard": "Go to main dashboard", "install-error-title": "Installation Failed", "install-error-message": "Failed to install '{{name}}'.", - "install-dependency-error": "Failed to install the dependency '{{name}}':", + "install-dependency-error": "Failed to install the dependency '{{name}}': {{error}}", "install-plan-title": "Install '{{name}}' and its dependencies", "install-plan-will-install": "{{count}} item(s) will be installed.", "install-plan-will-update": "{{count}} item(s) already installed and will be skipped.", From 0453663dd9098050c0baaa07528ba77cf8ba8e9b Mon Sep 17 00:00:00 2001 From: dpinkevych Date: Tue, 8 Sep 2026 13:39:22 +0300 Subject: [PATCH 015/159] address the PE review notes on the install report - drop the java.util.Collection import that stayed behind when firstOrNull was inlined - cap each report section at ten names plus "and N more": a template can hold hundreds of devices, and the dialog renders these details without the height cap the plain-text branch has - leave the details empty when the server reported no message of its own, since the description above them already names the item that failed - cover the asset conflict, the capped report and the remaining mocks in the validation test --- .../solutions/DefaultSolutionService.java | 14 ++++++--- .../solutions/DefaultSolutionServiceTest.java | 31 +++++++++++++++++-- .../iot-hub-install-dialog.component.html | 14 +++++---- .../iot-hub-install-dialog.component.ts | 18 ++++++----- 4 files changed, 56 insertions(+), 21 deletions(-) diff --git a/application/src/main/java/org/thingsboard/server/service/solutions/DefaultSolutionService.java b/application/src/main/java/org/thingsboard/server/service/solutions/DefaultSolutionService.java index 1cd720d1fc..43828a4891 100644 --- a/application/src/main/java/org/thingsboard/server/service/solutions/DefaultSolutionService.java +++ b/application/src/main/java/org/thingsboard/server/service/solutions/DefaultSolutionService.java @@ -152,7 +152,6 @@ import java.nio.file.SimpleFileVisitor; import java.nio.file.attribute.BasicFileAttributes; import java.time.ZonedDateTime; import java.util.ArrayList; -import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; @@ -185,6 +184,7 @@ public class DefaultSolutionService implements SolutionService { private static final String CONFLICTS_INTRO = "Some entities of the solution template already exist. Rename or delete them and install the template again:"; private static final String RANDOM_PLACEHOLDER = "$random"; + private static final int MAX_REPORTED_CONFLICTS = 10; @Value("${ui.solution_templates.docs_base_url:https://thingsboard.io/docs}") private String docsBaseUrl; @@ -340,7 +340,8 @@ public class DefaultSolutionService implements SolutionService { return null; } StringBuilder details = new StringBuilder(CONFLICTS_INTRO).append(BLANK_LINE); - conflicts.forEach((entityType, entities) -> appendConflicts(details, entityType, entities)); + conflicts.forEach((entityType, entities) -> appendConflicts(details, entityType, + entities.stream().map(entity -> "'" + entity.getName() + "'").toList())); SolutionInstallResponse solutionInstallResponse = new SolutionInstallResponse(); solutionInstallResponse.setSuccess(false); @@ -429,10 +430,13 @@ public class DefaultSolutionService implements SolutionService { * One markdown list item per entity type, so that the names of the conflicting entities are what the user reads, * instead of the same sentence repeated for every type. */ - private void appendConflicts(StringBuilder details, EntityType entityType, List entities) { + private void appendConflicts(StringBuilder details, EntityType entityType, List conflictDescriptions) { details.append("- **").append(entityType.getNormalName()).append("**: ") - .append(entities.stream().map(entity -> "'" + entity.getName() + "'").collect(Collectors.joining(", "))) - .append(System.lineSeparator()); + .append(conflictDescriptions.stream().limit(MAX_REPORTED_CONFLICTS).collect(Collectors.joining(", "))); + if (conflictDescriptions.size() > MAX_REPORTED_CONFLICTS) { + details.append(" and ").append(conflictDescriptions.size() - MAX_REPORTED_CONFLICTS).append(" more"); + } + details.append(System.lineSeparator()); } private SolutionInstallResponse doInstallSolution(User user, TenantId tenantId, String solutionId, Path tempDir, HttpServletRequest request) { diff --git a/application/src/test/java/org/thingsboard/server/service/solutions/DefaultSolutionServiceTest.java b/application/src/test/java/org/thingsboard/server/service/solutions/DefaultSolutionServiceTest.java index d89012057b..d28955e742 100644 --- a/application/src/test/java/org/thingsboard/server/service/solutions/DefaultSolutionServiceTest.java +++ b/application/src/test/java/org/thingsboard/server/service/solutions/DefaultSolutionServiceTest.java @@ -25,6 +25,7 @@ import org.thingsboard.server.common.data.Customer; import org.thingsboard.server.common.data.DashboardInfo; import org.thingsboard.server.common.data.Device; import org.thingsboard.server.common.data.DeviceProfile; +import org.thingsboard.server.common.data.asset.Asset; import org.thingsboard.server.common.data.asset.AssetProfile; import org.thingsboard.server.common.data.edge.Edge; import org.thingsboard.server.common.data.id.TenantId; @@ -46,6 +47,8 @@ import java.nio.file.Path; import java.util.List; import java.util.Optional; import java.util.UUID; +import java.util.stream.Collectors; +import java.util.stream.IntStream; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.times; @@ -88,7 +91,7 @@ class DefaultSolutionServiceTest { void testValidateSolutionNamesEveryConflictingEntity() throws IOException { writeEntitiesFile("customers.json", "[{\"name\": \"Existing customer\"}, {\"name\": \"Customer $random\"}]"); writeEntitiesFile("devices.json", "[{\"name\": \"Existing device\"}, {\"name\": \"New device\"}]"); - writeEntitiesFile("assets.json", "[{\"name\": \"New asset\"}]"); + writeEntitiesFile("assets.json", "[{\"name\": \"Existing asset\"}, {\"name\": \"New asset\"}]"); Customer customer = new Customer(); customer.setTitle("Existing customer"); @@ -96,6 +99,9 @@ class DefaultSolutionServiceTest { device.setName("Existing device"); when(customerService.findCustomerByTenantIdAndTitle(tenantId, "Existing customer")).thenReturn(Optional.of(customer)); + Asset asset = new Asset(); + asset.setName("Existing asset"); + when(assetService.findAssetByTenantIdAndName(tenantId, "Existing asset")).thenReturn(asset); when(assetService.findAssetByTenantIdAndName(tenantId, "New asset")).thenReturn(null); when(deviceService.findDeviceByTenantIdAndName(tenantId, "Existing device")).thenReturn(device); when(deviceService.findDeviceByTenantIdAndName(tenantId, "New device")).thenReturn(null); @@ -108,6 +114,7 @@ class DefaultSolutionServiceTest { .containsSubsequence( CONFLICTS_INTRO, "- **Customer**: 'Existing customer'", + "- **Asset**: 'Existing asset'", "- **Device**: 'Existing device'"); // the randomized customer title and the entities that do not exist yet are not reported assertThat(result.getDetails()) @@ -220,6 +227,25 @@ class DefaultSolutionServiceTest { verifyNoInteractions(deviceService); } + @Test + void testValidateSolutionCapsTheNamesItLists() throws IOException { + String definitions = IntStream.rangeClosed(1, 12) + .mapToObj(i -> "{\"name\": \"Sensor " + i + "\"}") + .collect(Collectors.joining(",")); + writeEntitiesFile("devices.json", "[" + definitions + "]"); + for (int i = 1; i <= 12; i++) { + Device device = new Device(); + device.setName("Sensor " + i); + when(deviceService.findDeviceByTenantIdAndName(tenantId, "Sensor " + i)).thenReturn(device); + } + + SolutionInstallResponse result = service.validateSolution(tenantId, tempDir); + + assertThat(result.getDetails().lines().toList()) + .contains("- **Device**: 'Sensor 1', 'Sensor 2', 'Sensor 3', 'Sensor 4', 'Sensor 5', 'Sensor 6', " + + "'Sensor 7', 'Sensor 8', 'Sensor 9', 'Sensor 10' and 2 more"); + } + @Test void testValidateSolutionWithoutConflicts() throws IOException { writeEntitiesFile("devices.json", "[{\"name\": \"New device\"}]"); @@ -231,7 +257,8 @@ class DefaultSolutionServiceTest { @Test void testValidateSolutionWithoutEntityFiles() { assertThat(service.validateSolution(tenantId, tempDir)).isNull(); - verifyNoInteractions(customerService, deviceService, assetService, dashboardService, ruleChainService); + verifyNoInteractions(customerService, deviceService, assetService, dashboardService, ruleChainService, + deviceProfileService, assetProfileService, edgeService); } private void writeFile(String relativePath, String content) throws IOException { diff --git a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-install-dialog.component.html b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-install-dialog.component.html index 25c5ca2089..d267ccf57e 100644 --- a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-install-dialog.component.html +++ b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-install-dialog.component.html @@ -141,12 +141,14 @@ @case ('error') {

{{ 'iot-hub.install-error-title' | translate }}

{{ 'iot-hub.install-error-message' | translate:{ name: item.name } }}

- @if (item.type === ItemType.SOLUTION_TEMPLATE) { - - } @else { -
- {{ errorMessage }} -
+ @if (errorMessage) { + @if (item.type === ItemType.SOLUTION_TEMPLATE) { + + } @else { +
+ {{ errorMessage }} +
+ } } } } diff --git a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-install-dialog.component.ts b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-install-dialog.component.ts index e4b177f598..3198d8ff28 100644 --- a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-install-dialog.component.ts +++ b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-install-dialog.component.ts @@ -314,7 +314,7 @@ export class TbIotHubInstallDialogComponent extends DialogComponent { if (!result.success) { this.state = 'error'; - this.errorMessage = result.errorMessage || this.translate.instant('iot-hub.install-error', { name: this.item.name }); + this.errorMessage = result.errorMessage ?? ''; return; } this.handleInstalledDescriptor(result.descriptor); @@ -337,18 +337,19 @@ export class TbIotHubInstallDialogComponent extends DialogComponent !entry.root && entry.errorMessage && entry.status === InstallPlanEntryStatus.WILL_INSTALL) : undefined; if (failedDependency) { @@ -360,7 +361,8 @@ export class TbIotHubInstallDialogComponent extends DialogComponent 0) { - message += '\n\n' + this.translate.instant('iot-hub.install-rollback-partial'); + const warning = this.translate.instant('iot-hub.install-rollback-partial'); + message = message ? message + '\n\n' + warning : warning; } this.errorMessage = message; return; From f97bc57694821c4ef8d8ca05222e9319cd44c9d7 Mon Sep 17 00:00:00 2001 From: dpinkevych Date: Tue, 8 Sep 2026 13:36:49 +0300 Subject: [PATCH 016/159] address the PE review notes on the install report - drop the java.util.Collection import that stayed behind when firstOrNull was inlined - cap each report section at ten names plus "and N more": a template can hold hundreds of devices, and the dialog renders these details without the height cap the plain-text branch has - leave the details empty when the server reported no message of its own, since the description above them already names the item that failed - cover the asset conflict, the capped report and the remaining mocks in the validation test --- .../solutions/DefaultSolutionService.java | 14 ++++++--- .../solutions/DefaultSolutionServiceTest.java | 31 +++++++++++++++++-- .../iot-hub-install-dialog.component.html | 14 +++++---- .../iot-hub-install-dialog.component.ts | 18 ++++++----- 4 files changed, 56 insertions(+), 21 deletions(-) diff --git a/application/src/main/java/org/thingsboard/server/service/solutions/DefaultSolutionService.java b/application/src/main/java/org/thingsboard/server/service/solutions/DefaultSolutionService.java index cdeb9c06af..352d4d4e17 100644 --- a/application/src/main/java/org/thingsboard/server/service/solutions/DefaultSolutionService.java +++ b/application/src/main/java/org/thingsboard/server/service/solutions/DefaultSolutionService.java @@ -150,7 +150,6 @@ import java.nio.file.SimpleFileVisitor; import java.nio.file.attribute.BasicFileAttributes; import java.time.ZonedDateTime; import java.util.ArrayList; -import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; @@ -183,6 +182,7 @@ public class DefaultSolutionService implements SolutionService { private static final String CONFLICTS_INTRO = "Some entities of the solution template already exist. Rename or delete them and install the template again:"; private static final String RANDOM_PLACEHOLDER = "$random"; + private static final int MAX_REPORTED_CONFLICTS = 10; @Value("${ui.solution_templates.docs_base_url:https://thingsboard.io/docs}") private String docsBaseUrl; @@ -338,7 +338,8 @@ public class DefaultSolutionService implements SolutionService { return null; } StringBuilder details = new StringBuilder(CONFLICTS_INTRO).append(BLANK_LINE); - conflicts.forEach((entityType, entities) -> appendConflicts(details, entityType, entities)); + conflicts.forEach((entityType, entities) -> appendConflicts(details, entityType, + entities.stream().map(entity -> "'" + entity.getName() + "'").toList())); SolutionInstallResponse solutionInstallResponse = new SolutionInstallResponse(); solutionInstallResponse.setSuccess(false); @@ -427,10 +428,13 @@ public class DefaultSolutionService implements SolutionService { * One markdown list item per entity type, so that the names of the conflicting entities are what the user reads, * instead of the same sentence repeated for every type. */ - private void appendConflicts(StringBuilder details, EntityType entityType, List entities) { + private void appendConflicts(StringBuilder details, EntityType entityType, List conflictDescriptions) { details.append("- **").append(entityType.getNormalName()).append("**: ") - .append(entities.stream().map(entity -> "'" + entity.getName() + "'").collect(Collectors.joining(", "))) - .append(System.lineSeparator()); + .append(conflictDescriptions.stream().limit(MAX_REPORTED_CONFLICTS).collect(Collectors.joining(", "))); + if (conflictDescriptions.size() > MAX_REPORTED_CONFLICTS) { + details.append(" and ").append(conflictDescriptions.size() - MAX_REPORTED_CONFLICTS).append(" more"); + } + details.append(System.lineSeparator()); } private SolutionInstallResponse doInstallSolution(User user, TenantId tenantId, String solutionId, Path tempDir, HttpServletRequest request) { diff --git a/application/src/test/java/org/thingsboard/server/service/solutions/DefaultSolutionServiceTest.java b/application/src/test/java/org/thingsboard/server/service/solutions/DefaultSolutionServiceTest.java index d89012057b..d28955e742 100644 --- a/application/src/test/java/org/thingsboard/server/service/solutions/DefaultSolutionServiceTest.java +++ b/application/src/test/java/org/thingsboard/server/service/solutions/DefaultSolutionServiceTest.java @@ -25,6 +25,7 @@ import org.thingsboard.server.common.data.Customer; import org.thingsboard.server.common.data.DashboardInfo; import org.thingsboard.server.common.data.Device; import org.thingsboard.server.common.data.DeviceProfile; +import org.thingsboard.server.common.data.asset.Asset; import org.thingsboard.server.common.data.asset.AssetProfile; import org.thingsboard.server.common.data.edge.Edge; import org.thingsboard.server.common.data.id.TenantId; @@ -46,6 +47,8 @@ import java.nio.file.Path; import java.util.List; import java.util.Optional; import java.util.UUID; +import java.util.stream.Collectors; +import java.util.stream.IntStream; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.times; @@ -88,7 +91,7 @@ class DefaultSolutionServiceTest { void testValidateSolutionNamesEveryConflictingEntity() throws IOException { writeEntitiesFile("customers.json", "[{\"name\": \"Existing customer\"}, {\"name\": \"Customer $random\"}]"); writeEntitiesFile("devices.json", "[{\"name\": \"Existing device\"}, {\"name\": \"New device\"}]"); - writeEntitiesFile("assets.json", "[{\"name\": \"New asset\"}]"); + writeEntitiesFile("assets.json", "[{\"name\": \"Existing asset\"}, {\"name\": \"New asset\"}]"); Customer customer = new Customer(); customer.setTitle("Existing customer"); @@ -96,6 +99,9 @@ class DefaultSolutionServiceTest { device.setName("Existing device"); when(customerService.findCustomerByTenantIdAndTitle(tenantId, "Existing customer")).thenReturn(Optional.of(customer)); + Asset asset = new Asset(); + asset.setName("Existing asset"); + when(assetService.findAssetByTenantIdAndName(tenantId, "Existing asset")).thenReturn(asset); when(assetService.findAssetByTenantIdAndName(tenantId, "New asset")).thenReturn(null); when(deviceService.findDeviceByTenantIdAndName(tenantId, "Existing device")).thenReturn(device); when(deviceService.findDeviceByTenantIdAndName(tenantId, "New device")).thenReturn(null); @@ -108,6 +114,7 @@ class DefaultSolutionServiceTest { .containsSubsequence( CONFLICTS_INTRO, "- **Customer**: 'Existing customer'", + "- **Asset**: 'Existing asset'", "- **Device**: 'Existing device'"); // the randomized customer title and the entities that do not exist yet are not reported assertThat(result.getDetails()) @@ -220,6 +227,25 @@ class DefaultSolutionServiceTest { verifyNoInteractions(deviceService); } + @Test + void testValidateSolutionCapsTheNamesItLists() throws IOException { + String definitions = IntStream.rangeClosed(1, 12) + .mapToObj(i -> "{\"name\": \"Sensor " + i + "\"}") + .collect(Collectors.joining(",")); + writeEntitiesFile("devices.json", "[" + definitions + "]"); + for (int i = 1; i <= 12; i++) { + Device device = new Device(); + device.setName("Sensor " + i); + when(deviceService.findDeviceByTenantIdAndName(tenantId, "Sensor " + i)).thenReturn(device); + } + + SolutionInstallResponse result = service.validateSolution(tenantId, tempDir); + + assertThat(result.getDetails().lines().toList()) + .contains("- **Device**: 'Sensor 1', 'Sensor 2', 'Sensor 3', 'Sensor 4', 'Sensor 5', 'Sensor 6', " + + "'Sensor 7', 'Sensor 8', 'Sensor 9', 'Sensor 10' and 2 more"); + } + @Test void testValidateSolutionWithoutConflicts() throws IOException { writeEntitiesFile("devices.json", "[{\"name\": \"New device\"}]"); @@ -231,7 +257,8 @@ class DefaultSolutionServiceTest { @Test void testValidateSolutionWithoutEntityFiles() { assertThat(service.validateSolution(tenantId, tempDir)).isNull(); - verifyNoInteractions(customerService, deviceService, assetService, dashboardService, ruleChainService); + verifyNoInteractions(customerService, deviceService, assetService, dashboardService, ruleChainService, + deviceProfileService, assetProfileService, edgeService); } private void writeFile(String relativePath, String content) throws IOException { diff --git a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-install-dialog.component.html b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-install-dialog.component.html index 25c5ca2089..d267ccf57e 100644 --- a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-install-dialog.component.html +++ b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-install-dialog.component.html @@ -141,12 +141,14 @@ @case ('error') {

{{ 'iot-hub.install-error-title' | translate }}

{{ 'iot-hub.install-error-message' | translate:{ name: item.name } }}

- @if (item.type === ItemType.SOLUTION_TEMPLATE) { - - } @else { -
- {{ errorMessage }} -
+ @if (errorMessage) { + @if (item.type === ItemType.SOLUTION_TEMPLATE) { + + } @else { +
+ {{ errorMessage }} +
+ } } } } diff --git a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-install-dialog.component.ts b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-install-dialog.component.ts index f777a4da31..5fe6879e5e 100644 --- a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-install-dialog.component.ts +++ b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-install-dialog.component.ts @@ -308,7 +308,7 @@ export class TbIotHubInstallDialogComponent extends DialogComponent { if (!result.success) { this.state = 'error'; - this.errorMessage = result.errorMessage || this.translate.instant('iot-hub.install-error', { name: this.item.name }); + this.errorMessage = result.errorMessage ?? ''; return; } this.handleInstalledDescriptor(result.descriptor); @@ -331,18 +331,19 @@ export class TbIotHubInstallDialogComponent extends DialogComponent !entry.root && entry.errorMessage && entry.status === InstallPlanEntryStatus.WILL_INSTALL) : undefined; if (failedDependency) { @@ -354,7 +355,8 @@ export class TbIotHubInstallDialogComponent extends DialogComponent 0) { - message += '\n\n' + this.translate.instant('iot-hub.install-rollback-partial'); + const warning = this.translate.instant('iot-hub.install-rollback-partial'); + message = message ? message + '\n\n' + warning : warning; } this.errorMessage = message; return; From 79e1a9ff77dca592fb12085dbd313285137cef53 Mon Sep 17 00:00:00 2001 From: dpinkevych Date: Wed, 9 Sep 2026 12:54:04 +0300 Subject: [PATCH 017/159] address the second PE review pass on the install report - rename the cap to MAX_LISTED_NAMES_PER_TYPE: it shortens the printed list, it does not limit what is validated - say how many conflicts a type has in total, and add a note when names were left out, so the "rename or delete them" instruction stays true - keep only the names in the conflict map, the entities were never read for anything else - one way of saying "there are no details" in the dialog, and one comment instead of two that open the same way - cover the whole branch of the cap (10, 11 and 12 names) and the profile name that comes from both the json file and the directory --- .../solutions/DefaultSolutionService.java | 36 ++++++---- .../solutions/DefaultSolutionServiceTest.java | 71 ++++++++++++++----- .../iot-hub-install-dialog.component.ts | 17 +++-- 3 files changed, 82 insertions(+), 42 deletions(-) diff --git a/application/src/main/java/org/thingsboard/server/service/solutions/DefaultSolutionService.java b/application/src/main/java/org/thingsboard/server/service/solutions/DefaultSolutionService.java index 352d4d4e17..d8ec610c58 100644 --- a/application/src/main/java/org/thingsboard/server/service/solutions/DefaultSolutionService.java +++ b/application/src/main/java/org/thingsboard/server/service/solutions/DefaultSolutionService.java @@ -182,7 +182,9 @@ public class DefaultSolutionService implements SolutionService { private static final String CONFLICTS_INTRO = "Some entities of the solution template already exist. Rename or delete them and install the template again:"; private static final String RANDOM_PLACEHOLDER = "$random"; - private static final int MAX_REPORTED_CONFLICTS = 10; + private static final int MAX_LISTED_NAMES_PER_TYPE = 10; + private static final String TRUNCATION_NOTE = "Only the first " + MAX_LISTED_NAMES_PER_TYPE + + " names of each type are listed. The rest are reported the next time the template is installed."; @Value("${ui.solution_templates.docs_base_url:https://thingsboard.io/docs}") private String docsBaseUrl; @@ -321,7 +323,7 @@ public class DefaultSolutionService implements SolutionService { }); // Insertion ordered, so that the reported sections keep the order the entities are provisioned in. - Map> conflicts = new LinkedHashMap<>(); + Map> conflicts = new LinkedHashMap<>(); collectRuleChainConflicts(conflicts, tenantId, tempDir, ruleChains); collectConflicts(conflicts, EntityType.DEVICE_PROFILE, deviceProfiles, DeviceProfile::getName, name -> deviceProfileService.findDeviceProfileByName(tenantId, name)); @@ -338,8 +340,11 @@ public class DefaultSolutionService implements SolutionService { return null; } StringBuilder details = new StringBuilder(CONFLICTS_INTRO).append(BLANK_LINE); - conflicts.forEach((entityType, entities) -> appendConflicts(details, entityType, - entities.stream().map(entity -> "'" + entity.getName() + "'").toList())); + conflicts.forEach((entityType, names) -> appendConflicts(details, entityType, + names.stream().map(name -> "'" + name + "'").toList())); + if (conflicts.values().stream().anyMatch(names -> names.size() > MAX_LISTED_NAMES_PER_TYPE)) { + details.append(System.lineSeparator()).append(TRUNCATION_NOTE); + } SolutionInstallResponse solutionInstallResponse = new SolutionInstallResponse(); solutionInstallResponse.setSuccess(false); @@ -351,7 +356,7 @@ public class DefaultSolutionService implements SolutionService { * The entity type and the name both come from the definition, so a list can not end up checked against the * wrong type by mistake. */ - private void collectConflicts(Map> conflicts, List definitions, + private void collectConflicts(Map> conflicts, List definitions, Function lookup) { Set checked = new HashSet<>(); for (EntityDefinition definition : definitions) { @@ -361,7 +366,7 @@ public class DefaultSolutionService implements SolutionService { } } - private void collectConflicts(Map> conflicts, EntityType entityType, List definitions, + private void collectConflicts(Map> conflicts, EntityType entityType, List definitions, Function nameExtractor, Function lookup) { Set checked = new HashSet<>(); for (T definition : definitions) { @@ -372,14 +377,14 @@ public class DefaultSolutionService implements SolutionService { } } - private void collectConflict(Map> conflicts, EntityType entityType, String name, + private void collectConflict(Map> conflicts, EntityType entityType, String name, Function lookup) { if (StringUtils.isEmpty(name)) { return; } HasName existing = lookup.apply(name); if (existing != null) { - conflicts.computeIfAbsent(entityType, key -> new ArrayList<>()).add(existing); + conflicts.computeIfAbsent(entityType, key -> new ArrayList<>()).add(existing.getName()); } } @@ -387,7 +392,7 @@ public class DefaultSolutionService implements SolutionService { * A rule chain is created from the rule chain file, so both the name and the type of the chain the install will * produce live there - the name in rule_chains.json is only a reference and the type defaults to CORE. */ - private void collectRuleChainConflicts(Map> conflicts, TenantId tenantId, Path tempDir, + private void collectRuleChainConflicts(Map> conflicts, TenantId tenantId, Path tempDir, List definitions) { Set checked = new HashSet<>(); for (ReferenceableEntityDefinition definition : definitions) { @@ -426,13 +431,16 @@ public class DefaultSolutionService implements SolutionService { /** * One markdown list item per entity type, so that the names of the conflicting entities are what the user reads, - * instead of the same sentence repeated for every type. + * instead of the same sentence repeated for every type. Only the first {@value #MAX_LISTED_NAMES_PER_TYPE} + * names of a type are listed, the rest are counted - {@link #TRUNCATION_NOTE} tells the user that the list of + * that type is not complete. */ - private void appendConflicts(StringBuilder details, EntityType entityType, List conflictDescriptions) { + private static void appendConflicts(StringBuilder details, EntityType entityType, List conflictDescriptions) { details.append("- **").append(entityType.getNormalName()).append("**: ") - .append(conflictDescriptions.stream().limit(MAX_REPORTED_CONFLICTS).collect(Collectors.joining(", "))); - if (conflictDescriptions.size() > MAX_REPORTED_CONFLICTS) { - details.append(" and ").append(conflictDescriptions.size() - MAX_REPORTED_CONFLICTS).append(" more"); + .append(conflictDescriptions.stream().limit(MAX_LISTED_NAMES_PER_TYPE).collect(Collectors.joining(", "))); + if (conflictDescriptions.size() > MAX_LISTED_NAMES_PER_TYPE) { + details.append(" and ").append(conflictDescriptions.size() - MAX_LISTED_NAMES_PER_TYPE) + .append(" more (").append(conflictDescriptions.size()).append(" in total)"); } details.append(System.lineSeparator()); } diff --git a/application/src/test/java/org/thingsboard/server/service/solutions/DefaultSolutionServiceTest.java b/application/src/test/java/org/thingsboard/server/service/solutions/DefaultSolutionServiceTest.java index d28955e742..b1b5f1726a 100644 --- a/application/src/test/java/org/thingsboard/server/service/solutions/DefaultSolutionServiceTest.java +++ b/application/src/test/java/org/thingsboard/server/service/solutions/DefaultSolutionServiceTest.java @@ -18,6 +18,8 @@ package org.thingsboard.server.service.solutions; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.junit.jupiter.api.io.TempDir; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; @@ -61,6 +63,10 @@ class DefaultSolutionServiceTest { private static final String CONFLICTS_INTRO = "Some entities of the solution template already exist. Rename or delete them and install the template again:"; + // mirrors DefaultSolutionService.MAX_LISTED_NAMES_PER_TYPE and the note that goes with it + private static final int LISTED_NAMES_PER_TYPE = 10; + private static final String TRUNCATION_NOTE = "Only the first " + LISTED_NAMES_PER_TYPE + + " names of each type are listed. The rest are reported the next time the template is installed."; private final TenantId tenantId = TenantId.fromUUID(UUID.randomUUID()); @@ -95,15 +101,14 @@ class DefaultSolutionServiceTest { Customer customer = new Customer(); customer.setTitle("Existing customer"); - Device device = new Device(); - device.setName("Existing device"); when(customerService.findCustomerByTenantIdAndTitle(tenantId, "Existing customer")).thenReturn(Optional.of(customer)); Asset asset = new Asset(); asset.setName("Existing asset"); when(assetService.findAssetByTenantIdAndName(tenantId, "Existing asset")).thenReturn(asset); when(assetService.findAssetByTenantIdAndName(tenantId, "New asset")).thenReturn(null); - when(deviceService.findDeviceByTenantIdAndName(tenantId, "Existing device")).thenReturn(device); + when(deviceService.findDeviceByTenantIdAndName(tenantId, "Existing device")) + .thenReturn(existingDevice("Existing device")); when(deviceService.findDeviceByTenantIdAndName(tenantId, "New device")).thenReturn(null); SolutionInstallResponse result = service.validateSolution(tenantId, tempDir); @@ -184,9 +189,7 @@ class DefaultSolutionServiceTest { void testValidateSolutionLooksTheSameNameUpOnce() throws IOException { writeEntitiesFile("devices.json", "[{\"name\": \"Sensor\"}, {\"name\": \"Sensor\"}]"); - Device device = new Device(); - device.setName("Sensor"); - when(deviceService.findDeviceByTenantIdAndName(tenantId, "Sensor")).thenReturn(device); + when(deviceService.findDeviceByTenantIdAndName(tenantId, "Sensor")).thenReturn(existingDevice("Sensor")); SolutionInstallResponse result = service.validateSolution(tenantId, tempDir); @@ -227,23 +230,47 @@ class DefaultSolutionServiceTest { verifyNoInteractions(deviceService); } - @Test - void testValidateSolutionCapsTheNamesItLists() throws IOException { - String definitions = IntStream.rangeClosed(1, 12) - .mapToObj(i -> "{\"name\": \"Sensor " + i + "\"}") - .collect(Collectors.joining(",")); - writeEntitiesFile("devices.json", "[" + definitions + "]"); - for (int i = 1; i <= 12; i++) { - Device device = new Device(); - device.setName("Sensor " + i); - when(deviceService.findDeviceByTenantIdAndName(tenantId, "Sensor " + i)).thenReturn(device); + @ParameterizedTest + @ValueSource(ints = {LISTED_NAMES_PER_TYPE, LISTED_NAMES_PER_TYPE + 1, LISTED_NAMES_PER_TYPE + 2}) + void testValidateSolutionListsAtMostTenNamesOfAType(int conflictCount) throws IOException { + List names = IntStream.rangeClosed(1, conflictCount).mapToObj(i -> "Sensor " + i).toList(); + writeEntitiesFile("devices.json", names.stream() + .map(name -> "{\"name\": \"" + name + "\"}") + .collect(Collectors.joining(",", "[", "]"))); + names.forEach(name -> when(deviceService.findDeviceByTenantIdAndName(tenantId, name)) + .thenReturn(existingDevice(name))); + + SolutionInstallResponse result = service.validateSolution(tenantId, tempDir); + + int hidden = conflictCount - LISTED_NAMES_PER_TYPE; + String listed = names.stream().limit(LISTED_NAMES_PER_TYPE) + .map(name -> "'" + name + "'").collect(Collectors.joining(", ")); + assertThat(result.getDetails().lines().toList()).contains("- **Device**: " + listed + + (hidden > 0 ? " and " + hidden + " more (" + conflictCount + " in total)" : "")); + if (hidden > 0) { + assertThat(result.getDetails()).contains(TRUNCATION_NOTE); + } else { + assertThat(result.getDetails()).doesNotContain(TRUNCATION_NOTE); } + } + + /** + * The profile lists are the json file plus every file in the directory of the same name merged into one list, so + * this is where the same name genuinely can appear twice. + */ + @Test + void testValidateSolutionChecksAProfileFromBothSourcesOnce() throws IOException { + writeEntitiesFile("device_profiles.json", "[{\"name\": \"Sensor profile\"}]"); + writeFile("device_profiles/sensor_profile.json", "{\"name\": \"Sensor profile\"}"); + + DeviceProfile profile = new DeviceProfile(); + profile.setName("Sensor profile"); + when(deviceProfileService.findDeviceProfileByName(tenantId, "Sensor profile")).thenReturn(profile); SolutionInstallResponse result = service.validateSolution(tenantId, tempDir); - assertThat(result.getDetails().lines().toList()) - .contains("- **Device**: 'Sensor 1', 'Sensor 2', 'Sensor 3', 'Sensor 4', 'Sensor 5', 'Sensor 6', " - + "'Sensor 7', 'Sensor 8', 'Sensor 9', 'Sensor 10' and 2 more"); + assertThat(result.getDetails().lines().toList()).contains("- **Device profile**: 'Sensor profile'"); + verify(deviceProfileService, times(1)).findDeviceProfileByName(tenantId, "Sensor profile"); } @Test @@ -261,6 +288,12 @@ class DefaultSolutionServiceTest { deviceProfileService, assetProfileService, edgeService); } + private static Device existingDevice(String name) { + Device device = new Device(); + device.setName(name); + return device; + } + private void writeFile(String relativePath, String content) throws IOException { Path file = tempDir.resolve(relativePath); Files.createDirectories(file.getParent()); diff --git a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-install-dialog.component.ts b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-install-dialog.component.ts index 5fe6879e5e..552120b83f 100644 --- a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-install-dialog.component.ts +++ b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-install-dialog.component.ts @@ -308,7 +308,7 @@ export class TbIotHubInstallDialogComponent extends DialogComponent { if (!result.success) { this.state = 'error'; - this.errorMessage = result.errorMessage ?? ''; + this.errorMessage = result.errorMessage || ''; return; } this.handleInstalledDescriptor(result.descriptor); @@ -338,12 +338,11 @@ export class TbIotHubInstallDialogComponent extends DialogComponent !entry.root && entry.errorMessage && entry.status === InstallPlanEntryStatus.WILL_INSTALL) : undefined; if (failedDependency) { @@ -355,8 +354,8 @@ export class TbIotHubInstallDialogComponent extends DialogComponent 0) { - const warning = this.translate.instant('iot-hub.install-rollback-partial'); - message = message ? message + '\n\n' + warning : warning; + message = [message, this.translate.instant('iot-hub.install-rollback-partial')] + .filter(Boolean).join('\n\n'); } this.errorMessage = message; return; From dafefdcd8182385d595cb14b5b1b02245f1df223 Mon Sep 17 00:00:00 2001 From: dpinkevych Date: Wed, 9 Sep 2026 12:56:40 +0300 Subject: [PATCH 018/159] address the second PE review pass on the install report - rename the cap to MAX_LISTED_NAMES_PER_TYPE: it shortens the printed list, it does not limit what is validated - say how many conflicts a type has in total, and add a note when names were left out, so the "rename or delete them" instruction stays true - keep only the names in the conflict map, the entities were never read for anything else - one way of saying "there are no details" in the dialog, and one comment instead of two that open the same way - cover the whole branch of the cap (10, 11 and 12 names) and the profile name that comes from both the json file and the directory --- .../solutions/DefaultSolutionService.java | 36 ++++++---- .../solutions/DefaultSolutionServiceTest.java | 71 ++++++++++++++----- .../iot-hub-install-dialog.component.ts | 17 +++-- 3 files changed, 82 insertions(+), 42 deletions(-) diff --git a/application/src/main/java/org/thingsboard/server/service/solutions/DefaultSolutionService.java b/application/src/main/java/org/thingsboard/server/service/solutions/DefaultSolutionService.java index 43828a4891..b480afae0e 100644 --- a/application/src/main/java/org/thingsboard/server/service/solutions/DefaultSolutionService.java +++ b/application/src/main/java/org/thingsboard/server/service/solutions/DefaultSolutionService.java @@ -184,7 +184,9 @@ public class DefaultSolutionService implements SolutionService { private static final String CONFLICTS_INTRO = "Some entities of the solution template already exist. Rename or delete them and install the template again:"; private static final String RANDOM_PLACEHOLDER = "$random"; - private static final int MAX_REPORTED_CONFLICTS = 10; + private static final int MAX_LISTED_NAMES_PER_TYPE = 10; + private static final String TRUNCATION_NOTE = "Only the first " + MAX_LISTED_NAMES_PER_TYPE + + " names of each type are listed. The rest are reported the next time the template is installed."; @Value("${ui.solution_templates.docs_base_url:https://thingsboard.io/docs}") private String docsBaseUrl; @@ -323,7 +325,7 @@ public class DefaultSolutionService implements SolutionService { }); // Insertion ordered, so that the reported sections keep the order the entities are provisioned in. - Map> conflicts = new LinkedHashMap<>(); + Map> conflicts = new LinkedHashMap<>(); collectRuleChainConflicts(conflicts, tenantId, tempDir, ruleChains); collectConflicts(conflicts, EntityType.DEVICE_PROFILE, deviceProfiles, DeviceProfile::getName, name -> deviceProfileService.findDeviceProfileByName(tenantId, name)); @@ -340,8 +342,11 @@ public class DefaultSolutionService implements SolutionService { return null; } StringBuilder details = new StringBuilder(CONFLICTS_INTRO).append(BLANK_LINE); - conflicts.forEach((entityType, entities) -> appendConflicts(details, entityType, - entities.stream().map(entity -> "'" + entity.getName() + "'").toList())); + conflicts.forEach((entityType, names) -> appendConflicts(details, entityType, + names.stream().map(name -> "'" + name + "'").toList())); + if (conflicts.values().stream().anyMatch(names -> names.size() > MAX_LISTED_NAMES_PER_TYPE)) { + details.append(System.lineSeparator()).append(TRUNCATION_NOTE); + } SolutionInstallResponse solutionInstallResponse = new SolutionInstallResponse(); solutionInstallResponse.setSuccess(false); @@ -353,7 +358,7 @@ public class DefaultSolutionService implements SolutionService { * The entity type and the name both come from the definition, so a list can not end up checked against the * wrong type by mistake. */ - private void collectConflicts(Map> conflicts, List definitions, + private void collectConflicts(Map> conflicts, List definitions, Function lookup) { Set checked = new HashSet<>(); for (EntityDefinition definition : definitions) { @@ -363,7 +368,7 @@ public class DefaultSolutionService implements SolutionService { } } - private void collectConflicts(Map> conflicts, EntityType entityType, List definitions, + private void collectConflicts(Map> conflicts, EntityType entityType, List definitions, Function nameExtractor, Function lookup) { Set checked = new HashSet<>(); for (T definition : definitions) { @@ -374,14 +379,14 @@ public class DefaultSolutionService implements SolutionService { } } - private void collectConflict(Map> conflicts, EntityType entityType, String name, + private void collectConflict(Map> conflicts, EntityType entityType, String name, Function lookup) { if (StringUtils.isEmpty(name)) { return; } HasName existing = lookup.apply(name); if (existing != null) { - conflicts.computeIfAbsent(entityType, key -> new ArrayList<>()).add(existing); + conflicts.computeIfAbsent(entityType, key -> new ArrayList<>()).add(existing.getName()); } } @@ -389,7 +394,7 @@ public class DefaultSolutionService implements SolutionService { * A rule chain is created from the rule chain file, so both the name and the type of the chain the install will * produce live there - the name in rule_chains.json is only a reference and the type defaults to CORE. */ - private void collectRuleChainConflicts(Map> conflicts, TenantId tenantId, Path tempDir, + private void collectRuleChainConflicts(Map> conflicts, TenantId tenantId, Path tempDir, List definitions) { Set checked = new HashSet<>(); for (ReferenceableEntityDefinition definition : definitions) { @@ -428,13 +433,16 @@ public class DefaultSolutionService implements SolutionService { /** * One markdown list item per entity type, so that the names of the conflicting entities are what the user reads, - * instead of the same sentence repeated for every type. + * instead of the same sentence repeated for every type. Only the first {@value #MAX_LISTED_NAMES_PER_TYPE} + * names of a type are listed, the rest are counted - {@link #TRUNCATION_NOTE} tells the user that the list of + * that type is not complete. */ - private void appendConflicts(StringBuilder details, EntityType entityType, List conflictDescriptions) { + private static void appendConflicts(StringBuilder details, EntityType entityType, List conflictDescriptions) { details.append("- **").append(entityType.getNormalName()).append("**: ") - .append(conflictDescriptions.stream().limit(MAX_REPORTED_CONFLICTS).collect(Collectors.joining(", "))); - if (conflictDescriptions.size() > MAX_REPORTED_CONFLICTS) { - details.append(" and ").append(conflictDescriptions.size() - MAX_REPORTED_CONFLICTS).append(" more"); + .append(conflictDescriptions.stream().limit(MAX_LISTED_NAMES_PER_TYPE).collect(Collectors.joining(", "))); + if (conflictDescriptions.size() > MAX_LISTED_NAMES_PER_TYPE) { + details.append(" and ").append(conflictDescriptions.size() - MAX_LISTED_NAMES_PER_TYPE) + .append(" more (").append(conflictDescriptions.size()).append(" in total)"); } details.append(System.lineSeparator()); } diff --git a/application/src/test/java/org/thingsboard/server/service/solutions/DefaultSolutionServiceTest.java b/application/src/test/java/org/thingsboard/server/service/solutions/DefaultSolutionServiceTest.java index d28955e742..b1b5f1726a 100644 --- a/application/src/test/java/org/thingsboard/server/service/solutions/DefaultSolutionServiceTest.java +++ b/application/src/test/java/org/thingsboard/server/service/solutions/DefaultSolutionServiceTest.java @@ -18,6 +18,8 @@ package org.thingsboard.server.service.solutions; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.junit.jupiter.api.io.TempDir; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; @@ -61,6 +63,10 @@ class DefaultSolutionServiceTest { private static final String CONFLICTS_INTRO = "Some entities of the solution template already exist. Rename or delete them and install the template again:"; + // mirrors DefaultSolutionService.MAX_LISTED_NAMES_PER_TYPE and the note that goes with it + private static final int LISTED_NAMES_PER_TYPE = 10; + private static final String TRUNCATION_NOTE = "Only the first " + LISTED_NAMES_PER_TYPE + + " names of each type are listed. The rest are reported the next time the template is installed."; private final TenantId tenantId = TenantId.fromUUID(UUID.randomUUID()); @@ -95,15 +101,14 @@ class DefaultSolutionServiceTest { Customer customer = new Customer(); customer.setTitle("Existing customer"); - Device device = new Device(); - device.setName("Existing device"); when(customerService.findCustomerByTenantIdAndTitle(tenantId, "Existing customer")).thenReturn(Optional.of(customer)); Asset asset = new Asset(); asset.setName("Existing asset"); when(assetService.findAssetByTenantIdAndName(tenantId, "Existing asset")).thenReturn(asset); when(assetService.findAssetByTenantIdAndName(tenantId, "New asset")).thenReturn(null); - when(deviceService.findDeviceByTenantIdAndName(tenantId, "Existing device")).thenReturn(device); + when(deviceService.findDeviceByTenantIdAndName(tenantId, "Existing device")) + .thenReturn(existingDevice("Existing device")); when(deviceService.findDeviceByTenantIdAndName(tenantId, "New device")).thenReturn(null); SolutionInstallResponse result = service.validateSolution(tenantId, tempDir); @@ -184,9 +189,7 @@ class DefaultSolutionServiceTest { void testValidateSolutionLooksTheSameNameUpOnce() throws IOException { writeEntitiesFile("devices.json", "[{\"name\": \"Sensor\"}, {\"name\": \"Sensor\"}]"); - Device device = new Device(); - device.setName("Sensor"); - when(deviceService.findDeviceByTenantIdAndName(tenantId, "Sensor")).thenReturn(device); + when(deviceService.findDeviceByTenantIdAndName(tenantId, "Sensor")).thenReturn(existingDevice("Sensor")); SolutionInstallResponse result = service.validateSolution(tenantId, tempDir); @@ -227,23 +230,47 @@ class DefaultSolutionServiceTest { verifyNoInteractions(deviceService); } - @Test - void testValidateSolutionCapsTheNamesItLists() throws IOException { - String definitions = IntStream.rangeClosed(1, 12) - .mapToObj(i -> "{\"name\": \"Sensor " + i + "\"}") - .collect(Collectors.joining(",")); - writeEntitiesFile("devices.json", "[" + definitions + "]"); - for (int i = 1; i <= 12; i++) { - Device device = new Device(); - device.setName("Sensor " + i); - when(deviceService.findDeviceByTenantIdAndName(tenantId, "Sensor " + i)).thenReturn(device); + @ParameterizedTest + @ValueSource(ints = {LISTED_NAMES_PER_TYPE, LISTED_NAMES_PER_TYPE + 1, LISTED_NAMES_PER_TYPE + 2}) + void testValidateSolutionListsAtMostTenNamesOfAType(int conflictCount) throws IOException { + List names = IntStream.rangeClosed(1, conflictCount).mapToObj(i -> "Sensor " + i).toList(); + writeEntitiesFile("devices.json", names.stream() + .map(name -> "{\"name\": \"" + name + "\"}") + .collect(Collectors.joining(",", "[", "]"))); + names.forEach(name -> when(deviceService.findDeviceByTenantIdAndName(tenantId, name)) + .thenReturn(existingDevice(name))); + + SolutionInstallResponse result = service.validateSolution(tenantId, tempDir); + + int hidden = conflictCount - LISTED_NAMES_PER_TYPE; + String listed = names.stream().limit(LISTED_NAMES_PER_TYPE) + .map(name -> "'" + name + "'").collect(Collectors.joining(", ")); + assertThat(result.getDetails().lines().toList()).contains("- **Device**: " + listed + + (hidden > 0 ? " and " + hidden + " more (" + conflictCount + " in total)" : "")); + if (hidden > 0) { + assertThat(result.getDetails()).contains(TRUNCATION_NOTE); + } else { + assertThat(result.getDetails()).doesNotContain(TRUNCATION_NOTE); } + } + + /** + * The profile lists are the json file plus every file in the directory of the same name merged into one list, so + * this is where the same name genuinely can appear twice. + */ + @Test + void testValidateSolutionChecksAProfileFromBothSourcesOnce() throws IOException { + writeEntitiesFile("device_profiles.json", "[{\"name\": \"Sensor profile\"}]"); + writeFile("device_profiles/sensor_profile.json", "{\"name\": \"Sensor profile\"}"); + + DeviceProfile profile = new DeviceProfile(); + profile.setName("Sensor profile"); + when(deviceProfileService.findDeviceProfileByName(tenantId, "Sensor profile")).thenReturn(profile); SolutionInstallResponse result = service.validateSolution(tenantId, tempDir); - assertThat(result.getDetails().lines().toList()) - .contains("- **Device**: 'Sensor 1', 'Sensor 2', 'Sensor 3', 'Sensor 4', 'Sensor 5', 'Sensor 6', " - + "'Sensor 7', 'Sensor 8', 'Sensor 9', 'Sensor 10' and 2 more"); + assertThat(result.getDetails().lines().toList()).contains("- **Device profile**: 'Sensor profile'"); + verify(deviceProfileService, times(1)).findDeviceProfileByName(tenantId, "Sensor profile"); } @Test @@ -261,6 +288,12 @@ class DefaultSolutionServiceTest { deviceProfileService, assetProfileService, edgeService); } + private static Device existingDevice(String name) { + Device device = new Device(); + device.setName(name); + return device; + } + private void writeFile(String relativePath, String content) throws IOException { Path file = tempDir.resolve(relativePath); Files.createDirectories(file.getParent()); diff --git a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-install-dialog.component.ts b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-install-dialog.component.ts index 3198d8ff28..62865a2455 100644 --- a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-install-dialog.component.ts +++ b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-install-dialog.component.ts @@ -314,7 +314,7 @@ export class TbIotHubInstallDialogComponent extends DialogComponent { if (!result.success) { this.state = 'error'; - this.errorMessage = result.errorMessage ?? ''; + this.errorMessage = result.errorMessage || ''; return; } this.handleInstalledDescriptor(result.descriptor); @@ -344,12 +344,11 @@ export class TbIotHubInstallDialogComponent extends DialogComponent !entry.root && entry.errorMessage && entry.status === InstallPlanEntryStatus.WILL_INSTALL) : undefined; if (failedDependency) { @@ -361,8 +360,8 @@ export class TbIotHubInstallDialogComponent extends DialogComponent 0) { - const warning = this.translate.instant('iot-hub.install-rollback-partial'); - message = message ? message + '\n\n' + warning : warning; + message = [message, this.translate.instant('iot-hub.install-rollback-partial')] + .filter(Boolean).join('\n\n'); } this.errorMessage = message; return; From 27f83a1102a31e4538a092f82f6c720c1f8eead9 Mon Sep 17 00:00:00 2001 From: dpinkevych Date: Wed, 9 Sep 2026 13:56:22 +0300 Subject: [PATCH 019/159] name what the install still does not pre-validate The TODO predates the report and most of it is done now - customers, assets, devices, edges, dashboards, rule chains and both profile types are all checked before anything is created. What is left is the entities that still only fail at provision time. --- .../server/service/solutions/DefaultSolutionService.java | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/application/src/main/java/org/thingsboard/server/service/solutions/DefaultSolutionService.java b/application/src/main/java/org/thingsboard/server/service/solutions/DefaultSolutionService.java index d8ec610c58..ecdb313639 100644 --- a/application/src/main/java/org/thingsboard/server/service/solutions/DefaultSolutionService.java +++ b/application/src/main/java/org/thingsboard/server/service/solutions/DefaultSolutionService.java @@ -301,7 +301,8 @@ public class DefaultSolutionService implements SolutionService { } SolutionInstallResponse validateSolution(TenantId tenantId, Path tempDir) { - //TODO: check other entities. + //TODO: pre-validate what still only fails at provision time: customer users (unique by email), + // alarm rules and calculated fields. List ruleChains = loadListOfEntitiesIfFileExists(tempDir, "rule_chains.json", new TypeReference<>() { }); From 893101233911b0802f8c5417cba0f567996def2e Mon Sep 17 00:00:00 2001 From: dpinkevych Date: Wed, 9 Sep 2026 13:56:22 +0300 Subject: [PATCH 020/159] name what the install still does not pre-validate The TODO predates the report and most of it is done now - customers, assets, devices, edges, dashboards, rule chains and both profile types are all checked before anything is created. What is left is the entities that still only fail at provision time. --- .../server/service/solutions/DefaultSolutionService.java | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/application/src/main/java/org/thingsboard/server/service/solutions/DefaultSolutionService.java b/application/src/main/java/org/thingsboard/server/service/solutions/DefaultSolutionService.java index b480afae0e..70578444b1 100644 --- a/application/src/main/java/org/thingsboard/server/service/solutions/DefaultSolutionService.java +++ b/application/src/main/java/org/thingsboard/server/service/solutions/DefaultSolutionService.java @@ -303,7 +303,8 @@ public class DefaultSolutionService implements SolutionService { } SolutionInstallResponse validateSolution(TenantId tenantId, Path tempDir) { - //TODO: check other entities. + //TODO: pre-validate what still only fails at provision time: customer users (unique by email), + // alarm rules and calculated fields. List ruleChains = loadListOfEntitiesIfFileExists(tempDir, "rule_chains.json", new TypeReference<>() { }); From 99465e283cf8ee97ae722d590e191125f5b00078 Mon Sep 17 00:00:00 2001 From: dpinkevych Date: Wed, 9 Sep 2026 15:27:34 +0300 Subject: [PATCH 021/159] quote the names where the conflict is collected The map then holds what the report prints, which leaves appendConflicts a plain pass-through and matches PE, where the entity group descriptions arrive already formatted. --- .../service/solutions/DefaultSolutionService.java | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/application/src/main/java/org/thingsboard/server/service/solutions/DefaultSolutionService.java b/application/src/main/java/org/thingsboard/server/service/solutions/DefaultSolutionService.java index ecdb313639..b279d693ef 100644 --- a/application/src/main/java/org/thingsboard/server/service/solutions/DefaultSolutionService.java +++ b/application/src/main/java/org/thingsboard/server/service/solutions/DefaultSolutionService.java @@ -341,9 +341,8 @@ public class DefaultSolutionService implements SolutionService { return null; } StringBuilder details = new StringBuilder(CONFLICTS_INTRO).append(BLANK_LINE); - conflicts.forEach((entityType, names) -> appendConflicts(details, entityType, - names.stream().map(name -> "'" + name + "'").toList())); - if (conflicts.values().stream().anyMatch(names -> names.size() > MAX_LISTED_NAMES_PER_TYPE)) { + conflicts.forEach((entityType, conflictDescriptions) -> appendConflicts(details, entityType, conflictDescriptions)); + if (conflicts.values().stream().anyMatch(descriptions -> descriptions.size() > MAX_LISTED_NAMES_PER_TYPE)) { details.append(System.lineSeparator()).append(TRUNCATION_NOTE); } @@ -385,7 +384,7 @@ public class DefaultSolutionService implements SolutionService { } HasName existing = lookup.apply(name); if (existing != null) { - conflicts.computeIfAbsent(entityType, key -> new ArrayList<>()).add(existing.getName()); + conflicts.computeIfAbsent(entityType, key -> new ArrayList<>()).add(quoted(existing.getName())); } } @@ -430,6 +429,10 @@ public class DefaultSolutionService implements SolutionService { return title.contains(RANDOM_PLACEHOLDER); } + private static String quoted(String value) { + return "'" + value + "'"; + } + /** * One markdown list item per entity type, so that the names of the conflicting entities are what the user reads, * instead of the same sentence repeated for every type. Only the first {@value #MAX_LISTED_NAMES_PER_TYPE} From 3bc6f0c23564f6b8bb578b4a101de2ad7b10b7df Mon Sep 17 00:00:00 2001 From: dpinkevych Date: Wed, 9 Sep 2026 15:27:34 +0300 Subject: [PATCH 022/159] quote the names where the conflict is collected The map then holds what the report prints, which leaves appendConflicts a plain pass-through and matches PE, where the entity group descriptions arrive already formatted. --- .../service/solutions/DefaultSolutionService.java | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/application/src/main/java/org/thingsboard/server/service/solutions/DefaultSolutionService.java b/application/src/main/java/org/thingsboard/server/service/solutions/DefaultSolutionService.java index 70578444b1..81000b6e45 100644 --- a/application/src/main/java/org/thingsboard/server/service/solutions/DefaultSolutionService.java +++ b/application/src/main/java/org/thingsboard/server/service/solutions/DefaultSolutionService.java @@ -343,9 +343,8 @@ public class DefaultSolutionService implements SolutionService { return null; } StringBuilder details = new StringBuilder(CONFLICTS_INTRO).append(BLANK_LINE); - conflicts.forEach((entityType, names) -> appendConflicts(details, entityType, - names.stream().map(name -> "'" + name + "'").toList())); - if (conflicts.values().stream().anyMatch(names -> names.size() > MAX_LISTED_NAMES_PER_TYPE)) { + conflicts.forEach((entityType, conflictDescriptions) -> appendConflicts(details, entityType, conflictDescriptions)); + if (conflicts.values().stream().anyMatch(descriptions -> descriptions.size() > MAX_LISTED_NAMES_PER_TYPE)) { details.append(System.lineSeparator()).append(TRUNCATION_NOTE); } @@ -387,7 +386,7 @@ public class DefaultSolutionService implements SolutionService { } HasName existing = lookup.apply(name); if (existing != null) { - conflicts.computeIfAbsent(entityType, key -> new ArrayList<>()).add(existing.getName()); + conflicts.computeIfAbsent(entityType, key -> new ArrayList<>()).add(quoted(existing.getName())); } } @@ -432,6 +431,10 @@ public class DefaultSolutionService implements SolutionService { return title.contains(RANDOM_PLACEHOLDER); } + private static String quoted(String value) { + return "'" + value + "'"; + } + /** * One markdown list item per entity type, so that the names of the conflicting entities are what the user reads, * instead of the same sentence repeated for every type. Only the first {@value #MAX_LISTED_NAMES_PER_TYPE} From 8c14d1dee0f297e344c8abb5882593e7c9a81651 Mon Sep 17 00:00:00 2001 From: nickAS21 Date: Wed, 9 Sep 2026 16:35:36 +0300 Subject: [PATCH 023/159] lwm2m: fix bootstrap-short-server-id = null --- .../src/main/resources/thingsboard.yml | 4 +- .../server/edge/DeviceProfileEdgeTest.java | 30 +++++------ .../lwm2m/AbstractLwM2MIntegrationTest.java | 25 +++++---- .../AbstractSecurityLwM2MIntegrationTest.java | 52 +++++++++--------- ...oSecLwM2MIntegrationDtlsCidLengthTest.java | 2 +- .../PskLwm2mIntegrationDtlsCidLengthTest.java | 2 +- .../PskLwm2mIntegrationDtlsCidLengthTest.java | 3 +- ...oSecLwM2MIntegrationDtlsCidLengthTest.java | 3 +- .../PskLwm2mIntegrationDtlsCidLengthTest.java | 3 +- .../PskLwm2mIntegrationDtlsCidLengthTest.java | 2 +- .../PskLwm2mIntegrationDtlsCidLengthTest.java | 2 +- ...oSecLwM2MIntegrationDtlsCidLengthTest.java | 2 +- .../PskLwm2mIntegrationDtlsCidLengthTest.java | 2 +- .../LwM2MIntegrationDiffPortTest.java | 4 +- .../security/sql/PskLwm2mIntegrationTest.java | 14 ++--- .../security/sql/RpkLwM2MIntegrationTest.java | 8 +-- .../sql/X509_NoTrustLwM2MIntegrationTest.java | 8 +-- .../sql/X509_TrustLwM2MIntegrationTest.java | 4 +- .../bootstrap/LwM2MServerSecurityConfig.java | 6 +-- .../secure/LwM2MBootstrapConfig.java | 3 -- .../validator/DeviceProfileDataValidator.java | 53 ++++++++++++++++--- .../src/main/resources/tb-lwm2m-transport.yml | 4 +- 22 files changed, 133 insertions(+), 103 deletions(-) diff --git a/application/src/main/resources/thingsboard.yml b/application/src/main/resources/thingsboard.yml index 7a2e002750..77369c73e2 100644 --- a/application/src/main/resources/thingsboard.yml +++ b/application/src/main/resources/thingsboard.yml @@ -1344,8 +1344,8 @@ transport: bootstrap: # Enable/disable Bootstrap Server enabled: "${LWM2M_ENABLED_BS:true}" - # Default value in LwM2M client after start in mode Bootstrap for the object : name "LWM2M Security" field: "Short Server ID" (deviceProfile: Bootstrap.BOOTSTRAP SERVER.Short ID) - id: "${LWM2M_SERVER_ID_BS:0}" + # Short Server ID for Bootstrap Server is not applicable according to OMA LwM2M spec (Object 0 Resource 10 must be omitted/null for Bootstrap Server). + id: "${LWM2M_SERVER_ID_BS:}" # LwM2M bootstrap server bind address. Bind to all interfaces by default bind_address: "${LWM2M_BS_BIND_ADDRESS:0.0.0.0}" # LwM2M bootstrap server bind port diff --git a/application/src/test/java/org/thingsboard/server/edge/DeviceProfileEdgeTest.java b/application/src/test/java/org/thingsboard/server/edge/DeviceProfileEdgeTest.java index 3ac7b3d648..8646a69751 100644 --- a/application/src/test/java/org/thingsboard/server/edge/DeviceProfileEdgeTest.java +++ b/application/src/test/java/org/thingsboard/server/edge/DeviceProfileEdgeTest.java @@ -245,13 +245,13 @@ public class DeviceProfileEdgeTest extends AbstractEdgeTest { Assert.assertFalse(transportConfiguration.getBootstrap().isEmpty()); LwM2MBootstrapServerCredential lwM2MBootstrapServerCredential = transportConfiguration.getBootstrap().get(0); Assert.assertTrue(lwM2MBootstrapServerCredential instanceof NoSecLwM2MBootstrapServerCredential); - NoSecLwM2MBootstrapServerCredential noSecLwM2MBootstrapServerCredential = (NoSecLwM2MBootstrapServerCredential) lwM2MBootstrapServerCredential; + NoSecLwM2MBootstrapServerCredential noSecLwM2MBootstrapSectionDmServerCredential = (NoSecLwM2MBootstrapServerCredential) lwM2MBootstrapServerCredential; - Assert.assertEquals("PUBLIC_KEY", noSecLwM2MBootstrapServerCredential.getServerPublicKey()); - Assert.assertEquals(Integer.valueOf(123), noSecLwM2MBootstrapServerCredential.getShortServerId()); - Assert.assertFalse(noSecLwM2MBootstrapServerCredential.isBootstrapServerIs()); - Assert.assertEquals("localhost", noSecLwM2MBootstrapServerCredential.getHost()); - Assert.assertEquals(Integer.valueOf(5685), noSecLwM2MBootstrapServerCredential.getPort()); + Assert.assertEquals("PUBLIC_KEY", noSecLwM2MBootstrapSectionDmServerCredential.getServerPublicKey()); + Assert.assertEquals(Integer.valueOf(123), noSecLwM2MBootstrapSectionDmServerCredential.getShortServerId()); + Assert.assertFalse(noSecLwM2MBootstrapSectionDmServerCredential.isBootstrapServerIs()); + Assert.assertEquals("localhost", noSecLwM2MBootstrapSectionDmServerCredential.getHost()); + Assert.assertEquals(Integer.valueOf(5685), noSecLwM2MBootstrapSectionDmServerCredential.getPort()); TelemetryMappingConfiguration observeAttr = transportConfiguration.getObserveAttr(); Assert.assertEquals("batteryLevel", observeAttr.getKeyName().get("/3_1.2/0/9")); @@ -413,15 +413,15 @@ public class DeviceProfileEdgeTest extends AbstractEdgeTest { JacksonUtil.fromString(AbstractLwM2MIntegrationTest.TELEMETRY_WITHOUT_OBSERVE, TelemetryMappingConfiguration.class); transportConfiguration.setObserveAttr(observeAttrConfiguration); - List bootstrap = new ArrayList<>(); - AbstractLwM2MBootstrapServerCredential bootstrapServerCredential = new NoSecLwM2MBootstrapServerCredential(); - bootstrapServerCredential.setServerPublicKey("PUBLIC_KEY"); - bootstrapServerCredential.setShortServerId(123); - bootstrapServerCredential.setBootstrapServerIs(false); - bootstrapServerCredential.setHost("localhost"); - bootstrapServerCredential.setPort(5685); - bootstrap.add(bootstrapServerCredential); - transportConfiguration.setBootstrap(bootstrap); + List bootstrapSections = new ArrayList<>(); + AbstractLwM2MBootstrapServerCredential bootstrapSectionServerCredential = new NoSecLwM2MBootstrapServerCredential(); + bootstrapSectionServerCredential.setServerPublicKey("PUBLIC_KEY"); + bootstrapSectionServerCredential.setShortServerId(123); + bootstrapSectionServerCredential.setBootstrapServerIs(false); + bootstrapSectionServerCredential.setHost("localhost"); + bootstrapSectionServerCredential.setPort(5685); + bootstrapSections.add(bootstrapSectionServerCredential); + transportConfiguration.setBootstrap(bootstrapSections); return transportConfiguration; } diff --git a/application/src/test/java/org/thingsboard/server/transport/lwm2m/AbstractLwM2MIntegrationTest.java b/application/src/test/java/org/thingsboard/server/transport/lwm2m/AbstractLwM2MIntegrationTest.java index 258a173451..527915062e 100644 --- a/application/src/test/java/org/thingsboard/server/transport/lwm2m/AbstractLwM2MIntegrationTest.java +++ b/application/src/test/java/org/thingsboard/server/transport/lwm2m/AbstractLwM2MIntegrationTest.java @@ -19,7 +19,6 @@ import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.node.ObjectNode; import com.google.gson.JsonArray; import com.google.gson.JsonElement; -import jnr.ffi.annotations.In; import lombok.extern.slf4j.Slf4j; import org.apache.commons.io.IOUtils; import org.awaitility.core.ConditionTimeoutException; @@ -725,28 +724,28 @@ public abstract class AbstractLwM2MIntegrationTest extends AbstractTransportInte List bootstrap = new ArrayList<>(); switch (bootstrapConfigType) { case BOTH: - bootstrap.add(getBootstrapServerCredentialNoSec(false)); - bootstrap.add(getBootstrapServerCredentialNoSec(true)); + bootstrap.add(getBootstrapSectionServerCredentialNoSec(false)); + bootstrap.add(getBootstrapSectionServerCredentialNoSec(true)); break; case BOOTSTRAP_ONLY: - bootstrap.add(getBootstrapServerCredentialNoSec(true)); + bootstrap.add(getBootstrapSectionServerCredentialNoSec(true)); break; case LWM2M_ONLY: - bootstrap.add(getBootstrapServerCredentialNoSec(false)); + bootstrap.add(getBootstrapSectionServerCredentialNoSec(false)); break; case NONE: } return bootstrap; } - protected AbstractLwM2MBootstrapServerCredential getBootstrapServerCredentialNoSec(boolean isBootstrap) { - AbstractLwM2MBootstrapServerCredential bootstrapServerCredential = new NoSecLwM2MBootstrapServerCredential(); - bootstrapServerCredential.setServerPublicKey(""); - bootstrapServerCredential.setShortServerId(isBootstrap ? null : shortServerId); - bootstrapServerCredential.setBootstrapServerIs(isBootstrap); - bootstrapServerCredential.setHost(isBootstrap ? LWM2M_BOOTSTRAP_HOST : LWM2M_HOST); - bootstrapServerCredential.setPort(isBootstrap ? LWM2M_BOOTSTRAP_PORT : LWM2M_PORT); - return bootstrapServerCredential; + protected AbstractLwM2MBootstrapServerCredential getBootstrapSectionServerCredentialNoSec(boolean isBootstrap) { + AbstractLwM2MBootstrapServerCredential bootstrapSectionServerCredential = new NoSecLwM2MBootstrapServerCredential(); + bootstrapSectionServerCredential.setServerPublicKey(""); + bootstrapSectionServerCredential.setShortServerId(isBootstrap ? null : shortServerId); + bootstrapSectionServerCredential.setBootstrapServerIs(isBootstrap); + bootstrapSectionServerCredential.setHost(isBootstrap ? LWM2M_BOOTSTRAP_HOST : LWM2M_HOST); + bootstrapSectionServerCredential.setPort(isBootstrap ? LWM2M_BOOTSTRAP_PORT : LWM2M_PORT); + return bootstrapSectionServerCredential; } protected LwM2MDeviceCredentials getDeviceCredentialsNoSec(LwM2MClientCredential clientCredentials) { diff --git a/application/src/test/java/org/thingsboard/server/transport/lwm2m/security/AbstractSecurityLwM2MIntegrationTest.java b/application/src/test/java/org/thingsboard/server/transport/lwm2m/security/AbstractSecurityLwM2MIntegrationTest.java index 52bef912f2..55471f2d20 100644 --- a/application/src/test/java/org/thingsboard/server/transport/lwm2m/security/AbstractSecurityLwM2MIntegrationTest.java +++ b/application/src/test/java/org/thingsboard/server/transport/lwm2m/security/AbstractSecurityLwM2MIntegrationTest.java @@ -239,10 +239,10 @@ public abstract class AbstractSecurityLwM2MIntegrationTest extends AbstractLwM2M public void basicTestConnectionBootstrapRequestTriggerBefore(String clientEndpoint, String awaitAlias, LwM2MProfileBootstrapConfigType type, int cnt) throws Exception { List bootstrapServerCredentialsNoSec = getBootstrapServerCredentialsNoSec(type); for (int i = 2; i <= cnt; i++) { - AbstractLwM2MBootstrapServerCredential bsCredential = getBootstrapServerCredentialNoSec(false); - bsCredential.setHost("0.0.0." + i); - bsCredential.setShortServerId(bsCredential.getShortServerId() + i); - bootstrapServerCredentialsNoSec.add(bsCredential); + AbstractLwM2MBootstrapServerCredential bsSectionCredential = getBootstrapSectionServerCredentialNoSec(false); + bsSectionCredential.setHost("0.0.0." + i); + bsSectionCredential.setShortServerId(bsSectionCredential.getShortServerId() + i); + bootstrapServerCredentialsNoSec.add(bsSectionCredential); } Lwm2mDeviceProfileTransportConfiguration transportConfiguration = getTransportConfiguration(OBSERVE_ATTRIBUTES_WITHOUT_PARAMS, bootstrapServerCredentialsNoSec); LwM2MDeviceCredentials deviceCredentials = getDeviceCredentialsNoSec(createNoSecClientCredentials(clientEndpoint)); @@ -316,46 +316,46 @@ public abstract class AbstractSecurityLwM2MIntegrationTest extends AbstractLwM2M Assert.assertTrue(lwM2MTestClient.getClientStates().containsAll(expectedStatusesBs)); } - protected List getBootstrapServerCredentialsSecure(LwM2MSecurityMode mode, LwM2MProfileBootstrapConfigType bootstrapConfigType) { - List bootstrap = new ArrayList<>(); + protected List getBootstrapSectionsServerCredentialsSecure(LwM2MSecurityMode mode, LwM2MProfileBootstrapConfigType bootstrapConfigType) { + List bootstrapSections = new ArrayList<>(); switch (bootstrapConfigType) { case BOTH: - bootstrap.add(getBootstrapServerCredential(mode, false)); - bootstrap.add(getBootstrapServerCredential(mode, true)); + bootstrapSections.add(getBootstrapSectionServerCredential(mode, false)); + bootstrapSections.add(getBootstrapSectionServerCredential(mode, true)); break; case BOOTSTRAP_ONLY: - bootstrap.add(getBootstrapServerCredential(mode, true)); + bootstrapSections.add(getBootstrapSectionServerCredential(mode, true)); break; case LWM2M_ONLY: - bootstrap.add(getBootstrapServerCredential(mode, false)); + bootstrapSections.add(getBootstrapSectionServerCredential(mode, false)); break; case NONE: } - return bootstrap; + return bootstrapSections; } - private AbstractLwM2MBootstrapServerCredential getBootstrapServerCredential(LwM2MSecurityMode mode, boolean isBootstrap) { - AbstractLwM2MBootstrapServerCredential bootstrapServerCredential; + private AbstractLwM2MBootstrapServerCredential getBootstrapSectionServerCredential(LwM2MSecurityMode mode, boolean isBootstrap) { + AbstractLwM2MBootstrapServerCredential bootstrapSectionServerCredential; switch (mode) { case PSK: - bootstrapServerCredential = new PSKLwM2MBootstrapServerCredential(); - bootstrapServerCredential.setServerPublicKey(""); + bootstrapSectionServerCredential = new PSKLwM2MBootstrapServerCredential(); + bootstrapSectionServerCredential.setServerPublicKey(""); break; case RPK: - bootstrapServerCredential = new RPKLwM2MBootstrapServerCredential(); + bootstrapSectionServerCredential = new RPKLwM2MBootstrapServerCredential(); if (isBootstrap) { - bootstrapServerCredential.setServerPublicKey(Base64.encodeBase64String(serverPublicKeyFromCertBs.getEncoded())); + bootstrapSectionServerCredential.setServerPublicKey(Base64.encodeBase64String(serverPublicKeyFromCertBs.getEncoded())); } else { - bootstrapServerCredential.setServerPublicKey(Base64.encodeBase64String(serverPublicKeyFromCert.getEncoded())); + bootstrapSectionServerCredential.setServerPublicKey(Base64.encodeBase64String(serverPublicKeyFromCert.getEncoded())); } break; case X509: - bootstrapServerCredential = new X509LwM2MBootstrapServerCredential(); + bootstrapSectionServerCredential = new X509LwM2MBootstrapServerCredential(); try { if (isBootstrap) { - bootstrapServerCredential.setServerPublicKey(Base64.encodeBase64String(serverX509CertBs.getEncoded())); + bootstrapSectionServerCredential.setServerPublicKey(Base64.encodeBase64String(serverX509CertBs.getEncoded())); } else { - bootstrapServerCredential.setServerPublicKey(Base64.encodeBase64String(serverX509Cert.getEncoded())); + bootstrapSectionServerCredential.setServerPublicKey(Base64.encodeBase64String(serverX509Cert.getEncoded())); } } catch (CertificateEncodingException e) { e.printStackTrace(); @@ -364,11 +364,11 @@ public abstract class AbstractSecurityLwM2MIntegrationTest extends AbstractLwM2M default: throw new IllegalStateException("Unexpected value: " + mode); } - bootstrapServerCredential.setShortServerId(isBootstrap ? null : shortServerId); - bootstrapServerCredential.setBootstrapServerIs(isBootstrap); - bootstrapServerCredential.setHost(isBootstrap ? LWM2M_BOOTSTRAP_HOST : LWM2M_HOST); - bootstrapServerCredential.setPort(isBootstrap ? LWM2MS_BOOTSTRAP_PORT : LWM2MS_PORT); - return bootstrapServerCredential; + bootstrapSectionServerCredential.setShortServerId(isBootstrap ? null : shortServerId); + bootstrapSectionServerCredential.setBootstrapServerIs(isBootstrap); + bootstrapSectionServerCredential.setHost(isBootstrap ? LWM2M_BOOTSTRAP_HOST : LWM2M_HOST); + bootstrapSectionServerCredential.setPort(isBootstrap ? LWM2MS_BOOTSTRAP_PORT : LWM2MS_PORT); + return bootstrapSectionServerCredential; } diff --git a/application/src/test/java/org/thingsboard/server/transport/lwm2m/security/cid/serverDtlsCidLength_0/NoSecLwM2MIntegrationDtlsCidLengthTest.java b/application/src/test/java/org/thingsboard/server/transport/lwm2m/security/cid/serverDtlsCidLength_0/NoSecLwM2MIntegrationDtlsCidLengthTest.java index 5c2a4ceb29..5cec2a0a89 100644 --- a/application/src/test/java/org/thingsboard/server/transport/lwm2m/security/cid/serverDtlsCidLength_0/NoSecLwM2MIntegrationDtlsCidLengthTest.java +++ b/application/src/test/java/org/thingsboard/server/transport/lwm2m/security/cid/serverDtlsCidLength_0/NoSecLwM2MIntegrationDtlsCidLengthTest.java @@ -26,7 +26,7 @@ public class NoSecLwM2MIntegrationDtlsCidLengthTest extends AbstractSecurityLwM2 @Before public void setUpNoSecDtlsCidLength() { - transportConfiguration = getTransportConfiguration(OBSERVE_ATTRIBUTES_WITHOUT_PARAMS, getBootstrapServerCredentialsSecure(NO_SEC, NONE)); + transportConfiguration = getTransportConfiguration(OBSERVE_ATTRIBUTES_WITHOUT_PARAMS, getBootstrapSectionsServerCredentialsSecure(NO_SEC, NONE)); awaitAlias = "await on client state (NoSec_Lwm2m) serverDtlsCidLength = 0"; } diff --git a/application/src/test/java/org/thingsboard/server/transport/lwm2m/security/cid/serverDtlsCidLength_0/PskLwm2mIntegrationDtlsCidLengthTest.java b/application/src/test/java/org/thingsboard/server/transport/lwm2m/security/cid/serverDtlsCidLength_0/PskLwm2mIntegrationDtlsCidLengthTest.java index d080e1bc65..0773e56aed 100644 --- a/application/src/test/java/org/thingsboard/server/transport/lwm2m/security/cid/serverDtlsCidLength_0/PskLwm2mIntegrationDtlsCidLengthTest.java +++ b/application/src/test/java/org/thingsboard/server/transport/lwm2m/security/cid/serverDtlsCidLength_0/PskLwm2mIntegrationDtlsCidLengthTest.java @@ -26,7 +26,7 @@ public class PskLwm2mIntegrationDtlsCidLengthTest extends AbstractSecurityLwM2MI @Before public void createProfileRpc() { - transportConfiguration = getTransportConfiguration(OBSERVE_ATTRIBUTES_WITHOUT_PARAMS, getBootstrapServerCredentialsSecure(PSK, NONE)); + transportConfiguration = getTransportConfiguration(OBSERVE_ATTRIBUTES_WITHOUT_PARAMS, getBootstrapSectionsServerCredentialsSecure(PSK, NONE)); awaitAlias = "await on client state (Psk_Lwm2m) serverDtlsCidLength = 0"; } diff --git a/application/src/test/java/org/thingsboard/server/transport/lwm2m/security/cid/serverDtlsCidLength_1/PskLwm2mIntegrationDtlsCidLengthTest.java b/application/src/test/java/org/thingsboard/server/transport/lwm2m/security/cid/serverDtlsCidLength_1/PskLwm2mIntegrationDtlsCidLengthTest.java index d39afdd504..124d32e090 100644 --- a/application/src/test/java/org/thingsboard/server/transport/lwm2m/security/cid/serverDtlsCidLength_1/PskLwm2mIntegrationDtlsCidLengthTest.java +++ b/application/src/test/java/org/thingsboard/server/transport/lwm2m/security/cid/serverDtlsCidLength_1/PskLwm2mIntegrationDtlsCidLengthTest.java @@ -17,7 +17,6 @@ package org.thingsboard.server.transport.lwm2m.security.cid.serverDtlsCidLength_ import org.junit.Before; import org.junit.Test; -import org.thingsboard.server.transport.lwm2m.security.cid.AbstractSecurityLwM2MIntegrationDtlsCidLength0Test; import org.thingsboard.server.transport.lwm2m.security.cid.AbstractSecurityLwM2MIntegrationDtlsCidLength1Test; import static org.thingsboard.server.common.data.device.credentials.lwm2m.LwM2MSecurityMode.PSK; @@ -27,7 +26,7 @@ public class PskLwm2mIntegrationDtlsCidLengthTest extends AbstractSecurityLwM2MI @Before public void createProfileRpc() { - transportConfiguration = getTransportConfiguration(OBSERVE_ATTRIBUTES_WITHOUT_PARAMS, getBootstrapServerCredentialsSecure(PSK, NONE)); + transportConfiguration = getTransportConfiguration(OBSERVE_ATTRIBUTES_WITHOUT_PARAMS, getBootstrapSectionsServerCredentialsSecure(PSK, NONE)); awaitAlias = "await on client state (Psk_Lwm2m) serverDtlsCidLength = 1"; } diff --git a/application/src/test/java/org/thingsboard/server/transport/lwm2m/security/cid/serverDtlsCidLength_16/NoSecLwM2MIntegrationDtlsCidLengthTest.java b/application/src/test/java/org/thingsboard/server/transport/lwm2m/security/cid/serverDtlsCidLength_16/NoSecLwM2MIntegrationDtlsCidLengthTest.java index ca36137295..d59d2c7d60 100644 --- a/application/src/test/java/org/thingsboard/server/transport/lwm2m/security/cid/serverDtlsCidLength_16/NoSecLwM2MIntegrationDtlsCidLengthTest.java +++ b/application/src/test/java/org/thingsboard/server/transport/lwm2m/security/cid/serverDtlsCidLength_16/NoSecLwM2MIntegrationDtlsCidLengthTest.java @@ -18,7 +18,6 @@ package org.thingsboard.server.transport.lwm2m.security.cid.serverDtlsCidLength_ import org.junit.Before; import org.junit.Test; import org.thingsboard.server.transport.lwm2m.security.cid.AbstractSecurityLwM2MIntegrationDtlsCidLength16Test; -import org.thingsboard.server.transport.lwm2m.security.cid.AbstractSecurityLwM2MIntegrationDtlsCidLength4Test; import static org.thingsboard.server.common.data.device.credentials.lwm2m.LwM2MSecurityMode.NO_SEC; import static org.thingsboard.server.transport.lwm2m.Lwm2mTestHelper.LwM2MProfileBootstrapConfigType.NONE; @@ -27,7 +26,7 @@ public class NoSecLwM2MIntegrationDtlsCidLengthTest extends AbstractSecurityLwM2 @Before public void setUpNoSecDtlsCidLength() { - transportConfiguration = getTransportConfiguration(OBSERVE_ATTRIBUTES_WITHOUT_PARAMS, getBootstrapServerCredentialsSecure(NO_SEC, NONE)); + transportConfiguration = getTransportConfiguration(OBSERVE_ATTRIBUTES_WITHOUT_PARAMS, getBootstrapSectionsServerCredentialsSecure(NO_SEC, NONE)); awaitAlias = "await on client state (NoSec_Lwm2m) serverDtlsCidLength = 16"; } diff --git a/application/src/test/java/org/thingsboard/server/transport/lwm2m/security/cid/serverDtlsCidLength_16/PskLwm2mIntegrationDtlsCidLengthTest.java b/application/src/test/java/org/thingsboard/server/transport/lwm2m/security/cid/serverDtlsCidLength_16/PskLwm2mIntegrationDtlsCidLengthTest.java index 45b52c6ddd..90955c2a44 100644 --- a/application/src/test/java/org/thingsboard/server/transport/lwm2m/security/cid/serverDtlsCidLength_16/PskLwm2mIntegrationDtlsCidLengthTest.java +++ b/application/src/test/java/org/thingsboard/server/transport/lwm2m/security/cid/serverDtlsCidLength_16/PskLwm2mIntegrationDtlsCidLengthTest.java @@ -18,7 +18,6 @@ package org.thingsboard.server.transport.lwm2m.security.cid.serverDtlsCidLength_ import org.junit.Before; import org.junit.Test; import org.thingsboard.server.transport.lwm2m.security.cid.AbstractSecurityLwM2MIntegrationDtlsCidLength16Test; -import org.thingsboard.server.transport.lwm2m.security.cid.AbstractSecurityLwM2MIntegrationDtlsCidLength4Test; import static org.thingsboard.server.common.data.device.credentials.lwm2m.LwM2MSecurityMode.PSK; import static org.thingsboard.server.transport.lwm2m.Lwm2mTestHelper.LwM2MProfileBootstrapConfigType.NONE; @@ -27,7 +26,7 @@ public class PskLwm2mIntegrationDtlsCidLengthTest extends AbstractSecurityLwM2MI @Before public void createProfileRpc() { - transportConfiguration = getTransportConfiguration(OBSERVE_ATTRIBUTES_WITHOUT_PARAMS, getBootstrapServerCredentialsSecure(PSK, NONE)); + transportConfiguration = getTransportConfiguration(OBSERVE_ATTRIBUTES_WITHOUT_PARAMS, getBootstrapSectionsServerCredentialsSecure(PSK, NONE)); awaitAlias = "await on client state (Psk_Lwm2m) serverDtlsCidLength = 16"; } diff --git a/application/src/test/java/org/thingsboard/server/transport/lwm2m/security/cid/serverDtlsCidLength_2/PskLwm2mIntegrationDtlsCidLengthTest.java b/application/src/test/java/org/thingsboard/server/transport/lwm2m/security/cid/serverDtlsCidLength_2/PskLwm2mIntegrationDtlsCidLengthTest.java index 2e0b40da3d..ff4692bf63 100644 --- a/application/src/test/java/org/thingsboard/server/transport/lwm2m/security/cid/serverDtlsCidLength_2/PskLwm2mIntegrationDtlsCidLengthTest.java +++ b/application/src/test/java/org/thingsboard/server/transport/lwm2m/security/cid/serverDtlsCidLength_2/PskLwm2mIntegrationDtlsCidLengthTest.java @@ -26,7 +26,7 @@ public class PskLwm2mIntegrationDtlsCidLengthTest extends AbstractSecurityLwM2MI @Before public void createProfileRpc() { - transportConfiguration = getTransportConfiguration(OBSERVE_ATTRIBUTES_WITHOUT_PARAMS, getBootstrapServerCredentialsSecure(PSK, NONE)); + transportConfiguration = getTransportConfiguration(OBSERVE_ATTRIBUTES_WITHOUT_PARAMS, getBootstrapSectionsServerCredentialsSecure(PSK, NONE)); awaitAlias = "await on client state (Psk_Lwm2m) serverDtlsCidLength = 2"; } diff --git a/application/src/test/java/org/thingsboard/server/transport/lwm2m/security/cid/serverDtlsCidLength_4/PskLwm2mIntegrationDtlsCidLengthTest.java b/application/src/test/java/org/thingsboard/server/transport/lwm2m/security/cid/serverDtlsCidLength_4/PskLwm2mIntegrationDtlsCidLengthTest.java index aa281020a7..ff76104a30 100644 --- a/application/src/test/java/org/thingsboard/server/transport/lwm2m/security/cid/serverDtlsCidLength_4/PskLwm2mIntegrationDtlsCidLengthTest.java +++ b/application/src/test/java/org/thingsboard/server/transport/lwm2m/security/cid/serverDtlsCidLength_4/PskLwm2mIntegrationDtlsCidLengthTest.java @@ -26,7 +26,7 @@ public class PskLwm2mIntegrationDtlsCidLengthTest extends AbstractSecurityLwM2MI @Before public void createProfileRpc() { - transportConfiguration = getTransportConfiguration(OBSERVE_ATTRIBUTES_WITHOUT_PARAMS, getBootstrapServerCredentialsSecure(PSK, NONE)); + transportConfiguration = getTransportConfiguration(OBSERVE_ATTRIBUTES_WITHOUT_PARAMS, getBootstrapSectionsServerCredentialsSecure(PSK, NONE)); awaitAlias = "await on client state (Psk_Lwm2m) serverDtlsCidLength = 4"; } diff --git a/application/src/test/java/org/thingsboard/server/transport/lwm2m/security/cid/serverDtlsCidLength_null/NoSecLwM2MIntegrationDtlsCidLengthTest.java b/application/src/test/java/org/thingsboard/server/transport/lwm2m/security/cid/serverDtlsCidLength_null/NoSecLwM2MIntegrationDtlsCidLengthTest.java index 88bc5a2622..da5ef9085e 100644 --- a/application/src/test/java/org/thingsboard/server/transport/lwm2m/security/cid/serverDtlsCidLength_null/NoSecLwM2MIntegrationDtlsCidLengthTest.java +++ b/application/src/test/java/org/thingsboard/server/transport/lwm2m/security/cid/serverDtlsCidLength_null/NoSecLwM2MIntegrationDtlsCidLengthTest.java @@ -26,7 +26,7 @@ public class NoSecLwM2MIntegrationDtlsCidLengthTest extends AbstractSecurityLwM2 @Before public void setUpNoSecDtlsCidLength() { - transportConfiguration = getTransportConfiguration(OBSERVE_ATTRIBUTES_WITHOUT_PARAMS, getBootstrapServerCredentialsSecure(NO_SEC, NONE)); + transportConfiguration = getTransportConfiguration(OBSERVE_ATTRIBUTES_WITHOUT_PARAMS, getBootstrapSectionsServerCredentialsSecure(NO_SEC, NONE)); awaitAlias = "await on client state (NoSec_Lwm2m) serverDtlsCidLength = Null"; } diff --git a/application/src/test/java/org/thingsboard/server/transport/lwm2m/security/cid/serverDtlsCidLength_null/PskLwm2mIntegrationDtlsCidLengthTest.java b/application/src/test/java/org/thingsboard/server/transport/lwm2m/security/cid/serverDtlsCidLength_null/PskLwm2mIntegrationDtlsCidLengthTest.java index 37611c2bdb..fae638d62c 100644 --- a/application/src/test/java/org/thingsboard/server/transport/lwm2m/security/cid/serverDtlsCidLength_null/PskLwm2mIntegrationDtlsCidLengthTest.java +++ b/application/src/test/java/org/thingsboard/server/transport/lwm2m/security/cid/serverDtlsCidLength_null/PskLwm2mIntegrationDtlsCidLengthTest.java @@ -26,7 +26,7 @@ public class PskLwm2mIntegrationDtlsCidLengthTest extends AbstractSecurityLwM2MI @Before public void createProfileRpc() { - transportConfiguration = getTransportConfiguration(OBSERVE_ATTRIBUTES_WITHOUT_PARAMS, getBootstrapServerCredentialsSecure(PSK, NONE)); + transportConfiguration = getTransportConfiguration(OBSERVE_ATTRIBUTES_WITHOUT_PARAMS, getBootstrapSectionsServerCredentialsSecure(PSK, NONE)); awaitAlias = "await on client state (Psk_Lwm2m) serverDtlsCidLength = Null"; } diff --git a/application/src/test/java/org/thingsboard/server/transport/lwm2m/security/diffPort/LwM2MIntegrationDiffPortTest.java b/application/src/test/java/org/thingsboard/server/transport/lwm2m/security/diffPort/LwM2MIntegrationDiffPortTest.java index 8301905b85..e667484f21 100644 --- a/application/src/test/java/org/thingsboard/server/transport/lwm2m/security/diffPort/LwM2MIntegrationDiffPortTest.java +++ b/application/src/test/java/org/thingsboard/server/transport/lwm2m/security/diffPort/LwM2MIntegrationDiffPortTest.java @@ -27,7 +27,7 @@ public class LwM2MIntegrationDiffPortTest extends AbstractLwM2MIntegrationDiffPo @Test public void testWithNoSecConnectLwm2mSuccess_AfterRegistration_UpdateRegistrationFromDifferentPort_Ok() throws Exception { String awaitAlias = "await on client state (NoSec different port)"; - Lwm2mDeviceProfileTransportConfiguration transportConfiguration = getTransportConfiguration(OBSERVE_ATTRIBUTES_WITHOUT_PARAMS, getBootstrapServerCredentialsSecure(NO_SEC, NONE)); + Lwm2mDeviceProfileTransportConfiguration transportConfiguration = getTransportConfiguration(OBSERVE_ATTRIBUTES_WITHOUT_PARAMS, getBootstrapSectionsServerCredentialsSecure(NO_SEC, NONE)); initDeviceCredentialsNoSek(); basicTestConnectionDifferentPort( transportConfiguration, @@ -36,7 +36,7 @@ public class LwM2MIntegrationDiffPortTest extends AbstractLwM2MIntegrationDiffPo @Test public void testWithPskConnectLwm2mSuccess_AfterRegistration_UpdateRegistrationFromDifferentPort_Ok() throws Exception { String awaitAlias = "await on client state (Psk different port)"; - Lwm2mDeviceProfileTransportConfiguration transportConfiguration = getTransportConfiguration(OBSERVE_ATTRIBUTES_WITHOUT_PARAMS, getBootstrapServerCredentialsSecure(PSK, NONE)); + Lwm2mDeviceProfileTransportConfiguration transportConfiguration = getTransportConfiguration(OBSERVE_ATTRIBUTES_WITHOUT_PARAMS, getBootstrapSectionsServerCredentialsSecure(PSK, NONE)); initDeviceCredentialsPsk(); basicTestConnectionDifferentPort( transportConfiguration, diff --git a/application/src/test/java/org/thingsboard/server/transport/lwm2m/security/sql/PskLwm2mIntegrationTest.java b/application/src/test/java/org/thingsboard/server/transport/lwm2m/security/sql/PskLwm2mIntegrationTest.java index a80e9c4643..f01ea6d6ea 100644 --- a/application/src/test/java/org/thingsboard/server/transport/lwm2m/security/sql/PskLwm2mIntegrationTest.java +++ b/application/src/test/java/org/thingsboard/server/transport/lwm2m/security/sql/PskLwm2mIntegrationTest.java @@ -56,7 +56,7 @@ public class PskLwm2mIntegrationTest extends AbstractSecurityLwM2MIntegrationTes shortServerId, identity.getBytes(StandardCharsets.UTF_8), Hex.decodeHex(keyPsk.toCharArray())); - Lwm2mDeviceProfileTransportConfiguration transportConfiguration = getTransportConfiguration(OBSERVE_ATTRIBUTES_WITHOUT_PARAMS, getBootstrapServerCredentialsSecure(PSK, NONE)); + Lwm2mDeviceProfileTransportConfiguration transportConfiguration = getTransportConfiguration(OBSERVE_ATTRIBUTES_WITHOUT_PARAMS, getBootstrapSectionsServerCredentialsSecure(PSK, NONE)); LwM2MDeviceCredentials deviceCredentials = getDeviceCredentialsSecure(clientCredentials, null, null, PSK, false); this.basicTestConnection(security, null, deviceCredentials, @@ -83,7 +83,7 @@ public class PskLwm2mIntegrationTest extends AbstractSecurityLwM2MIntegrationTes shortServerId, identity.getBytes(StandardCharsets.UTF_8), Hex.decodeHex(keyPsk.toCharArray())); - Lwm2mDeviceProfileTransportConfiguration transportConfiguration = getTransportConfiguration(TELEMETRY_WITH_ONE_OBSERVE, getBootstrapServerCredentialsSecure(PSK, NONE)); + Lwm2mDeviceProfileTransportConfiguration transportConfiguration = getTransportConfiguration(TELEMETRY_WITH_ONE_OBSERVE, getBootstrapSectionsServerCredentialsSecure(PSK, NONE)); LwM2MDeviceCredentials deviceCredentials = getDeviceCredentialsSecure(clientCredentials, null, null, PSK, false); String awaitAlias = "await on client state (Psk_Lwm2m)"; Device lwm2mDevice = this.basicTestConnection(security, null, @@ -98,7 +98,7 @@ public class PskLwm2mIntegrationTest extends AbstractSecurityLwM2MIntegrationTes awaitObserveReadAll(1, lwm2mDevice.getId().getId().toString()); DeviceProfile foundDeviceProfile = doGet("/api/deviceProfile/" + lwm2mDevice.getDeviceProfileId().getId().toString(), DeviceProfile.class); - transportConfiguration = getTransportConfiguration(TELEMETRY_WITH_MANY_OBSERVE, getBootstrapServerCredentialsSecure(PSK, NONE)); + transportConfiguration = getTransportConfiguration(TELEMETRY_WITH_MANY_OBSERVE, getBootstrapSectionsServerCredentialsSecure(PSK, NONE)); foundDeviceProfile.getProfileData().setTransportConfiguration(transportConfiguration); DeviceProfile lwm2mDeviceProfileManyParams = doPost("/api/deviceProfile", foundDeviceProfile, DeviceProfile.class); Assert.assertNotNull(lwm2mDeviceProfileManyParams); @@ -120,7 +120,7 @@ public class PskLwm2mIntegrationTest extends AbstractSecurityLwM2MIntegrationTes shortServerId, identity.getBytes(StandardCharsets.UTF_8), Hex.decodeHex(keyPsk.toCharArray())); - Lwm2mDeviceProfileTransportConfiguration transportConfiguration = getTransportConfiguration(TELEMETRY_WITH_ONE_OBSERVE, getBootstrapServerCredentialsSecure(PSK, NONE)); + Lwm2mDeviceProfileTransportConfiguration transportConfiguration = getTransportConfiguration(TELEMETRY_WITH_ONE_OBSERVE, getBootstrapSectionsServerCredentialsSecure(PSK, NONE)); LwM2MDeviceCredentials deviceCredentials = getDeviceCredentialsSecure(clientCredentials, null, null, PSK, false); String awaitAlias = "await on client state (Psk_Lwm2m)"; Device lwm2mDevice = this.basicTestConnection(security, null, @@ -137,7 +137,7 @@ public class PskLwm2mIntegrationTest extends AbstractSecurityLwM2MIntegrationTes lwM2MTestClient.stop(true); DeviceProfile foundDeviceProfile = doGet("/api/deviceProfile/" + lwm2mDevice.getDeviceProfileId().getId().toString(), DeviceProfile.class); - transportConfiguration = getTransportConfiguration(TELEMETRY_WITH_MANY_OBSERVE, getBootstrapServerCredentialsSecure(PSK, NONE)); + transportConfiguration = getTransportConfiguration(TELEMETRY_WITH_MANY_OBSERVE, getBootstrapSectionsServerCredentialsSecure(PSK, NONE)); foundDeviceProfile.getProfileData().setTransportConfiguration(transportConfiguration); DeviceProfile lwm2mDeviceProfileManyParams = doPost("/api/deviceProfile", foundDeviceProfile, DeviceProfile.class); Assert.assertNotNull(lwm2mDeviceProfileManyParams); @@ -156,7 +156,7 @@ public class PskLwm2mIntegrationTest extends AbstractSecurityLwM2MIntegrationTes clientCredentials.setEndpoint(clientEndpoint); clientCredentials.setIdentity(identity); clientCredentials.setKey(keyPsk); - Lwm2mDeviceProfileTransportConfiguration transportConfiguration = getTransportConfiguration(OBSERVE_ATTRIBUTES_WITHOUT_PARAMS, getBootstrapServerCredentialsSecure(PSK, NONE)); + Lwm2mDeviceProfileTransportConfiguration transportConfiguration = getTransportConfiguration(OBSERVE_ATTRIBUTES_WITHOUT_PARAMS, getBootstrapSectionsServerCredentialsSecure(PSK, NONE)); DeviceProfile deviceProfile = createLwm2mDeviceProfile("profileFor" + clientEndpoint, transportConfiguration); // Wait for the profile to become available. This synchronizes asynchronous processes and prevents TenantNotFoundException during tearDown. @@ -192,7 +192,7 @@ public class PskLwm2mIntegrationTest extends AbstractSecurityLwM2MIntegrationTes Security securityPskBs = pskBootstrap(SECURE_URI_BS, identity.getBytes(StandardCharsets.UTF_8), Hex.decodeHex(keyPsk.toCharArray())); - Lwm2mDeviceProfileTransportConfiguration transportConfiguration = getTransportConfiguration(OBSERVE_ATTRIBUTES_WITHOUT_PARAMS, getBootstrapServerCredentialsSecure(PSK, BOTH)); + Lwm2mDeviceProfileTransportConfiguration transportConfiguration = getTransportConfiguration(OBSERVE_ATTRIBUTES_WITHOUT_PARAMS, getBootstrapSectionsServerCredentialsSecure(PSK, BOTH)); LwM2MDeviceCredentials deviceCredentials = getDeviceCredentialsSecure(clientCredentials, null, null, PSK, false); this.basicTestConnection(null, securityPskBs, deviceCredentials, diff --git a/application/src/test/java/org/thingsboard/server/transport/lwm2m/security/sql/RpkLwM2MIntegrationTest.java b/application/src/test/java/org/thingsboard/server/transport/lwm2m/security/sql/RpkLwM2MIntegrationTest.java index ce942090e9..ccf02d94f9 100644 --- a/application/src/test/java/org/thingsboard/server/transport/lwm2m/security/sql/RpkLwM2MIntegrationTest.java +++ b/application/src/test/java/org/thingsboard/server/transport/lwm2m/security/sql/RpkLwM2MIntegrationTest.java @@ -56,7 +56,7 @@ public class RpkLwM2MIntegrationTest extends AbstractSecurityLwM2MIntegrationTes certificate.getPublicKey().getEncoded(), privateKey.getEncoded(), serverX509Cert.getPublicKey().getEncoded()); - Lwm2mDeviceProfileTransportConfiguration transportConfiguration = getTransportConfiguration(OBSERVE_ATTRIBUTES_WITHOUT_PARAMS, getBootstrapServerCredentialsSecure(RPK, NONE)); + Lwm2mDeviceProfileTransportConfiguration transportConfiguration = getTransportConfiguration(OBSERVE_ATTRIBUTES_WITHOUT_PARAMS, getBootstrapSectionsServerCredentialsSecure(RPK, NONE)); LwM2MDeviceCredentials deviceCredentials = getDeviceCredentialsSecure(clientCredentials, privateKey, certificate, RPK, false); this.basicTestConnection(security, null, deviceCredentials, @@ -77,7 +77,7 @@ public class RpkLwM2MIntegrationTest extends AbstractSecurityLwM2MIntegrationTes RPKClientCredential clientCredentials = new RPKClientCredential(); clientCredentials.setEndpoint(clientEndpoint); clientCredentials.setKey(Hex.encodeHexString(certificate.getPublicKey().getEncoded())); - Lwm2mDeviceProfileTransportConfiguration transportConfiguration = getTransportConfiguration(OBSERVE_ATTRIBUTES_WITHOUT_PARAMS, getBootstrapServerCredentialsSecure(PSK, NONE)); + Lwm2mDeviceProfileTransportConfiguration transportConfiguration = getTransportConfiguration(OBSERVE_ATTRIBUTES_WITHOUT_PARAMS, getBootstrapSectionsServerCredentialsSecure(PSK, NONE)); DeviceProfile deviceProfile = createLwm2mDeviceProfile("profileFor" + clientEndpoint, transportConfiguration); LwM2MDeviceCredentials deviceCredentials = getDeviceCredentialsSecure(clientCredentials, privateKey, certificate, RPK, false); @@ -95,7 +95,7 @@ public class RpkLwM2MIntegrationTest extends AbstractSecurityLwM2MIntegrationTes RPKClientCredential clientCredentials = new RPKClientCredential(); clientCredentials.setEndpoint(clientEndpoint); clientCredentials.setKey(Base64.encodeBase64String(certificate.getPublicKey().getEncoded())); - Lwm2mDeviceProfileTransportConfiguration transportConfiguration = getTransportConfiguration(OBSERVE_ATTRIBUTES_WITHOUT_PARAMS, getBootstrapServerCredentialsSecure(PSK, NONE)); + Lwm2mDeviceProfileTransportConfiguration transportConfiguration = getTransportConfiguration(OBSERVE_ATTRIBUTES_WITHOUT_PARAMS, getBootstrapSectionsServerCredentialsSecure(PSK, NONE)); DeviceProfile deviceProfile = createLwm2mDeviceProfile("profileFor" + clientEndpoint, transportConfiguration); LwM2MDeviceCredentials deviceCredentials = getDeviceCredentialsSecure(clientCredentials, privateKey, certificate, RPK, true); MvcResult result = createDeviceWithMvcResult(deviceCredentials, clientEndpoint, deviceProfile.getId()); @@ -117,7 +117,7 @@ public class RpkLwM2MIntegrationTest extends AbstractSecurityLwM2MIntegrationTes certificate.getPublicKey().getEncoded(), privateKey.getEncoded(), serverX509CertBs.getPublicKey().getEncoded()); - Lwm2mDeviceProfileTransportConfiguration transportConfiguration = getTransportConfiguration(OBSERVE_ATTRIBUTES_WITHOUT_PARAMS, getBootstrapServerCredentialsSecure(RPK, BOTH)); + Lwm2mDeviceProfileTransportConfiguration transportConfiguration = getTransportConfiguration(OBSERVE_ATTRIBUTES_WITHOUT_PARAMS, getBootstrapSectionsServerCredentialsSecure(RPK, BOTH)); LwM2MDeviceCredentials deviceCredentials = getDeviceCredentialsSecure(clientCredentials, clientPrivateKeyFromCertTrust, certificate, RPK, false); this.basicTestConnection(null, securityRpkBs, deviceCredentials, diff --git a/application/src/test/java/org/thingsboard/server/transport/lwm2m/security/sql/X509_NoTrustLwM2MIntegrationTest.java b/application/src/test/java/org/thingsboard/server/transport/lwm2m/security/sql/X509_NoTrustLwM2MIntegrationTest.java index 5b385dfea0..c461460c57 100644 --- a/application/src/test/java/org/thingsboard/server/transport/lwm2m/security/sql/X509_NoTrustLwM2MIntegrationTest.java +++ b/application/src/test/java/org/thingsboard/server/transport/lwm2m/security/sql/X509_NoTrustLwM2MIntegrationTest.java @@ -56,7 +56,7 @@ public class X509_NoTrustLwM2MIntegrationTest extends AbstractSecurityLwM2MInteg certificate.getEncoded(), privateKey.getEncoded(), serverX509Cert.getEncoded()); - Lwm2mDeviceProfileTransportConfiguration transportConfiguration = getTransportConfiguration(OBSERVE_ATTRIBUTES_WITHOUT_PARAMS, getBootstrapServerCredentialsSecure(X509, NONE)); + Lwm2mDeviceProfileTransportConfiguration transportConfiguration = getTransportConfiguration(OBSERVE_ATTRIBUTES_WITHOUT_PARAMS, getBootstrapSectionsServerCredentialsSecure(X509, NONE)); LwM2MDeviceCredentials deviceCredentials = getDeviceCredentialsSecure(clientCredentials, privateKey, certificate, X509, false); this.basicTestConnection(securityX509, null, deviceCredentials, @@ -78,7 +78,7 @@ public class X509_NoTrustLwM2MIntegrationTest extends AbstractSecurityLwM2MInteg clientCredentials.setEndpoint(clientEndpoint); clientCredentials.setCert(Hex.encodeHexString(certificate.getEncoded())); LwM2MDeviceCredentials deviceCredentials = getDeviceCredentialsSecure(clientCredentials, privateKey, certificate, X509, false); - Lwm2mDeviceProfileTransportConfiguration transportConfiguration = getTransportConfiguration(OBSERVE_ATTRIBUTES_WITHOUT_PARAMS, getBootstrapServerCredentialsSecure(PSK, NONE)); + Lwm2mDeviceProfileTransportConfiguration transportConfiguration = getTransportConfiguration(OBSERVE_ATTRIBUTES_WITHOUT_PARAMS, getBootstrapSectionsServerCredentialsSecure(PSK, NONE)); DeviceProfile deviceProfile = createLwm2mDeviceProfile("profileFor" + clientEndpoint, transportConfiguration); MvcResult result = createDeviceWithMvcResult(deviceCredentials, clientEndpoint, deviceProfile.getId()); assertEquals(HttpServletResponse.SC_BAD_REQUEST, result.getResponse().getStatus()); @@ -95,7 +95,7 @@ public class X509_NoTrustLwM2MIntegrationTest extends AbstractSecurityLwM2MInteg clientCredentials.setEndpoint(clientEndpoint); clientCredentials.setCert(Base64.getEncoder().encodeToString(certificate.getEncoded())); LwM2MDeviceCredentials deviceCredentials = getDeviceCredentialsSecure(clientCredentials, privateKey, certificate, X509, true); - Lwm2mDeviceProfileTransportConfiguration transportConfiguration = getTransportConfiguration(OBSERVE_ATTRIBUTES_WITHOUT_PARAMS, getBootstrapServerCredentialsSecure(PSK, NONE)); + Lwm2mDeviceProfileTransportConfiguration transportConfiguration = getTransportConfiguration(OBSERVE_ATTRIBUTES_WITHOUT_PARAMS, getBootstrapSectionsServerCredentialsSecure(PSK, NONE)); DeviceProfile deviceProfile = createLwm2mDeviceProfile("profileFor" + clientEndpoint, transportConfiguration); MvcResult result = createDeviceWithMvcResult(deviceCredentials, clientEndpoint, deviceProfile.getId()); assertEquals(HttpServletResponse.SC_BAD_REQUEST, result.getResponse().getStatus()); @@ -116,7 +116,7 @@ public class X509_NoTrustLwM2MIntegrationTest extends AbstractSecurityLwM2MInteg certificate.getEncoded(), privateKey.getEncoded(), serverX509CertBs.getEncoded()); - Lwm2mDeviceProfileTransportConfiguration transportConfiguration = getTransportConfiguration(OBSERVE_ATTRIBUTES_WITHOUT_PARAMS, getBootstrapServerCredentialsSecure(X509, BOTH)); + Lwm2mDeviceProfileTransportConfiguration transportConfiguration = getTransportConfiguration(OBSERVE_ATTRIBUTES_WITHOUT_PARAMS, getBootstrapSectionsServerCredentialsSecure(X509, BOTH)); LwM2MDeviceCredentials deviceCredentials = getDeviceCredentialsSecure(clientCredentials, privateKey, certificate, X509, false); this.basicTestConnection(security, null, deviceCredentials, diff --git a/application/src/test/java/org/thingsboard/server/transport/lwm2m/security/sql/X509_TrustLwM2MIntegrationTest.java b/application/src/test/java/org/thingsboard/server/transport/lwm2m/security/sql/X509_TrustLwM2MIntegrationTest.java index 44eeb96d5f..a7019ca9ea 100644 --- a/application/src/test/java/org/thingsboard/server/transport/lwm2m/security/sql/X509_TrustLwM2MIntegrationTest.java +++ b/application/src/test/java/org/thingsboard/server/transport/lwm2m/security/sql/X509_TrustLwM2MIntegrationTest.java @@ -48,7 +48,7 @@ public class X509_TrustLwM2MIntegrationTest extends AbstractSecurityLwM2MIntegra certificate.getEncoded(), privateKey.getEncoded(), serverX509Cert.getEncoded()); - Lwm2mDeviceProfileTransportConfiguration transportConfiguration = getTransportConfiguration(OBSERVE_ATTRIBUTES_WITHOUT_PARAMS, getBootstrapServerCredentialsSecure(X509, NONE)); + Lwm2mDeviceProfileTransportConfiguration transportConfiguration = getTransportConfiguration(OBSERVE_ATTRIBUTES_WITHOUT_PARAMS, getBootstrapSectionsServerCredentialsSecure(X509, NONE)); LwM2MDeviceCredentials deviceCredentials = getDeviceCredentialsSecure(clientCredentials, privateKey, certificate, X509, false); this.basicTestConnection(security, null, deviceCredentials, @@ -74,7 +74,7 @@ public class X509_TrustLwM2MIntegrationTest extends AbstractSecurityLwM2MIntegra certificate.getEncoded(), privateKey.getEncoded(), serverX509CertBs.getEncoded()); - Lwm2mDeviceProfileTransportConfiguration transportConfiguration = getTransportConfiguration(OBSERVE_ATTRIBUTES_WITHOUT_PARAMS, getBootstrapServerCredentialsSecure(X509, BOTH)); + Lwm2mDeviceProfileTransportConfiguration transportConfiguration = getTransportConfiguration(OBSERVE_ATTRIBUTES_WITHOUT_PARAMS, getBootstrapSectionsServerCredentialsSecure(X509, BOTH)); LwM2MDeviceCredentials deviceCredentials = getDeviceCredentialsSecure(clientCredentials, privateKey, certificate, X509, false); this.basicTestConnection(security,null, deviceCredentials, diff --git a/common/data/src/main/java/org/thingsboard/server/common/data/device/profile/lwm2m/bootstrap/LwM2MServerSecurityConfig.java b/common/data/src/main/java/org/thingsboard/server/common/data/device/profile/lwm2m/bootstrap/LwM2MServerSecurityConfig.java index 8d826b6e5c..d88705fa8c 100644 --- a/common/data/src/main/java/org/thingsboard/server/common/data/device/profile/lwm2m/bootstrap/LwM2MServerSecurityConfig.java +++ b/common/data/src/main/java/org/thingsboard/server/common/data/device/profile/lwm2m/bootstrap/LwM2MServerSecurityConfig.java @@ -25,9 +25,9 @@ import java.io.Serializable; public class LwM2MServerSecurityConfig implements Serializable { @Schema(description = "Server short Id. Used as link to associate server Object Instance. This identifier uniquely identifies each LwM2M Server configured for the LwM2M Client. " + - "This Resource MUST be set when the Bootstrap-Server Resource has a value of 'false'. " + - "The values ID:0 and ID:65535 values MUST NOT be used for identifying the LwM2M Server.", example = "123", accessMode = Schema.AccessMode.READ_ONLY) - protected Integer shortServerId = 123; + "This Resource MUST be set when the Bootstrap-Server Resource has a value of 'false' and MUST be null when Bootstrap-Server is 'true'. " + + "The values ID:0 and ID:65535 values MUST NOT be used for identifying the LwM2M Server.", example = "1", accessMode = Schema.AccessMode.READ_ONLY) + protected Integer shortServerId; /** Security -> ObjectId = 0 'LWM2M Security' */ @Schema(description = "Is Bootstrap Server or Lwm2m Server. " + "The LwM2M Client MAY be configured to use one or more LwM2M Server Account(s). " + diff --git a/common/transport/lwm2m/src/main/java/org/thingsboard/server/transport/lwm2m/bootstrap/secure/LwM2MBootstrapConfig.java b/common/transport/lwm2m/src/main/java/org/thingsboard/server/transport/lwm2m/bootstrap/secure/LwM2MBootstrapConfig.java index 45b3148219..1308e23a13 100644 --- a/common/transport/lwm2m/src/main/java/org/thingsboard/server/transport/lwm2m/bootstrap/secure/LwM2MBootstrapConfig.java +++ b/common/transport/lwm2m/src/main/java/org/thingsboard/server/transport/lwm2m/bootstrap/secure/LwM2MBootstrapConfig.java @@ -127,9 +127,6 @@ public class LwM2MBootstrapConfig implements Serializable { private BootstrapConfig.ServerConfig setServerConfig (AbstractLwM2MBootstrapServerCredential serverCredential) { BootstrapConfig.ServerConfig serverConfig = new BootstrapConfig.ServerConfig(); - if (serverCredential.getShortServerId() != null) { - serverConfig.shortId = serverCredential.getShortServerId(); - } serverConfig.lifetime = serverCredential.getLifetime(); serverConfig.defaultMinPeriod = serverCredential.getDefaultMinPeriod(); serverConfig.notifIfDisabled = serverCredential.isNotifIfDisabled(); diff --git a/dao/src/main/java/org/thingsboard/server/dao/service/validator/DeviceProfileDataValidator.java b/dao/src/main/java/org/thingsboard/server/dao/service/validator/DeviceProfileDataValidator.java index 74fa56dc87..b7aff6d5db 100644 --- a/dao/src/main/java/org/thingsboard/server/dao/service/validator/DeviceProfileDataValidator.java +++ b/dao/src/main/java/org/thingsboard/server/dao/service/validator/DeviceProfileDataValidator.java @@ -346,9 +346,27 @@ public class DeviceProfileDataValidator extends AbstractHasOtaPackageValidator lwM2MBootstrapServersConfigurations, boolean isBootstrapServerUpdateEnable) { Set uris = new HashSet<>(); Set shortServerIds = new HashSet<>(); + boolean hasBootstrapServer = false; + for (LwM2MBootstrapServerCredential bootstrapServerCredential : lwM2MBootstrapServersConfigurations) { AbstractLwM2MBootstrapServerCredential serverConfig = (AbstractLwM2MBootstrapServerCredential) bootstrapServerCredential; if (!isBootstrapServerUpdateEnable && serverConfig.isBootstrapServerIs()) { @@ -356,14 +374,29 @@ public class DeviceProfileDataValidator extends AbstractHasOtaPackageValidator Date: Thu, 10 Sep 2026 12:07:21 +0300 Subject: [PATCH 024/159] Keep the edge event check and its new events flag with the session that owns the edge --- .../service/edge/rpc/EdgeGrpcService.java | 126 +++++++++++------- 1 file changed, 77 insertions(+), 49 deletions(-) diff --git a/application/src/main/java/org/thingsboard/server/service/edge/rpc/EdgeGrpcService.java b/application/src/main/java/org/thingsboard/server/service/edge/rpc/EdgeGrpcService.java index 4de478fe34..5fdd67e0b3 100644 --- a/application/src/main/java/org/thingsboard/server/service/edge/rpc/EdgeGrpcService.java +++ b/application/src/main/java/org/thingsboard/server/service/edge/rpc/EdgeGrpcService.java @@ -311,7 +311,7 @@ public class EdgeGrpcService extends EdgeRpcServiceGrpc.EdgeRpcServiceImplBase i @Override public void deleteEdge(TenantId tenantId, EdgeId edgeId) { - EdgeGrpcSession toRemove = detachSession(edgeId, EdgeGrpcSession::isConnected); + EdgeGrpcSession toRemove = detachSession(edgeId); if (toRemove != null) { log.info("[{}] Closing and removing session for edge [{}]", tenantId, edgeId); sessionsById.remove(toRemove.getSessionId()); @@ -322,7 +322,6 @@ public class EdgeGrpcService extends EdgeRpcServiceGrpc.EdgeRpcServiceImplBase i } finally { newEventLock.unlock(); } - // destroy is slow (stops the kafka edge event consumer), keep it off the atomic path destroySession(toRemove); toRemove.cleanUp(); } @@ -386,7 +385,6 @@ public class EdgeGrpcService extends EdgeRpcServiceGrpc.EdgeRpcServiceImplBase i edgeEventsMigrationProcessed.putIfAbsent(edgeId, Boolean.FALSE); scheduleEdgeEventsCheck(edgeGrpcSession); if (replaced != null) { - // destroy is slow (stops the kafka edge event consumer), keep it off the atomic path destroySession(replaced); } } @@ -450,47 +448,6 @@ public class EdgeGrpcService extends EdgeRpcServiceGrpc.EdgeRpcServiceImplBase i EdgeId edgeId = session.getEdge().getId(); TenantId tenantId = session.getEdge().getTenantId(); - Runnable edgeEventCheck = () -> { - try { - final Lock newEventLock = sessionNewEventsLocks.computeIfAbsent(edgeId, id -> new ReentrantLock()); - newEventLock.lock(); - try { - if (Boolean.TRUE.equals(sessionNewEvents.get(edgeId))) { - log.trace("[{}][{}] set session new events flag to false", tenantId, edgeId.getId()); - sessionNewEvents.put(edgeId, false); - session.processHighPriorityEvents(); - processEdgeEventMigrationIfNeeded(session, edgeId); - if (Boolean.TRUE.equals(edgeEventsMigrationProcessed.get(edgeId))) { - Futures.addCallback(session.processEdgeEvents(), new FutureCallback<>() { - @Override - public void onSuccess(Boolean newEventsAdded) { - if (Boolean.TRUE.equals(newEventsAdded)) { - log.trace("[{}][{}] new events added. set session new events flag to true", tenantId, edgeId.getId()); - sessionNewEvents.put(edgeId, true); - } - scheduleEdgeEventsCheck(session); - } - - @Override - public void onFailure(Throwable t) { - log.warn("[{}] Failed to process edge events for edge [{}]!", tenantId, session.getEdge().getId().getId(), t); - scheduleEdgeEventsCheck(session); - } - }, ctx.getGrpcCallbackExecutorService()); - } else { - scheduleEdgeEventsCheck(session); - } - } else { - scheduleEdgeEventsCheck(session); - } - } finally { - newEventLock.unlock(); - } - } catch (Exception e) { - log.warn("[{}] Failed to process edge events for edge [{}]!", tenantId, session.getEdge().getId().getId(), e); - } - }; - // arm the next check only while this exact session is still the current one, atomically with // cancelling the previous one, so that a concurrent connect/disconnect can neither lose the // re-arm nor cancel a check that belongs to a session other than the one it is tearing down @@ -501,13 +458,66 @@ public class EdgeGrpcService extends EdgeRpcServiceGrpc.EdgeRpcServiceImplBase i return current; } cancelScheduleEdgeEventsCheck(edgeId); - sessionEdgeEventChecks.put(edgeId, edgeEventProcessingExecutorService.schedule(edgeEventCheck, + sessionEdgeEventChecks.put(edgeId, edgeEventProcessingExecutorService.schedule( + () -> processEvents(session, edgeId, tenantId), ctx.getEdgeEventStorageSettings().getNoRecordsSleepInterval(), TimeUnit.MILLISECONDS)); log.trace("[{}] Check edge event scheduled for edge [{}]", tenantId, edgeId.getId()); return current; }); } + private void processEvents(EdgeGrpcSession session, EdgeId edgeId, TenantId tenantId) { + try { + final Lock newEventLock = sessionNewEventsLocks.computeIfAbsent(edgeId, id -> new ReentrantLock()); + newEventLock.lock(); + try { + if (sessions.get(edgeId) != session) { + log.debug("[{}] Session is not current anymore, edge event check must not run for edge [{}]", + tenantId, edgeId.getId()); + return; + } + if (Boolean.TRUE.equals(sessionNewEvents.get(edgeId))) { + log.trace("[{}][{}] set session new events flag to false", tenantId, edgeId.getId()); + sessionNewEvents.put(edgeId, false); + session.processHighPriorityEvents(); + processEdgeEventMigrationIfNeeded(session, edgeId); + if (Boolean.TRUE.equals(edgeEventsMigrationProcessed.get(edgeId))) { + Futures.addCallback(session.processEdgeEvents(), new FutureCallback<>() { + @Override + public void onSuccess(Boolean newEventsAdded) { + if (Boolean.TRUE.equals(newEventsAdded)) { + log.trace("[{}][{}] new events added. set session new events flag to true", tenantId, edgeId.getId()); + final Lock newEventLock = sessionNewEventsLocks.computeIfAbsent(edgeId, id -> new ReentrantLock()); + newEventLock.lock(); + try { + sessionNewEvents.put(edgeId, true); + } finally { + newEventLock.unlock(); + } + } + scheduleEdgeEventsCheck(session); + } + + @Override + public void onFailure(Throwable t) { + log.warn("[{}] Failed to process edge events for edge [{}]!", tenantId, session.getEdge().getId().getId(), t); + scheduleEdgeEventsCheck(session); + } + }, ctx.getGrpcCallbackExecutorService()); + } else { + scheduleEdgeEventsCheck(session); + } + } else { + scheduleEdgeEventsCheck(session); + } + } finally { + newEventLock.unlock(); + } + } catch (Exception e) { + log.warn("[{}] Failed to process edge events for edge [{}]!", tenantId, session.getEdge().getId().getId(), e); + } + } + private void processEdgeEventMigrationIfNeeded(EdgeGrpcSession session, EdgeId edgeId) throws Exception { boolean isMigrationProcessed = edgeEventsMigrationProcessed.getOrDefault(edgeId, Boolean.FALSE); if (!isMigrationProcessed) { @@ -550,7 +560,6 @@ public class EdgeGrpcService extends EdgeRpcServiceGrpc.EdgeRpcServiceImplBase i save(tenantId, edgeId, ACTIVITY_STATE, false); save(tenantId, edgeId, LAST_DISCONNECT_TIME, lastDisconnectTs); pushRuleEngineMessage(tenantId, edge, lastDisconnectTs, TbMsgType.DISCONNECT_EVENT); - // destroy is slow (stops the kafka edge event consumer), keep it off the atomic path destroySession(toRemove); } else { log.info("[{}] edge session [{}] is not current anymore. Attempting to destroy it by sessionId.", edgeId, sessionId); @@ -572,6 +581,11 @@ public class EdgeGrpcService extends EdgeRpcServiceGrpc.EdgeRpcServiceImplBase i * Registers the session as the current one for the edge and cancels the edge event check armed by * the session it replaces, as a single atomic step. Returns the replaced session, or null if there * was none - the caller is responsible for destroying it outside of this critical section. + *

+ * Only cheap non-blocking work may run inside the remapping function: it holds the bin lock of + * {@link #sessions} for this edge, so everything slow or lock-taking - {@link #destroySession}, + * {@code EdgeGrpcSession.cleanUp()}, {@code save(...)}, {@code pushRuleEngineMessage(...)} or + * acquiring the per-edge new events lock - has to be done by the caller once compute has returned. */ private EdgeGrpcSession attachSession(EdgeId edgeId, EdgeGrpcSession session) { AtomicReference replaced = new AtomicReference<>(); @@ -583,12 +597,19 @@ public class EdgeGrpcService extends EdgeRpcServiceGrpc.EdgeRpcServiceImplBase i return replaced.get(); } + private EdgeGrpcSession detachSession(EdgeId edgeId) { + return detachSession(edgeId, s -> true); + } + /** * Detaches the edge's registered session and cancels its edge event check as a single atomic step, * but only if that session satisfies shouldDetach. Returns the detached session, or null if the * predicate rejected it - most importantly when another session has taken the edge over in the * meantime, in which case nothing is touched and a reconnect racing with a teardown cannot lose * the check it has just armed. The caller destroys the returned session outside the atomic step. + *

+ * The remapping function is subject to the same "cheap non-blocking work only" rule as + * {@link #attachSession(EdgeId, EdgeGrpcSession)}. */ private EdgeGrpcSession detachSession(EdgeId edgeId, Predicate shouldDetach) { AtomicReference detached = new AtomicReference<>(); @@ -603,6 +624,12 @@ public class EdgeGrpcService extends EdgeRpcServiceGrpc.EdgeRpcServiceImplBase i return detached.get(); } + /** + * Stops the session's edge event consumer and shuts down its executor, collecting the session for a + * later retry if that fails. This can block for seconds - {@code KafkaEdgeGrpcSession.destroy()} + * gives the consumer executor up to 5s to terminate - so it must never be called from inside a + * {@link #sessions} remapping function. + */ private void destroySession(EdgeGrpcSession session) { try (session) { if (!session.destroy()) { @@ -722,9 +749,10 @@ public class EdgeGrpcService extends EdgeRpcServiceGrpc.EdgeRpcServiceImplBase i private void cleanupZombieSessions() { try { - // compare-and-remove: the edge may have reconnected since the zombie scan, and that newer - // session must not be evicted by the cleanup of the one it replaced - tryToDestroyZombieSessions(getZombieSessions(sessions.values()), s -> sessions.remove(s.getEdge().getId(), s)); + // detach by identity: the edge may have reconnected since the zombie scan, and that newer + // session must neither be evicted nor have its edge event check cancelled by the cleanup of + // the one it replaced + tryToDestroyZombieSessions(getZombieSessions(sessions.values()), s -> detachSession(s.getEdge().getId(), current -> current == s)); tryToDestroyZombieSessions(getZombieSessions(sessionsById.values()), s -> sessionsById.remove(s.getSessionId())); zombieSessions.removeIf(zombie -> { From a0c6bd4416be26f12ff9ef43488c2bf996c047e6 Mon Sep 17 00:00:00 2001 From: Nikita Mazurenko Date: Thu, 10 Sep 2026 12:07:22 +0300 Subject: [PATCH 025/159] Add EdgeGrpcService tests for the edge session reconnect race --- .../rpc/EdgeGrpcServiceReconnectTest.java | 338 ++++++++++++++++++ 1 file changed, 338 insertions(+) create mode 100644 application/src/test/java/org/thingsboard/server/service/edge/rpc/EdgeGrpcServiceReconnectTest.java diff --git a/application/src/test/java/org/thingsboard/server/service/edge/rpc/EdgeGrpcServiceReconnectTest.java b/application/src/test/java/org/thingsboard/server/service/edge/rpc/EdgeGrpcServiceReconnectTest.java new file mode 100644 index 0000000000..8b90004e25 --- /dev/null +++ b/application/src/test/java/org/thingsboard/server/service/edge/rpc/EdgeGrpcServiceReconnectTest.java @@ -0,0 +1,338 @@ +/** + * Copyright © 2016-2026 The Thingsboard Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.thingsboard.server.service.edge.rpc; + +import com.google.common.util.concurrent.Futures; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.springframework.test.util.ReflectionTestUtils; +import org.thingsboard.server.cache.SimpleTbCacheValueWrapper; +import org.thingsboard.server.cache.TbTransactionalCache; +import org.thingsboard.server.cluster.TbClusterService; +import org.thingsboard.server.common.data.edge.Edge; +import org.thingsboard.server.common.data.id.EdgeId; +import org.thingsboard.server.common.data.id.TenantId; +import org.thingsboard.server.common.msg.notification.NotificationRuleProcessor; +import org.thingsboard.server.gen.transport.TransportProtos.ToEdgeEventNotificationMsg; +import org.thingsboard.server.queue.TbQueueConsumer; +import org.thingsboard.server.queue.common.TbProtoQueueMsg; +import org.thingsboard.server.queue.common.consumer.QueueConsumerManager; +import org.thingsboard.server.queue.discovery.TbServiceInfoProvider; +import org.thingsboard.server.service.edge.EdgeContextComponent; +import org.thingsboard.server.service.executors.GrpcCallbackExecutorService; +import org.thingsboard.server.service.telemetry.TelemetrySubscriptionService; + +import java.util.Map; +import java.util.UUID; +import java.util.concurrent.ConcurrentMap; +import java.util.concurrent.Executors; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.ScheduledFuture; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.doAnswer; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +/** + * Covers the reconnect race between a session that is being torn down and the session that has already + * taken the edge over: the teardown must not detach, cancel the edge event check of, or consume the new + * events flag of the session that replaced it. + */ +class EdgeGrpcServiceReconnectTest { + + // long enough that an armed check never actually fires during a test + private static final long NO_RECORDS_SLEEP_INTERVAL_MS = 60_000L; + private static final String THIS_NODE = "test-core"; + + private EdgeGrpcService service; + private ScheduledExecutorService edgeEventProcessingExecutorService; + private TbTransactionalCache edgeIdServiceIdCache; + + private TenantId tenantId; + private EdgeId edgeId; + private Edge edge; + + @BeforeEach + @SuppressWarnings("unchecked") + void setUp() { + tenantId = TenantId.fromUUID(UUID.randomUUID()); + edgeId = new EdgeId(UUID.randomUUID()); + edge = new Edge(edgeId); + edge.setTenantId(tenantId); + edge.setName("test-edge"); + + EdgeEventStorageSettings storageSettings = new EdgeEventStorageSettings(); + ReflectionTestUtils.setField(storageSettings, "noRecordsSleepInterval", NO_RECORDS_SLEEP_INTERVAL_MS); + + GrpcCallbackExecutorService grpcCallbackExecutorService = mock(GrpcCallbackExecutorService.class); + // run future callbacks inline so the re-arm is observable without waiting on a pool + doAnswer(invocation -> { + invocation.getArgument(0, Runnable.class).run(); + return null; + }).when(grpcCallbackExecutorService).execute(any()); + + EdgeContextComponent ctx = mock(EdgeContextComponent.class); + when(ctx.getEdgeEventStorageSettings()).thenReturn(storageSettings); + when(ctx.getGrpcCallbackExecutorService()).thenReturn(grpcCallbackExecutorService); + when(ctx.getRuleProcessor()).thenReturn(mock(NotificationRuleProcessor.class)); + + TbServiceInfoProvider serviceInfoProvider = mock(TbServiceInfoProvider.class); + when(serviceInfoProvider.getServiceId()).thenReturn(THIS_NODE); + + edgeIdServiceIdCache = mock(TbTransactionalCache.class); + // this node is the recorded owner of the edge, which is what a live local session implies + when(edgeIdServiceIdCache.get(edgeId)).thenReturn(SimpleTbCacheValueWrapper.wrap(THIS_NODE)); + edgeEventProcessingExecutorService = Executors.newSingleThreadScheduledExecutor(); + + service = new EdgeGrpcService(); + ReflectionTestUtils.setField(service, "ctx", ctx); + ReflectionTestUtils.setField(service, "tsSubService", mock(TelemetrySubscriptionService.class)); + ReflectionTestUtils.setField(service, "clusterService", mock(TbClusterService.class)); + ReflectionTestUtils.setField(service, "serviceInfoProvider", serviceInfoProvider); + ReflectionTestUtils.setField(service, "edgeIdServiceIdCache", edgeIdServiceIdCache); + ReflectionTestUtils.setField(service, "edgeEventProcessingExecutorService", edgeEventProcessingExecutorService); + } + + @AfterEach + void tearDown() { + edgeEventProcessingExecutorService.shutdownNow(); + } + + @Test + void checkIsArmedForTheCurrentSession() { + EdgeGrpcSession session = newSession(); + sessions().put(edgeId, session); + + scheduleEdgeEventsCheck(session); + + ScheduledFuture armed = edgeEventChecks().get(edgeId); + assertThat((Object) armed).as("check armed for the session that owns the edge").isNotNull(); + assertThat(armed.isCancelled()).isFalse(); + } + + @Test + void checkIsNotArmedForASupersededSession() { + EdgeGrpcSession current = newSession(); + EdgeGrpcSession superseded = newSession(); + sessions().put(edgeId, current); + scheduleEdgeEventsCheck(current); + ScheduledFuture armedByCurrent = edgeEventChecks().get(edgeId); + + scheduleEdgeEventsCheck(superseded); + + assertThat((Object) edgeEventChecks().get(edgeId)) + .as("the superseded session must neither cancel nor replace the current session's check") + .isSameAs(armedByCurrent); + assertThat(armedByCurrent.isCancelled()).isFalse(); + } + + @Test + void disconnectOfTheCurrentSessionDetachesItAndCancelsItsCheck() { + EdgeGrpcSession session = newSession(); + onEdgeConnect(session); + ScheduledFuture armedCheck = edgeEventChecks().get(edgeId); + + onEdgeDisconnect(session); + + assertThat(sessions()).doesNotContainKey(edgeId); + assertThat(sessionsById()).doesNotContainKey(session.getSessionId()); + assertThat(armedCheck.isCancelled()).as("the detached session's check is cancelled").isTrue(); + verify(edgeIdServiceIdCache).evict(edgeId); + verify(session).destroy(); + } + + @Test + void disconnectOfASupersededSessionKeepsTheReconnectedSessionAndItsCheck() { + EdgeGrpcSession first = newSession(); + onEdgeConnect(first); + // the edge reconnects before the gRPC stream of the first session is closed + EdgeGrpcSession second = newSession(); + onEdgeConnect(second); + ScheduledFuture armedBySecond = edgeEventChecks().get(edgeId); + + onEdgeDisconnect(first); + + assertThat(sessions().get(edgeId)).as("the reconnected session stays registered").isSameAs(second); + assertThat(sessionsById()).containsKey(second.getSessionId()); + assertThat((Object) edgeEventChecks().get(edgeId)) + .as("the check armed by the reconnected session survives the teardown of the one it replaced") + .isSameAs(armedBySecond); + assertThat(armedBySecond.isCancelled()).isFalse(); + verify(edgeIdServiceIdCache, never()).evict(edgeId); + } + + @Test + void disconnectDoesNotClearTheNewEventsFlag() { + EdgeGrpcSession session = newSession(); + onEdgeConnect(session); + assertThat(newEvents()).containsEntry(edgeId, true); + + onEdgeDisconnect(session); + + assertThat(newEvents()) + .as("clearing the flag here would wipe the one a reconnecting session has just raised") + .containsEntry(edgeId, true); + } + + @Test + void checkOfTheCurrentSessionConsumesTheFlagAndReArms() throws Exception { + EdgeGrpcSession session = newSession(); + when(session.processEdgeEvents()).thenReturn(Futures.immediateFuture(false)); + sessions().put(edgeId, session); + newEvents().put(edgeId, true); + migrationProcessed().put(edgeId, Boolean.TRUE); + + processEvents(session); + + assertThat(newEvents()).containsEntry(edgeId, false); + verify(session).processHighPriorityEvents(); + verify(session).processEdgeEvents(); + assertThat((Object) edgeEventChecks().get(edgeId)).as("the check re-arms itself").isNotNull(); + } + + @Test + void checkOfASupersededSessionLeavesTheFlagForTheSessionThatOwnsTheEdge() throws Exception { + EdgeGrpcSession superseded = newSession(); + EdgeGrpcSession current = newSession(); + sessions().put(edgeId, current); + newEvents().put(edgeId, true); + migrationProcessed().put(edgeId, Boolean.TRUE); + + // cancel(true) cannot stop a check that has already started, so it runs against the old session + processEvents(superseded); + + assertThat(newEvents()) + .as("consuming the flag here would leave the reconnected session with nothing to fetch") + .containsEntry(edgeId, true); + verify(superseded, never()).processHighPriorityEvents(); + verify(superseded, never()).processEdgeEvents(); + assertThat(edgeEventChecks()).doesNotContainKey(edgeId); + } + + @Test + void zombieCleanupCancelsTheCheckOfTheSessionItRemoves() { + KafkaEdgeGrpcSession zombie = newZombieSession(); + when(zombie.destroy()).thenReturn(true); + sessions().put(edgeId, zombie); + scheduleEdgeEventsCheck(zombie); + ScheduledFuture armedByZombie = edgeEventChecks().get(edgeId); + + cleanupZombieSessions(); + + assertThat(sessions()).doesNotContainKey(edgeId); + assertThat(armedByZombie.isCancelled()) + .as("the removed zombie must not leave an armed check behind") + .isTrue(); + } + + @Test + void zombieCleanupKeepsASessionThatReconnectedDuringTheSweep() { + KafkaEdgeGrpcSession zombie = newZombieSession(); + EdgeGrpcSession reconnected = newSession(); + sessions().put(edgeId, zombie); + // the edge reconnects while the zombie is being destroyed, i.e. after the scan picked it up + when(zombie.destroy()).thenAnswer(invocation -> { + sessions().put(edgeId, reconnected); + scheduleEdgeEventsCheck(reconnected); + return true; + }); + + cleanupZombieSessions(); + + assertThat(sessions().get(edgeId)).isSameAs(reconnected); + ScheduledFuture armedByReconnected = edgeEventChecks().get(edgeId); + assertThat((Object) armedByReconnected).as("the reconnected session keeps its check").isNotNull(); + assertThat(armedByReconnected.isCancelled()).isFalse(); + } + + private EdgeGrpcSession newSession() { + EdgeGrpcSession session = mock(EdgeGrpcSession.class); + stubSession(session); + return session; + } + + private KafkaEdgeGrpcSession newZombieSession() { + KafkaEdgeGrpcSession session = mock(KafkaEdgeGrpcSession.class); + stubSession(session); + @SuppressWarnings("unchecked") + QueueConsumerManager> consumerManager = mock(QueueConsumerManager.class); + @SuppressWarnings("unchecked") + TbQueueConsumer> consumer = mock(TbQueueConsumer.class); + when(consumerManager.getConsumer()).thenReturn(consumer); + when(consumer.isStopped()).thenReturn(false); + when(session.getConsumer()).thenReturn(consumerManager); + return session; + } + + private void stubSession(EdgeGrpcSession session) { + when(session.getEdge()).thenReturn(edge); + when(session.getTenantId()).thenReturn(tenantId); + when(session.getSessionId()).thenReturn(UUID.randomUUID()); + when(session.isConnected()).thenReturn(false); + when(session.destroy()).thenReturn(true); + } + + private void onEdgeConnect(EdgeGrpcSession session) { + ReflectionTestUtils.invokeMethod(service, "onEdgeConnect", edgeId, session); + } + + private void onEdgeDisconnect(EdgeGrpcSession session) { + ReflectionTestUtils.invokeMethod(service, "onEdgeDisconnect", edge, session.getSessionId()); + } + + private void scheduleEdgeEventsCheck(EdgeGrpcSession session) { + ReflectionTestUtils.invokeMethod(service, "scheduleEdgeEventsCheck", session); + } + + private void processEvents(EdgeGrpcSession session) { + ReflectionTestUtils.invokeMethod(service, "processEvents", session, edgeId, tenantId); + } + + private void cleanupZombieSessions() { + ReflectionTestUtils.invokeMethod(service, "cleanupZombieSessions"); + } + + private ConcurrentMap sessions() { + return field("sessions"); + } + + private ConcurrentMap sessionsById() { + return field("sessionsById"); + } + + private ConcurrentMap> edgeEventChecks() { + return field("sessionEdgeEventChecks"); + } + + private Map newEvents() { + return field("sessionNewEvents"); + } + + private ConcurrentMap migrationProcessed() { + return field("edgeEventsMigrationProcessed"); + } + + @SuppressWarnings("unchecked") + private T field(String name) { + return (T) ReflectionTestUtils.getField(service, name); + } + +} From 33e0cb6619925078d0b1b9f08aa713137bb241e8 Mon Sep 17 00:00:00 2001 From: Nikita Mazurenko Date: Thu, 10 Sep 2026 13:58:57 +0300 Subject: [PATCH 026/159] Revert "Release EdgeGrpcClient channel on failed connect and guard send/disconnect race" This reverts commit b67fc8dfb1ad1ca22dc076047f8ee37743b894f2. --- .../thingsboard/edge/rpc/EdgeGrpcClient.java | 146 +++++++----------- 1 file changed, 54 insertions(+), 92 deletions(-) diff --git a/common/edge-api/src/main/java/org/thingsboard/edge/rpc/EdgeGrpcClient.java b/common/edge-api/src/main/java/org/thingsboard/edge/rpc/EdgeGrpcClient.java index f96fe8b38f..7e58a2cb9f 100644 --- a/common/edge-api/src/main/java/org/thingsboard/edge/rpc/EdgeGrpcClient.java +++ b/common/edge-api/src/main/java/org/thingsboard/edge/rpc/EdgeGrpcClient.java @@ -86,7 +86,7 @@ public class EdgeGrpcClient implements EdgeRpcClient { private StreamObserver inputStream; - private final ReentrantLock connectionLock = new ReentrantLock(); + private static final ReentrantLock uplinkMsgLock = new ReentrantLock(); @Override public void connect(String edgeKey, @@ -127,38 +127,19 @@ public class EdgeGrpcClient implements EdgeRpcClient { .build()); } - connectionLock.lock(); - try { - channel = builder.build(); - EdgeRpcServiceGrpc.EdgeRpcServiceStub stub = EdgeRpcServiceGrpc.newStub(channel); - log.info("[{}] Sending a connect request to the TB!", edgeKey); - this.inputStream = stub.withCompression("gzip").handleMsgs(initOutputStream(edgeKey, channel, onUplinkResponse, onEdgeUpdate, onDownlink, onError)); - this.inputStream.onNext(RequestMsg.newBuilder() - .setMsgType(RequestMsgType.CONNECT_RPC_MESSAGE) - .setConnectRequestMsg(ConnectRequestMsg.newBuilder() - .setEdgeRoutingKey(edgeKey) - .setEdgeSecret(edgeSecret) - .setEdgeVersion(getNewestEdgeVersion()) - .setMaxInboundMessageSize(maxInboundMessageSize) - .build()) - .build()); - } catch (RuntimeException e) { - // Release the half-built channel, otherwise every failed reconnect attempt leaks - // its event loops and executors, and the next attempt may not recover at all. - log.error("[{}] Failed to establish the connection, shutting down the channel!", edgeKey, e); - if (channel != null) { - try { - channel.shutdownNow(); - } catch (Exception shutdownEx) { - log.error("[{}] Exception during shutdownNow of the failed channel", edgeKey, shutdownEx); - } - } - channel = null; - inputStream = null; - throw e; - } finally { - connectionLock.unlock(); - } + channel = builder.build(); + EdgeRpcServiceGrpc.EdgeRpcServiceStub stub = EdgeRpcServiceGrpc.newStub(channel); + log.info("[{}] Sending a connect request to the TB!", edgeKey); + this.inputStream = stub.withCompression("gzip").handleMsgs(initOutputStream(edgeKey, onUplinkResponse, onEdgeUpdate, onDownlink, onError)); + this.inputStream.onNext(RequestMsg.newBuilder() + .setMsgType(RequestMsgType.CONNECT_RPC_MESSAGE) + .setConnectRequestMsg(ConnectRequestMsg.newBuilder() + .setEdgeRoutingKey(edgeKey) + .setEdgeSecret(edgeSecret) + .setEdgeVersion(getNewestEdgeVersion()) + .setMaxInboundMessageSize(maxInboundMessageSize) + .build()) + .build()); } public static EdgeVersion getNewestEdgeVersion() { @@ -166,7 +147,6 @@ public class EdgeGrpcClient implements EdgeRpcClient { } private StreamObserver initOutputStream(String edgeKey, - ManagedChannel streamChannel, Consumer onUplinkResponse, Consumer onEdgeUpdate, Consumer onDownlink, @@ -186,7 +166,7 @@ public class EdgeGrpcClient implements EdgeRpcClient { } else { log.error("[{}] Failed to establish the connection! Code: {}. Error message: {}.", edgeKey, connectResponseMsg.getResponseCode(), connectResponseMsg.getErrorMsg()); try { - EdgeGrpcClient.this.disconnect(true, streamChannel); + EdgeGrpcClient.this.disconnect(true); } catch (InterruptedException e) { log.error("[{}] Got interruption during disconnect!", edgeKey, e); } @@ -208,7 +188,7 @@ public class EdgeGrpcClient implements EdgeRpcClient { public void onError(Throwable t) { log.warn("[{}] Stream was terminated due to error:", edgeKey, t); try { - EdgeGrpcClient.this.disconnect(true, streamChannel); + EdgeGrpcClient.this.disconnect(true); } catch (InterruptedException e) { log.error("[{}] Got interruption during disconnect!", edgeKey, e); } @@ -224,95 +204,77 @@ public class EdgeGrpcClient implements EdgeRpcClient { @Override public void disconnect(boolean onError) throws InterruptedException { - disconnect(onError, null); - } - - private void disconnect(boolean onError, ManagedChannel expectedChannel) throws InterruptedException { - ManagedChannel channelToShutdown; - connectionLock.lock(); - try { - // A terminated stream reports its error asynchronously and may lose the race with a - // reconnect: ignore such stale callbacks instead of tearing down the fresh channel. - if (expectedChannel != null && channel != expectedChannel) { - log.info("The channel was already replaced by a reconnect. Skipping disconnect of the stale channel."); - return; - } - if (!onError) { - try { - if (inputStream != null) { - inputStream.onCompleted(); - } - } catch (Exception e) { - log.error("Exception during onCompleted", e); + if (!onError) { + try { + if (inputStream != null) { + inputStream.onCompleted(); } + } catch (Exception e) { + log.error("Exception during onCompleted", e); } - // Clear the references under the lock so that no send can start against a stream - // whose channel is shutting down - such a write leaks the compressed ByteBuf. - inputStream = null; - channelToShutdown = channel; - channel = null; - } finally { - connectionLock.unlock(); } - if (channelToShutdown != null) { - channelToShutdown.shutdown(); + if (channel != null) { + channel.shutdown(); int attempt = 0; do { try { - channelToShutdown.awaitTermination(timeoutSecs, TimeUnit.SECONDS); + channel.awaitTermination(timeoutSecs, TimeUnit.SECONDS); } catch (Exception e) { log.error("Channel await termination was interrupted", e); } if (attempt > 5) { log.warn("We had reached maximum of termination attempts. Force closing channel"); try { - channelToShutdown.shutdownNow(); + channel.shutdownNow(); } catch (Exception e) { log.error("Exception during shutdownNow", e); } break; } attempt++; - } while (!channelToShutdown.isTerminated()); + } while (!channel.isTerminated()); } } @Override public void sendUplinkMsg(UplinkMsg msg) { - sendRequestMsg(RequestMsg.newBuilder() - .setMsgType(RequestMsgType.UPLINK_RPC_MESSAGE) - .setUplinkMsg(msg) - .build()); + uplinkMsgLock.lock(); + try { + this.inputStream.onNext(RequestMsg.newBuilder() + .setMsgType(RequestMsgType.UPLINK_RPC_MESSAGE) + .setUplinkMsg(msg) + .build()); + } finally { + uplinkMsgLock.unlock(); + } } @Override public void sendSyncRequestMsg(boolean fullSyncRequired) { - SyncRequestMsg syncRequestMsg = SyncRequestMsg.newBuilder() - .setFullSync(fullSyncRequired) - .build(); - sendRequestMsg(RequestMsg.newBuilder() - .setMsgType(RequestMsgType.SYNC_REQUEST_RPC_MESSAGE) - .setSyncRequestMsg(syncRequestMsg) - .build()); + uplinkMsgLock.lock(); + try { + SyncRequestMsg syncRequestMsg = SyncRequestMsg.newBuilder() + .setFullSync(fullSyncRequired) + .build(); + this.inputStream.onNext(RequestMsg.newBuilder() + .setMsgType(RequestMsgType.SYNC_REQUEST_RPC_MESSAGE) + .setSyncRequestMsg(syncRequestMsg) + .build()); + } finally { + uplinkMsgLock.unlock(); + } } @Override public void sendDownlinkResponseMsg(DownlinkResponseMsg downlinkResponseMsg) { - sendRequestMsg(RequestMsg.newBuilder() - .setMsgType(RequestMsgType.UPLINK_RPC_MESSAGE) - .setDownlinkResponseMsg(downlinkResponseMsg) - .build()); - } - - private void sendRequestMsg(RequestMsg requestMsg) { - connectionLock.lock(); + uplinkMsgLock.lock(); try { - if (inputStream == null) { - throw new IllegalStateException("Edge is not connected to the cloud. The message is discarded!"); - } - inputStream.onNext(requestMsg); + this.inputStream.onNext(RequestMsg.newBuilder() + .setMsgType(RequestMsgType.UPLINK_RPC_MESSAGE) + .setDownlinkResponseMsg(downlinkResponseMsg) + .build()); } finally { - connectionLock.unlock(); + uplinkMsgLock.unlock(); } } From 970d590a642ca5d14ab765085f44676f4b18f8b8 Mon Sep 17 00:00:00 2001 From: Nikita Mazurenko Date: Thu, 10 Sep 2026 15:02:46 +0300 Subject: [PATCH 027/159] Serialize JS script release under evalLock and cover both Nashorn backends --- .../script/NashornJsInvokeServiceTest.java | 5 +- .../script/api/js/NashornJsInvokeService.java | 16 ++- .../NashornJsInvokeServiceLifecycleTest.java | 122 ++++++++++++++++++ 3 files changed, 136 insertions(+), 7 deletions(-) create mode 100644 common/script/script-api/src/test/java/org/thingsboard/script/api/js/NashornJsInvokeServiceLifecycleTest.java diff --git a/application/src/test/java/org/thingsboard/server/service/script/NashornJsInvokeServiceTest.java b/application/src/test/java/org/thingsboard/server/service/script/NashornJsInvokeServiceTest.java index c76eac8c61..1b0ac652b0 100644 --- a/application/src/test/java/org/thingsboard/server/service/script/NashornJsInvokeServiceTest.java +++ b/application/src/test/java/org/thingsboard/server/service/script/NashornJsInvokeServiceTest.java @@ -231,12 +231,13 @@ class NashornJsInvokeServiceTest extends AbstractControllerTest { void whenScriptIsReleased_thenGlobalPropertyIsRemoved() throws Exception { UUID scriptId = evalScript("return msg;"); String functionName = "invokeInternal_" + scriptId.toString().replace('-', '_'); - assertThat(evalInEngine("this.hasOwnProperty('" + functionName + "')")).hasToString("true"); + assertThat(evalInEngine("this.hasOwnProperty('" + functionName + "')")).isEqualTo(true); invokeService.release(scriptId).get(); // the property must be deleted, not just set to undefined: an abandoned binding keeps - assertThat(evalInEngine("this.hasOwnProperty('" + functionName + "')")).hasToString("false"); + // its slot in the Global's PropertyMap forever + assertThat(evalInEngine("this.hasOwnProperty('" + functionName + "')")).isEqualTo(false); } @Test diff --git a/common/script/script-api/src/main/java/org/thingsboard/script/api/js/NashornJsInvokeService.java b/common/script/script-api/src/main/java/org/thingsboard/script/api/js/NashornJsInvokeService.java index bb95c60481..32ab55f7ef 100644 --- a/common/script/script-api/src/main/java/org/thingsboard/script/api/js/NashornJsInvokeService.java +++ b/common/script/script-api/src/main/java/org/thingsboard/script/api/js/NashornJsInvokeService.java @@ -144,7 +144,8 @@ public class NashornJsInvokeService extends AbstractJsInvokeService { // that can never be deleted, so every eval/release cycle would grow the Global's PropertyMap // shape history forever. Declaring the function inside an IIFE and assigning it to a global // property keeps the property configurable, allowing doRelease() to actually delete it. - // The prefix stays on the first line so that script line numbers in errors are unchanged. + // The prefix stays on the first line to preserve line numbering on the raw engine path; + // the sandbox beautifier reformats the wrapper and shifts reported error lines anyway. String wrappedScript = "this['" + scriptInfo.getFunctionName() + "'] = (function() { " + jsScript + "\nreturn " + scriptInfo.getFunctionName() + ";\n})();"; return jsExecutor.submit(() -> { @@ -190,10 +191,15 @@ public class NashornJsInvokeService extends AbstractJsInvokeService { protected void doRelease(UUID scriptId, JsScriptInfo scriptInfo) throws ScriptException { String deleteScript = "delete this['" + scriptInfo.getFunctionName() + "'];"; - if (useJsSandbox) { - sandbox.eval(deleteScript); - } else { - engine.eval(deleteScript); + evalLock.lock(); + try { + if (useJsSandbox) { + sandbox.eval(deleteScript); + } else { + engine.eval(deleteScript); + } + } finally { + evalLock.unlock(); } } diff --git a/common/script/script-api/src/test/java/org/thingsboard/script/api/js/NashornJsInvokeServiceLifecycleTest.java b/common/script/script-api/src/test/java/org/thingsboard/script/api/js/NashornJsInvokeServiceLifecycleTest.java new file mode 100644 index 0000000000..cdfd2d8e93 --- /dev/null +++ b/common/script/script-api/src/test/java/org/thingsboard/script/api/js/NashornJsInvokeServiceLifecycleTest.java @@ -0,0 +1,122 @@ +/** + * Copyright © 2016-2026 The Thingsboard Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.thingsboard.script.api.js; + +import delight.nashornsandbox.NashornSandbox; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; +import org.mockito.Mockito; +import org.springframework.test.util.ReflectionTestUtils; +import org.thingsboard.script.api.ScriptType; +import org.thingsboard.script.api.TbScriptException; +import org.thingsboard.server.common.data.id.TenantId; +import org.thingsboard.server.common.stats.StatsFactory; + +import javax.script.ScriptEngine; +import java.util.Optional; +import java.util.UUID; +import java.util.concurrent.ExecutionException; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.Mockito.mock; + +/** + * Covers the JS global scope lifecycle against both backends the service can be configured with. + * The Spring-wired {@code NashornJsInvokeServiceTest} only exercises the sandbox, since + * {@code js.local.use_js_sandbox} defaults to true. + */ +class NashornJsInvokeServiceLifecycleTest { + + private static final String[] ARG_NAMES = {"msg", "metadata", "msgType"}; + + private NashornJsInvokeService service; + private boolean useJsSandbox; + + @AfterEach + void tearDown() { + if (service != null) { + service.stop(); + } + } + + @ParameterizedTest(name = "useJsSandbox = {0}") + @ValueSource(booleans = {true, false}) + void whenScriptIsReleased_thenGlobalPropertyIsRemovedAndFunctionIsGone(boolean useJsSandbox) throws Exception { + givenService(useJsSandbox); + UUID scriptId = UUID.randomUUID(); + + JsScriptInfo scriptInfo = eval(scriptId, "return {doubled: msg.temperature * 2};"); + assertThat(hasGlobalProperty(scriptInfo)).isTrue(); + assertThat(invoke(scriptId, scriptInfo, "{\"temperature\":21}")).asString().contains("\"doubled\":42"); + + service.doRelease(scriptId); + + assertThat(hasGlobalProperty(scriptInfo)).isFalse(); + assertThatThrownBy(() -> invoke(scriptId, scriptInfo, "{\"temperature\":21}")) + .isInstanceOf(ExecutionException.class) + .cause() + .isInstanceOf(TbScriptException.class); + } + + @ParameterizedTest(name = "useJsSandbox = {0}") + @ValueSource(booleans = {true, false}) + void whenOneOfTwoScriptsIsReleased_thenTheOtherKeepsWorking(boolean useJsSandbox) throws Exception { + givenService(useJsSandbox); + UUID releasedId = UUID.randomUUID(); + UUID retainedId = UUID.randomUUID(); + + JsScriptInfo released = eval(releasedId, "return {v: 1};"); + JsScriptInfo retained = eval(retainedId, "return {v: 2};"); + + service.doRelease(releasedId); + + assertThat(hasGlobalProperty(released)).isFalse(); + assertThat(hasGlobalProperty(retained)).isTrue(); + assertThat(invoke(retainedId, retained, "{}")).asString().contains("\"v\":2"); + } + + private void givenService(boolean useJsSandbox) { + this.useJsSandbox = useJsSandbox; + service = new NashornJsInvokeService(Optional.empty(), Optional.empty()); + ReflectionTestUtils.setField(service, "statsFactory", mock(StatsFactory.class, Mockito.RETURNS_DEEP_STUBS)); + ReflectionTestUtils.setField(service, "useJsSandbox", useJsSandbox); + ReflectionTestUtils.setField(service, "jsExecutorThreadPoolSize", 4); + ReflectionTestUtils.setField(service, "monitorThreadPoolSize", 2); + ReflectionTestUtils.setField(service, "maxCpuTime", 8000L); + ReflectionTestUtils.setField(service, "maxMemory", 104857600L); + service.init(); + } + + private JsScriptInfo eval(UUID scriptId, String scriptBody) throws Exception { + service.doEvalScript(TenantId.SYS_TENANT_ID, ScriptType.RULE_NODE_SCRIPT, scriptBody, scriptId, ARG_NAMES).get(); + return service.scriptInfoMap.get(scriptId); + } + + private Object invoke(UUID scriptId, JsScriptInfo scriptInfo, String msg) throws Exception { + return service.doInvokeFunction(scriptId, scriptInfo, new Object[]{msg, "{}", "POST_TELEMETRY_REQUEST"}).get(); + } + + private boolean hasGlobalProperty(JsScriptInfo scriptInfo) throws Exception { + String expression = "this.hasOwnProperty('" + scriptInfo.getFunctionName() + "')"; + Object result = useJsSandbox + ? ((NashornSandbox) ReflectionTestUtils.getField(service, "sandbox")).eval(expression) + : ((ScriptEngine) ReflectionTestUtils.getField(service, "engine")).eval(expression); + return Boolean.TRUE.equals(result); + } + +} From bd25bee271ecd9ba540022a4b840db1e0f3f059d Mon Sep 17 00:00:00 2001 From: dpinkevych Date: Fri, 11 Sep 2026 10:42:54 +0300 Subject: [PATCH 028/159] give the validation a result type of its own validateSolution borrowed SolutionInstallResponse and used null to say that nothing conflicts, so the call site had to test two different ways of saying "go ahead". It returns a SolutionValidationResult now, built through passed() or conflictsFound(report) - the private constructor keeps the two states honest - and the install response is assembled where the install actually answers. --- .../solutions/DefaultSolutionService.java | 23 +++++--- .../data/SolutionValidationResult.java | 43 ++++++++++++++ .../solutions/DefaultSolutionServiceTest.java | 57 +++++++++---------- 3 files changed, 85 insertions(+), 38 deletions(-) create mode 100644 application/src/main/java/org/thingsboard/server/service/solutions/data/SolutionValidationResult.java diff --git a/application/src/main/java/org/thingsboard/server/service/solutions/DefaultSolutionService.java b/application/src/main/java/org/thingsboard/server/service/solutions/DefaultSolutionService.java index b279d693ef..ad8c6a224b 100644 --- a/application/src/main/java/org/thingsboard/server/service/solutions/DefaultSolutionService.java +++ b/application/src/main/java/org/thingsboard/server/service/solutions/DefaultSolutionService.java @@ -111,6 +111,7 @@ import org.thingsboard.server.service.solutions.data.DashboardLinkInfo; import org.thingsboard.server.service.solutions.data.DeviceCredentialsInfo; import org.thingsboard.server.service.solutions.data.EdgeLinkInfo; import org.thingsboard.server.service.solutions.data.SolutionInstallContext; +import org.thingsboard.server.service.solutions.data.SolutionValidationResult; import org.thingsboard.server.service.solutions.data.UserCredentialsInfo; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.thingsboard.server.service.solutions.data.definition.AssetDefinition; @@ -257,9 +258,9 @@ public class DefaultSolutionService implements SolutionService { throw new IllegalArgumentException("Solution template is missing solution.json or its 'title' field"); } - SolutionInstallResponse validateResult = validateSolution(tenantId, tempDir); - if (validateResult != null && !validateResult.isSuccess()) { - return validateResult; + SolutionValidationResult validation = validateSolution(tenantId, tempDir); + if (!validation.isPassed()) { + return conflictResponse(validation.getConflictReport()); } return doInstallSolution(user, tenantId, solutionId, tempDir, request); } finally { @@ -300,7 +301,7 @@ public class DefaultSolutionService implements SolutionService { } } - SolutionInstallResponse validateSolution(TenantId tenantId, Path tempDir) { + SolutionValidationResult validateSolution(TenantId tenantId, Path tempDir) { //TODO: pre-validate what still only fails at provision time: customer users (unique by email), // alarm rules and calculated fields. @@ -338,7 +339,7 @@ public class DefaultSolutionService implements SolutionService { collectConflicts(conflicts, edges, name -> edgeService.findEdgeByTenantIdAndName(tenantId, name)); if (conflicts.isEmpty()) { - return null; + return SolutionValidationResult.passed(); } StringBuilder details = new StringBuilder(CONFLICTS_INTRO).append(BLANK_LINE); conflicts.forEach((entityType, conflictDescriptions) -> appendConflicts(details, entityType, conflictDescriptions)); @@ -346,10 +347,14 @@ public class DefaultSolutionService implements SolutionService { details.append(System.lineSeparator()).append(TRUNCATION_NOTE); } - SolutionInstallResponse solutionInstallResponse = new SolutionInstallResponse(); - solutionInstallResponse.setSuccess(false); - solutionInstallResponse.setDetails(details.toString()); - return solutionInstallResponse; + return SolutionValidationResult.conflictsFound(details.toString()); + } + + private static SolutionInstallResponse conflictResponse(String conflictReport) { + SolutionInstallResponse response = new SolutionInstallResponse(); + response.setSuccess(false); + response.setDetails(conflictReport); + return response; } /** diff --git a/application/src/main/java/org/thingsboard/server/service/solutions/data/SolutionValidationResult.java b/application/src/main/java/org/thingsboard/server/service/solutions/data/SolutionValidationResult.java new file mode 100644 index 0000000000..407290e487 --- /dev/null +++ b/application/src/main/java/org/thingsboard/server/service/solutions/data/SolutionValidationResult.java @@ -0,0 +1,43 @@ +/** + * Copyright © 2016-2026 The Thingsboard Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.thingsboard.server.service.solutions.data; + +import lombok.AccessLevel; +import lombok.Getter; +import lombok.RequiredArgsConstructor; + +/** + * The outcome of validating a solution template before anything is created: either the install can go ahead, or the + * entities of the tenant the template clashes with, reported as the markdown the install dialog renders. + */ +@Getter +@RequiredArgsConstructor(access = AccessLevel.PRIVATE) +public class SolutionValidationResult { + + private static final SolutionValidationResult PASSED = new SolutionValidationResult(true, ""); + + private final boolean passed; + private final String conflictReport; + + public static SolutionValidationResult passed() { + return PASSED; + } + + public static SolutionValidationResult conflictsFound(String conflictReport) { + return new SolutionValidationResult(false, conflictReport); + } + +} diff --git a/application/src/test/java/org/thingsboard/server/service/solutions/DefaultSolutionServiceTest.java b/application/src/test/java/org/thingsboard/server/service/solutions/DefaultSolutionServiceTest.java index b1b5f1726a..860a6d3a0c 100644 --- a/application/src/test/java/org/thingsboard/server/service/solutions/DefaultSolutionServiceTest.java +++ b/application/src/test/java/org/thingsboard/server/service/solutions/DefaultSolutionServiceTest.java @@ -41,7 +41,7 @@ import org.thingsboard.server.dao.device.DeviceProfileService; import org.thingsboard.server.dao.device.DeviceService; import org.thingsboard.server.dao.edge.EdgeService; import org.thingsboard.server.dao.rule.RuleChainService; -import org.thingsboard.server.service.solutions.data.solution.SolutionInstallResponse; +import org.thingsboard.server.service.solutions.data.SolutionValidationResult; import java.io.IOException; import java.nio.file.Files; @@ -111,18 +111,17 @@ class DefaultSolutionServiceTest { .thenReturn(existingDevice("Existing device")); when(deviceService.findDeviceByTenantIdAndName(tenantId, "New device")).thenReturn(null); - SolutionInstallResponse result = service.validateSolution(tenantId, tempDir); + SolutionValidationResult result = service.validateSolution(tenantId, tempDir); - assertThat(result).isNotNull(); - assertThat(result.isSuccess()).isFalse(); - assertThat(result.getDetails().lines().toList()) + assertThat(result.isPassed()).isFalse(); + assertThat(result.getConflictReport().lines().toList()) .containsSubsequence( CONFLICTS_INTRO, "- **Customer**: 'Existing customer'", "- **Asset**: 'Existing asset'", "- **Device**: 'Existing device'"); // the randomized customer title and the entities that do not exist yet are not reported - assertThat(result.getDetails()) + assertThat(result.getConflictReport()) .doesNotContain("Customer $random") .doesNotContain("New device") .doesNotContain("New asset"); @@ -136,10 +135,10 @@ class DefaultSolutionServiceTest { dashboard.setTitle("Overview"); when(dashboardService.findFirstDashboardInfoByTenantIdAndName(tenantId, "Overview")).thenReturn(dashboard); - SolutionInstallResponse result = service.validateSolution(tenantId, tempDir); + SolutionValidationResult result = service.validateSolution(tenantId, tempDir); - assertThat(result).isNotNull(); - assertThat(result.getDetails().lines().toList()) + assertThat(result.isPassed()).isFalse(); + assertThat(result.getConflictReport().lines().toList()) .containsSubsequence(CONFLICTS_INTRO, "- **Dashboard**: 'Overview'"); } @@ -153,10 +152,10 @@ class DefaultSolutionServiceTest { when(ruleChainService.findTenantRuleChainsByTypeAndName(tenantId, RuleChainType.CORE, "Name the install creates")) .thenReturn(List.of(ruleChain)); - SolutionInstallResponse result = service.validateSolution(tenantId, tempDir); + SolutionValidationResult result = service.validateSolution(tenantId, tempDir); - assertThat(result).isNotNull(); - assertThat(result.getDetails().lines().toList()) + assertThat(result.isPassed()).isFalse(); + assertThat(result.getConflictReport().lines().toList()) .containsSubsequence(CONFLICTS_INTRO, "- **Rule chain**: 'Name the install creates'"); } @@ -176,10 +175,10 @@ class DefaultSolutionServiceTest { when(assetProfileService.findAssetProfileByName(tenantId, "building")).thenReturn(assetProfile); when(edgeService.findEdgeByTenantIdAndName(tenantId, "Main edge")).thenReturn(edge); - SolutionInstallResponse result = service.validateSolution(tenantId, tempDir); + SolutionValidationResult result = service.validateSolution(tenantId, tempDir); - assertThat(result).isNotNull(); - assertThat(result.getDetails().lines().toList()).containsSubsequence( + assertThat(result.isPassed()).isFalse(); + assertThat(result.getConflictReport().lines().toList()).containsSubsequence( "- **Device profile**: 'thermostat'", "- **Asset profile**: 'building'", "- **Edge**: 'Main edge'"); @@ -191,9 +190,9 @@ class DefaultSolutionServiceTest { when(deviceService.findDeviceByTenantIdAndName(tenantId, "Sensor")).thenReturn(existingDevice("Sensor")); - SolutionInstallResponse result = service.validateSolution(tenantId, tempDir); + SolutionValidationResult result = service.validateSolution(tenantId, tempDir); - assertThat(result.getDetails().lines().toList()).contains("- **Device**: 'Sensor'"); + assertThat(result.getConflictReport().lines().toList()).contains("- **Device**: 'Sensor'"); verify(deviceService, times(1)).findDeviceByTenantIdAndName(tenantId, "Sensor"); } @@ -203,7 +202,7 @@ class DefaultSolutionServiceTest { "{\"name\": \"No name inside\", \"file\": \"nameless.json\"}]"); writeFile("rule_chains/nameless.json", "{\"ruleChain\": {}}"); - assertThat(service.validateSolution(tenantId, tempDir)).isNull(); + assertThat(service.validateSolution(tenantId, tempDir).isPassed()).isTrue(); verifyNoInteractions(ruleChainService); } @@ -217,16 +216,16 @@ class DefaultSolutionServiceTest { when(ruleChainService.findTenantRuleChainsByTypeAndName(tenantId, RuleChainType.EDGE, "Edge chain")) .thenReturn(List.of(ruleChain)); - SolutionInstallResponse result = service.validateSolution(tenantId, tempDir); + SolutionValidationResult result = service.validateSolution(tenantId, tempDir); - assertThat(result.getDetails().lines().toList()).contains("- **Rule chain**: 'Edge chain'"); + assertThat(result.getConflictReport().lines().toList()).contains("- **Rule chain**: 'Edge chain'"); } @Test void testValidateSolutionTreatsAJsonNullFileAsEmpty() throws IOException { writeEntitiesFile("devices.json", "null"); - assertThat(service.validateSolution(tenantId, tempDir)).isNull(); + assertThat(service.validateSolution(tenantId, tempDir).isPassed()).isTrue(); verifyNoInteractions(deviceService); } @@ -240,17 +239,17 @@ class DefaultSolutionServiceTest { names.forEach(name -> when(deviceService.findDeviceByTenantIdAndName(tenantId, name)) .thenReturn(existingDevice(name))); - SolutionInstallResponse result = service.validateSolution(tenantId, tempDir); + SolutionValidationResult result = service.validateSolution(tenantId, tempDir); int hidden = conflictCount - LISTED_NAMES_PER_TYPE; String listed = names.stream().limit(LISTED_NAMES_PER_TYPE) .map(name -> "'" + name + "'").collect(Collectors.joining(", ")); - assertThat(result.getDetails().lines().toList()).contains("- **Device**: " + listed + assertThat(result.getConflictReport().lines().toList()).contains("- **Device**: " + listed + (hidden > 0 ? " and " + hidden + " more (" + conflictCount + " in total)" : "")); if (hidden > 0) { - assertThat(result.getDetails()).contains(TRUNCATION_NOTE); + assertThat(result.getConflictReport()).contains(TRUNCATION_NOTE); } else { - assertThat(result.getDetails()).doesNotContain(TRUNCATION_NOTE); + assertThat(result.getConflictReport()).doesNotContain(TRUNCATION_NOTE); } } @@ -267,9 +266,9 @@ class DefaultSolutionServiceTest { profile.setName("Sensor profile"); when(deviceProfileService.findDeviceProfileByName(tenantId, "Sensor profile")).thenReturn(profile); - SolutionInstallResponse result = service.validateSolution(tenantId, tempDir); + SolutionValidationResult result = service.validateSolution(tenantId, tempDir); - assertThat(result.getDetails().lines().toList()).contains("- **Device profile**: 'Sensor profile'"); + assertThat(result.getConflictReport().lines().toList()).contains("- **Device profile**: 'Sensor profile'"); verify(deviceProfileService, times(1)).findDeviceProfileByName(tenantId, "Sensor profile"); } @@ -278,12 +277,12 @@ class DefaultSolutionServiceTest { writeEntitiesFile("devices.json", "[{\"name\": \"New device\"}]"); when(deviceService.findDeviceByTenantIdAndName(tenantId, "New device")).thenReturn(null); - assertThat(service.validateSolution(tenantId, tempDir)).isNull(); + assertThat(service.validateSolution(tenantId, tempDir).isPassed()).isTrue(); } @Test void testValidateSolutionWithoutEntityFiles() { - assertThat(service.validateSolution(tenantId, tempDir)).isNull(); + assertThat(service.validateSolution(tenantId, tempDir).isPassed()).isTrue(); verifyNoInteractions(customerService, deviceService, assetService, dashboardService, ruleChainService, deviceProfileService, assetProfileService, edgeService); } From a1ff35f6b1f10f15ab57b2f9016fe9fd1b397b53 Mon Sep 17 00:00:00 2001 From: dpinkevych Date: Fri, 11 Sep 2026 10:42:55 +0300 Subject: [PATCH 029/159] give the validation a result type of its own validateSolution borrowed SolutionInstallResponse and used null to say that nothing conflicts, so the call site had to test two different ways of saying "go ahead". It returns a SolutionValidationResult now, built through passed() or conflictsFound(report) - the private constructor keeps the two states honest - and the install response is assembled where the install actually answers. --- .../solutions/DefaultSolutionService.java | 23 +++++--- .../data/SolutionValidationResult.java | 43 ++++++++++++++ .../solutions/DefaultSolutionServiceTest.java | 57 +++++++++---------- 3 files changed, 85 insertions(+), 38 deletions(-) create mode 100644 application/src/main/java/org/thingsboard/server/service/solutions/data/SolutionValidationResult.java diff --git a/application/src/main/java/org/thingsboard/server/service/solutions/DefaultSolutionService.java b/application/src/main/java/org/thingsboard/server/service/solutions/DefaultSolutionService.java index 81000b6e45..65655e75e6 100644 --- a/application/src/main/java/org/thingsboard/server/service/solutions/DefaultSolutionService.java +++ b/application/src/main/java/org/thingsboard/server/service/solutions/DefaultSolutionService.java @@ -113,6 +113,7 @@ import org.thingsboard.server.service.solutions.data.DashboardLinkInfo; import org.thingsboard.server.service.solutions.data.DeviceCredentialsInfo; import org.thingsboard.server.service.solutions.data.EdgeLinkInfo; import org.thingsboard.server.service.solutions.data.SolutionInstallContext; +import org.thingsboard.server.service.solutions.data.SolutionValidationResult; import org.thingsboard.server.service.solutions.data.UserCredentialsInfo; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.thingsboard.server.service.solutions.data.definition.AssetDefinition; @@ -259,9 +260,9 @@ public class DefaultSolutionService implements SolutionService { throw new IllegalArgumentException("Solution template is missing solution.json or its 'title' field"); } - SolutionInstallResponse validateResult = validateSolution(tenantId, tempDir); - if (validateResult != null && !validateResult.isSuccess()) { - return validateResult; + SolutionValidationResult validation = validateSolution(tenantId, tempDir); + if (!validation.isPassed()) { + return conflictResponse(validation.getConflictReport()); } return doInstallSolution(user, tenantId, solutionId, tempDir, request); } finally { @@ -302,7 +303,7 @@ public class DefaultSolutionService implements SolutionService { } } - SolutionInstallResponse validateSolution(TenantId tenantId, Path tempDir) { + SolutionValidationResult validateSolution(TenantId tenantId, Path tempDir) { //TODO: pre-validate what still only fails at provision time: customer users (unique by email), // alarm rules and calculated fields. @@ -340,7 +341,7 @@ public class DefaultSolutionService implements SolutionService { collectConflicts(conflicts, edges, name -> edgeService.findEdgeByTenantIdAndName(tenantId, name)); if (conflicts.isEmpty()) { - return null; + return SolutionValidationResult.passed(); } StringBuilder details = new StringBuilder(CONFLICTS_INTRO).append(BLANK_LINE); conflicts.forEach((entityType, conflictDescriptions) -> appendConflicts(details, entityType, conflictDescriptions)); @@ -348,10 +349,14 @@ public class DefaultSolutionService implements SolutionService { details.append(System.lineSeparator()).append(TRUNCATION_NOTE); } - SolutionInstallResponse solutionInstallResponse = new SolutionInstallResponse(); - solutionInstallResponse.setSuccess(false); - solutionInstallResponse.setDetails(details.toString()); - return solutionInstallResponse; + return SolutionValidationResult.conflictsFound(details.toString()); + } + + private static SolutionInstallResponse conflictResponse(String conflictReport) { + SolutionInstallResponse response = new SolutionInstallResponse(); + response.setSuccess(false); + response.setDetails(conflictReport); + return response; } /** diff --git a/application/src/main/java/org/thingsboard/server/service/solutions/data/SolutionValidationResult.java b/application/src/main/java/org/thingsboard/server/service/solutions/data/SolutionValidationResult.java new file mode 100644 index 0000000000..407290e487 --- /dev/null +++ b/application/src/main/java/org/thingsboard/server/service/solutions/data/SolutionValidationResult.java @@ -0,0 +1,43 @@ +/** + * Copyright © 2016-2026 The Thingsboard Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.thingsboard.server.service.solutions.data; + +import lombok.AccessLevel; +import lombok.Getter; +import lombok.RequiredArgsConstructor; + +/** + * The outcome of validating a solution template before anything is created: either the install can go ahead, or the + * entities of the tenant the template clashes with, reported as the markdown the install dialog renders. + */ +@Getter +@RequiredArgsConstructor(access = AccessLevel.PRIVATE) +public class SolutionValidationResult { + + private static final SolutionValidationResult PASSED = new SolutionValidationResult(true, ""); + + private final boolean passed; + private final String conflictReport; + + public static SolutionValidationResult passed() { + return PASSED; + } + + public static SolutionValidationResult conflictsFound(String conflictReport) { + return new SolutionValidationResult(false, conflictReport); + } + +} diff --git a/application/src/test/java/org/thingsboard/server/service/solutions/DefaultSolutionServiceTest.java b/application/src/test/java/org/thingsboard/server/service/solutions/DefaultSolutionServiceTest.java index b1b5f1726a..860a6d3a0c 100644 --- a/application/src/test/java/org/thingsboard/server/service/solutions/DefaultSolutionServiceTest.java +++ b/application/src/test/java/org/thingsboard/server/service/solutions/DefaultSolutionServiceTest.java @@ -41,7 +41,7 @@ import org.thingsboard.server.dao.device.DeviceProfileService; import org.thingsboard.server.dao.device.DeviceService; import org.thingsboard.server.dao.edge.EdgeService; import org.thingsboard.server.dao.rule.RuleChainService; -import org.thingsboard.server.service.solutions.data.solution.SolutionInstallResponse; +import org.thingsboard.server.service.solutions.data.SolutionValidationResult; import java.io.IOException; import java.nio.file.Files; @@ -111,18 +111,17 @@ class DefaultSolutionServiceTest { .thenReturn(existingDevice("Existing device")); when(deviceService.findDeviceByTenantIdAndName(tenantId, "New device")).thenReturn(null); - SolutionInstallResponse result = service.validateSolution(tenantId, tempDir); + SolutionValidationResult result = service.validateSolution(tenantId, tempDir); - assertThat(result).isNotNull(); - assertThat(result.isSuccess()).isFalse(); - assertThat(result.getDetails().lines().toList()) + assertThat(result.isPassed()).isFalse(); + assertThat(result.getConflictReport().lines().toList()) .containsSubsequence( CONFLICTS_INTRO, "- **Customer**: 'Existing customer'", "- **Asset**: 'Existing asset'", "- **Device**: 'Existing device'"); // the randomized customer title and the entities that do not exist yet are not reported - assertThat(result.getDetails()) + assertThat(result.getConflictReport()) .doesNotContain("Customer $random") .doesNotContain("New device") .doesNotContain("New asset"); @@ -136,10 +135,10 @@ class DefaultSolutionServiceTest { dashboard.setTitle("Overview"); when(dashboardService.findFirstDashboardInfoByTenantIdAndName(tenantId, "Overview")).thenReturn(dashboard); - SolutionInstallResponse result = service.validateSolution(tenantId, tempDir); + SolutionValidationResult result = service.validateSolution(tenantId, tempDir); - assertThat(result).isNotNull(); - assertThat(result.getDetails().lines().toList()) + assertThat(result.isPassed()).isFalse(); + assertThat(result.getConflictReport().lines().toList()) .containsSubsequence(CONFLICTS_INTRO, "- **Dashboard**: 'Overview'"); } @@ -153,10 +152,10 @@ class DefaultSolutionServiceTest { when(ruleChainService.findTenantRuleChainsByTypeAndName(tenantId, RuleChainType.CORE, "Name the install creates")) .thenReturn(List.of(ruleChain)); - SolutionInstallResponse result = service.validateSolution(tenantId, tempDir); + SolutionValidationResult result = service.validateSolution(tenantId, tempDir); - assertThat(result).isNotNull(); - assertThat(result.getDetails().lines().toList()) + assertThat(result.isPassed()).isFalse(); + assertThat(result.getConflictReport().lines().toList()) .containsSubsequence(CONFLICTS_INTRO, "- **Rule chain**: 'Name the install creates'"); } @@ -176,10 +175,10 @@ class DefaultSolutionServiceTest { when(assetProfileService.findAssetProfileByName(tenantId, "building")).thenReturn(assetProfile); when(edgeService.findEdgeByTenantIdAndName(tenantId, "Main edge")).thenReturn(edge); - SolutionInstallResponse result = service.validateSolution(tenantId, tempDir); + SolutionValidationResult result = service.validateSolution(tenantId, tempDir); - assertThat(result).isNotNull(); - assertThat(result.getDetails().lines().toList()).containsSubsequence( + assertThat(result.isPassed()).isFalse(); + assertThat(result.getConflictReport().lines().toList()).containsSubsequence( "- **Device profile**: 'thermostat'", "- **Asset profile**: 'building'", "- **Edge**: 'Main edge'"); @@ -191,9 +190,9 @@ class DefaultSolutionServiceTest { when(deviceService.findDeviceByTenantIdAndName(tenantId, "Sensor")).thenReturn(existingDevice("Sensor")); - SolutionInstallResponse result = service.validateSolution(tenantId, tempDir); + SolutionValidationResult result = service.validateSolution(tenantId, tempDir); - assertThat(result.getDetails().lines().toList()).contains("- **Device**: 'Sensor'"); + assertThat(result.getConflictReport().lines().toList()).contains("- **Device**: 'Sensor'"); verify(deviceService, times(1)).findDeviceByTenantIdAndName(tenantId, "Sensor"); } @@ -203,7 +202,7 @@ class DefaultSolutionServiceTest { "{\"name\": \"No name inside\", \"file\": \"nameless.json\"}]"); writeFile("rule_chains/nameless.json", "{\"ruleChain\": {}}"); - assertThat(service.validateSolution(tenantId, tempDir)).isNull(); + assertThat(service.validateSolution(tenantId, tempDir).isPassed()).isTrue(); verifyNoInteractions(ruleChainService); } @@ -217,16 +216,16 @@ class DefaultSolutionServiceTest { when(ruleChainService.findTenantRuleChainsByTypeAndName(tenantId, RuleChainType.EDGE, "Edge chain")) .thenReturn(List.of(ruleChain)); - SolutionInstallResponse result = service.validateSolution(tenantId, tempDir); + SolutionValidationResult result = service.validateSolution(tenantId, tempDir); - assertThat(result.getDetails().lines().toList()).contains("- **Rule chain**: 'Edge chain'"); + assertThat(result.getConflictReport().lines().toList()).contains("- **Rule chain**: 'Edge chain'"); } @Test void testValidateSolutionTreatsAJsonNullFileAsEmpty() throws IOException { writeEntitiesFile("devices.json", "null"); - assertThat(service.validateSolution(tenantId, tempDir)).isNull(); + assertThat(service.validateSolution(tenantId, tempDir).isPassed()).isTrue(); verifyNoInteractions(deviceService); } @@ -240,17 +239,17 @@ class DefaultSolutionServiceTest { names.forEach(name -> when(deviceService.findDeviceByTenantIdAndName(tenantId, name)) .thenReturn(existingDevice(name))); - SolutionInstallResponse result = service.validateSolution(tenantId, tempDir); + SolutionValidationResult result = service.validateSolution(tenantId, tempDir); int hidden = conflictCount - LISTED_NAMES_PER_TYPE; String listed = names.stream().limit(LISTED_NAMES_PER_TYPE) .map(name -> "'" + name + "'").collect(Collectors.joining(", ")); - assertThat(result.getDetails().lines().toList()).contains("- **Device**: " + listed + assertThat(result.getConflictReport().lines().toList()).contains("- **Device**: " + listed + (hidden > 0 ? " and " + hidden + " more (" + conflictCount + " in total)" : "")); if (hidden > 0) { - assertThat(result.getDetails()).contains(TRUNCATION_NOTE); + assertThat(result.getConflictReport()).contains(TRUNCATION_NOTE); } else { - assertThat(result.getDetails()).doesNotContain(TRUNCATION_NOTE); + assertThat(result.getConflictReport()).doesNotContain(TRUNCATION_NOTE); } } @@ -267,9 +266,9 @@ class DefaultSolutionServiceTest { profile.setName("Sensor profile"); when(deviceProfileService.findDeviceProfileByName(tenantId, "Sensor profile")).thenReturn(profile); - SolutionInstallResponse result = service.validateSolution(tenantId, tempDir); + SolutionValidationResult result = service.validateSolution(tenantId, tempDir); - assertThat(result.getDetails().lines().toList()).contains("- **Device profile**: 'Sensor profile'"); + assertThat(result.getConflictReport().lines().toList()).contains("- **Device profile**: 'Sensor profile'"); verify(deviceProfileService, times(1)).findDeviceProfileByName(tenantId, "Sensor profile"); } @@ -278,12 +277,12 @@ class DefaultSolutionServiceTest { writeEntitiesFile("devices.json", "[{\"name\": \"New device\"}]"); when(deviceService.findDeviceByTenantIdAndName(tenantId, "New device")).thenReturn(null); - assertThat(service.validateSolution(tenantId, tempDir)).isNull(); + assertThat(service.validateSolution(tenantId, tempDir).isPassed()).isTrue(); } @Test void testValidateSolutionWithoutEntityFiles() { - assertThat(service.validateSolution(tenantId, tempDir)).isNull(); + assertThat(service.validateSolution(tenantId, tempDir).isPassed()).isTrue(); verifyNoInteractions(customerService, deviceService, assetService, dashboardService, ruleChainService, deviceProfileService, assetProfileService, edgeService); } From 63387b45b0f61a2b49a91582c44e0ac51ef12f51 Mon Sep 17 00:00:00 2001 From: dpinkevych Date: Fri, 11 Sep 2026 10:54:57 +0300 Subject: [PATCH 030/159] use the SPDX license header on the new file The base branch switched every header to the SPDX form while this branch was open, so the one file this branch adds was the only one left with the old block comment. --- .../data/SolutionValidationResult.java | 17 ++--------------- 1 file changed, 2 insertions(+), 15 deletions(-) diff --git a/application/src/main/java/org/thingsboard/server/service/solutions/data/SolutionValidationResult.java b/application/src/main/java/org/thingsboard/server/service/solutions/data/SolutionValidationResult.java index 407290e487..4b6b07c54b 100644 --- a/application/src/main/java/org/thingsboard/server/service/solutions/data/SolutionValidationResult.java +++ b/application/src/main/java/org/thingsboard/server/service/solutions/data/SolutionValidationResult.java @@ -1,18 +1,5 @@ -/** - * Copyright © 2016-2026 The Thingsboard Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ +// SPDX-FileCopyrightText: Copyright The Thingsboard Authors +// SPDX-License-Identifier: Apache-2.0 package org.thingsboard.server.service.solutions.data; import lombok.AccessLevel; From 3458fc84c31d7f0316ae9871803b0fbca9c06b47 Mon Sep 17 00:00:00 2001 From: dpinkevych Date: Fri, 11 Sep 2026 10:54:58 +0300 Subject: [PATCH 031/159] use the SPDX license header on the new file The base branch switched every header to the SPDX form while this branch was open, so the one file this branch adds was the only one left with the old block comment. --- .../data/SolutionValidationResult.java | 17 ++--------------- 1 file changed, 2 insertions(+), 15 deletions(-) diff --git a/application/src/main/java/org/thingsboard/server/service/solutions/data/SolutionValidationResult.java b/application/src/main/java/org/thingsboard/server/service/solutions/data/SolutionValidationResult.java index 407290e487..4b6b07c54b 100644 --- a/application/src/main/java/org/thingsboard/server/service/solutions/data/SolutionValidationResult.java +++ b/application/src/main/java/org/thingsboard/server/service/solutions/data/SolutionValidationResult.java @@ -1,18 +1,5 @@ -/** - * Copyright © 2016-2026 The Thingsboard Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ +// SPDX-FileCopyrightText: Copyright The Thingsboard Authors +// SPDX-License-Identifier: Apache-2.0 package org.thingsboard.server.service.solutions.data; import lombok.AccessLevel; From 04feee5c87f0bfd9e032e20fe2fa21113f5876bb Mon Sep 17 00:00:00 2001 From: dpinkevych Date: Fri, 11 Sep 2026 11:07:24 +0300 Subject: [PATCH 032/159] use the SPDX license header on the new test class The base switched every header to the SPDX form yesterday, so the files this branch adds were the only ones left with the old block comment and license:check failed on them once the base was merged in. --- .../server/service/solutions/DefaultSolutionServiceTest.java | 2 ++ 1 file changed, 2 insertions(+) diff --git a/application/src/test/java/org/thingsboard/server/service/solutions/DefaultSolutionServiceTest.java b/application/src/test/java/org/thingsboard/server/service/solutions/DefaultSolutionServiceTest.java index 860a6d3a0c..d34798fe14 100644 --- a/application/src/test/java/org/thingsboard/server/service/solutions/DefaultSolutionServiceTest.java +++ b/application/src/test/java/org/thingsboard/server/service/solutions/DefaultSolutionServiceTest.java @@ -1,3 +1,5 @@ +// SPDX-FileCopyrightText: Copyright The Thingsboard Authors +// SPDX-License-Identifier: Apache-2.0 /** * Copyright © 2016-2026 The Thingsboard Authors * From ebc5879a3b16c75e36ed1369c2f3f88efc69da86 Mon Sep 17 00:00:00 2001 From: dpinkevych Date: Fri, 11 Sep 2026 11:09:42 +0300 Subject: [PATCH 033/159] use the SPDX license header on the new test class The base switched every header to the SPDX form yesterday, so the files this branch adds were the only ones left with the old block comment and license:check failed on them once the base was merged in. --- .../server/service/solutions/DefaultSolutionServiceTest.java | 2 ++ 1 file changed, 2 insertions(+) diff --git a/application/src/test/java/org/thingsboard/server/service/solutions/DefaultSolutionServiceTest.java b/application/src/test/java/org/thingsboard/server/service/solutions/DefaultSolutionServiceTest.java index 860a6d3a0c..d34798fe14 100644 --- a/application/src/test/java/org/thingsboard/server/service/solutions/DefaultSolutionServiceTest.java +++ b/application/src/test/java/org/thingsboard/server/service/solutions/DefaultSolutionServiceTest.java @@ -1,3 +1,5 @@ +// SPDX-FileCopyrightText: Copyright The Thingsboard Authors +// SPDX-License-Identifier: Apache-2.0 /** * Copyright © 2016-2026 The Thingsboard Authors * From d6b69e41aedc7707398e39a2027e9700ae40be1d Mon Sep 17 00:00:00 2001 From: dpinkevych Date: Fri, 11 Sep 2026 11:11:42 +0300 Subject: [PATCH 034/159] drop the old license block left under the SPDX header license:format prepends the header it expects without recognising the block comment the files were created with, so both new files carried the license twice. They now have only the two SPDX lines, the same as every other file that this repository shares with CE. --- .../solutions/DefaultSolutionServiceTest.java | 15 --------------- 1 file changed, 15 deletions(-) diff --git a/application/src/test/java/org/thingsboard/server/service/solutions/DefaultSolutionServiceTest.java b/application/src/test/java/org/thingsboard/server/service/solutions/DefaultSolutionServiceTest.java index d34798fe14..d65868a7fb 100644 --- a/application/src/test/java/org/thingsboard/server/service/solutions/DefaultSolutionServiceTest.java +++ b/application/src/test/java/org/thingsboard/server/service/solutions/DefaultSolutionServiceTest.java @@ -1,20 +1,5 @@ // SPDX-FileCopyrightText: Copyright The Thingsboard Authors // SPDX-License-Identifier: Apache-2.0 -/** - * Copyright © 2016-2026 The Thingsboard Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ package org.thingsboard.server.service.solutions; import org.junit.jupiter.api.Test; From 5887f01bb362c104db086c5983a3ad5e72141b87 Mon Sep 17 00:00:00 2001 From: dpinkevych Date: Fri, 11 Sep 2026 11:12:39 +0300 Subject: [PATCH 035/159] drop the old license block left under the SPDX header license:format prepends the header it expects without recognising the block comment the files were created with, so both new files carried the license twice. They now have only the two SPDX lines, the same as every other file that this repository shares with CE. --- .../solutions/DefaultSolutionServiceTest.java | 15 --------------- 1 file changed, 15 deletions(-) diff --git a/application/src/test/java/org/thingsboard/server/service/solutions/DefaultSolutionServiceTest.java b/application/src/test/java/org/thingsboard/server/service/solutions/DefaultSolutionServiceTest.java index d34798fe14..d65868a7fb 100644 --- a/application/src/test/java/org/thingsboard/server/service/solutions/DefaultSolutionServiceTest.java +++ b/application/src/test/java/org/thingsboard/server/service/solutions/DefaultSolutionServiceTest.java @@ -1,20 +1,5 @@ // SPDX-FileCopyrightText: Copyright The Thingsboard Authors // SPDX-License-Identifier: Apache-2.0 -/** - * Copyright © 2016-2026 The Thingsboard Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ package org.thingsboard.server.service.solutions; import org.junit.jupiter.api.Test; From fcaeec8c2cd9fc9dc7c09e55b47f89ecb9ee8c26 Mon Sep 17 00:00:00 2001 From: nickAS21 Date: Sun, 13 Sep 2026 20:27:55 +0300 Subject: [PATCH 036/159] lwm2m: fix bootstrap-short-server-id = null - comments 1 --- application/src/main/resources/thingsboard.yml | 2 +- .../lwm2m/bootstrap/secure/LwM2MBootstrapConfig.java | 5 ++++- .../dao/service/validator/DeviceProfileDataValidator.java | 8 +------- transport/lwm2m/src/main/resources/tb-lwm2m-transport.yml | 2 +- 4 files changed, 7 insertions(+), 10 deletions(-) diff --git a/application/src/main/resources/thingsboard.yml b/application/src/main/resources/thingsboard.yml index 77369c73e2..c83672ee60 100644 --- a/application/src/main/resources/thingsboard.yml +++ b/application/src/main/resources/thingsboard.yml @@ -1344,7 +1344,7 @@ transport: bootstrap: # Enable/disable Bootstrap Server enabled: "${LWM2M_ENABLED_BS:true}" - # Short Server ID for Bootstrap Server is not applicable according to OMA LwM2M spec (Object 0 Resource 10 must be omitted/null for Bootstrap Server). + # Short Server ID for Bootstrap Server is not applicable according to OMA LwM2M spec (Object 0 Resource 10 must be omitted/null); left empty by default, and any provided value is normalized to null by the validator upon save. id: "${LWM2M_SERVER_ID_BS:}" # LwM2M bootstrap server bind address. Bind to all interfaces by default bind_address: "${LWM2M_BS_BIND_ADDRESS:0.0.0.0}" diff --git a/common/transport/lwm2m/src/main/java/org/thingsboard/server/transport/lwm2m/bootstrap/secure/LwM2MBootstrapConfig.java b/common/transport/lwm2m/src/main/java/org/thingsboard/server/transport/lwm2m/bootstrap/secure/LwM2MBootstrapConfig.java index 1308e23a13..59d8120554 100644 --- a/common/transport/lwm2m/src/main/java/org/thingsboard/server/transport/lwm2m/bootstrap/secure/LwM2MBootstrapConfig.java +++ b/common/transport/lwm2m/src/main/java/org/thingsboard/server/transport/lwm2m/bootstrap/secure/LwM2MBootstrapConfig.java @@ -51,7 +51,7 @@ public class LwM2MBootstrapConfig implements Serializable { * clientSecretKey?: string, * serverPublicKey?: string; * clientHoldOffTime?: number, - * serverId?: number, + * shortServerId?: number for DM server; null for BS server, * bootstrapServerAccountTimeout: number * */ @Getter @@ -127,6 +127,9 @@ public class LwM2MBootstrapConfig implements Serializable { private BootstrapConfig.ServerConfig setServerConfig (AbstractLwM2MBootstrapServerCredential serverCredential) { BootstrapConfig.ServerConfig serverConfig = new BootstrapConfig.ServerConfig(); + if (!serverCredential.isBootstrapServerIs()) { + serverConfig.shortId = serverCredential.getShortServerId(); + } serverConfig.lifetime = serverCredential.getLifetime(); serverConfig.defaultMinPeriod = serverCredential.getDefaultMinPeriod(); serverConfig.notifIfDisabled = serverCredential.isNotifIfDisabled(); diff --git a/dao/src/main/java/org/thingsboard/server/dao/service/validator/DeviceProfileDataValidator.java b/dao/src/main/java/org/thingsboard/server/dao/service/validator/DeviceProfileDataValidator.java index b7aff6d5db..a8d0ddcee8 100644 --- a/dao/src/main/java/org/thingsboard/server/dao/service/validator/DeviceProfileDataValidator.java +++ b/dao/src/main/java/org/thingsboard/server/dao/service/validator/DeviceProfileDataValidator.java @@ -380,14 +380,8 @@ public class DeviceProfileDataValidator extends AbstractHasOtaPackageValidator Date: Mon, 14 Sep 2026 19:05:49 +0300 Subject: [PATCH 037/159] feat(iot-hub): group the hero search popup, and give the search page filters MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Two surfaces, one defect between them: a query answered by several content types could not show all of them. **The hero popup** asked /api/versions/published for one flat page of ten rows by install count and grouped that page on the client. Ten rows cannot hold four of each of six item types, so whichever types filled the page took it and the rest had no section at all — and an absent section was indistinguishable from "no matches of this type". Measured against the catalogue, `temperature` returns 71 matches across five types; a flat top-16 by install count shows no calculated field and no alarm rule, and by relevance it shows none of the 22 devices. On `gateway` neither ordering surfaces one of the 12 matching widgets. It asks for a grouped answer now. The server caps each type and puts `typeTotal` on every row, so the client renders what it was given: one section per type, the header a link to that type page carrying the current query and, when more of that type exists, a "+N more ›" chip. Count and chevron appear together or not at all — on a section already showing everything a chevron points at nothing. The footer names where it goes rather than an ordering. **The search page** keeps its flat paginated grid — the site's equivalent is a browsable catalogue with indexed page URLs, so neither product groups there — and gains what it was missing beside the type pages: * A filter panel: item type, category, use case. Type is new, this being the one page that mixes them. There is no catalogue-wide filterInfo endpoint, so the six per-type answers are merged client-side. Counts are deliberately not rendered: filterInfo takes no text query, so beside a searched result they would be the whole catalogue's numbers describing a different answer. * A page size that follows the column count, read from a hidden probe carrying the grid's own classes rather than restated from its media queries: max(12, columns × 3). Fifteen at every width ended a page mid-row at four and six columns. * One card layout. Calculated fields, alarm rules and rule chains render as a compact horizontal row that needs a wide cell; the type pages narrow the grid for them, a mixed grid cannot, and those rows truncated their own titles. **Relevance** is a sort option on all four surfaces that carry a search field, and the default on each. With text it ranks the answer; without it the backend substitutes the install count, so browsing keeps the order it had. Nothing switches on the field state — a control that relabels itself unasked was tried and rejected. Also here: the search page moves onto the type pages' frame — one even padding on the card, the component full bleed — which removes four breakpoints' worth of negative margins, each written to cancel that padding for one element. --- .../dashboard-widget-select.component.ts | 12 + .../iot-hub/iot-hub-browse.component.ts | 16 ++ .../iot-hub/iot-hub-components.module.ts | 3 + .../iot-hub/iot-hub-facet-list.component.html | 31 ++ .../iot-hub/iot-hub-facet-list.component.scss | 92 ++++++ .../iot-hub/iot-hub-facet-list.component.ts | 83 ++++++ .../iot-hub/iot-hub-item-card.component.html | 4 +- .../iot-hub/iot-hub-item-card.component.ts | 13 + .../iot-hub/iot-hub-search.component.html | 120 +++++--- .../iot-hub/iot-hub-search.component.scss | 190 +++++++++--- .../iot-hub/iot-hub-search.component.ts | 270 ++++++++++++++---- .../iot-hub-creator-profile.component.html | 5 +- .../pages/iot-hub/iot-hub-home.component.html | 67 +++-- .../pages/iot-hub/iot-hub-home.component.scss | 35 +++ .../pages/iot-hub/iot-hub-home.component.ts | 46 ++- .../iot-hub-search-page.component.scss | 101 ++----- .../models/iot-hub/iot-hub-version.models.ts | 27 ++ .../assets/locale/locale.constant-en_US.json | 4 + 18 files changed, 884 insertions(+), 235 deletions(-) create mode 100644 ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-facet-list.component.html create mode 100644 ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-facet-list.component.scss create mode 100644 ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-facet-list.component.ts diff --git a/ui-ngx/src/app/modules/home/components/dashboard-page/dashboard-widget-select.component.ts b/ui-ngx/src/app/modules/home/components/dashboard-page/dashboard-widget-select.component.ts index d93a1e504e..57c621eb8d 100644 --- a/ui-ngx/src/app/modules/home/components/dashboard-page/dashboard-widget-select.component.ts +++ b/ui-ngx/src/app/modules/home/components/dashboard-page/dashboard-widget-select.component.ts @@ -88,7 +88,19 @@ export class DashboardWidgetSelectComponent { includeDeprecated = false; searchFocused = false; + /** + * Relevance leads, and is therefore the default (iotHubSelectedSortIndex starts at 0). This + * panel has a search field, which is the only thing relevance ranks by; with the field empty + * the backend substitutes the install count, so the picker opens on the order it always had. + * + * scadaFirst is unaffected: the backend prepends it ahead of the caller's sort AND ahead of + * relevance, so a SCADA context still lists SCADA widgets first. + * + * Fourth copy of this list — the others are in TbIotHubSearchComponent, TbIotHubBrowseComponent + * and IOT_HUB_SORT_OPTIONS on thingsboard.io. Kept in step by hand. + */ iotHubSortOptions: WidgetSelectSortOption[] = [ + { value: 'relevance', label: 'iot-hub.sort-most-relevant', direction: Direction.DESC }, { value: 'totalInstallCount', label: 'iot-hub.sort-most-installed', direction: Direction.DESC }, { value: 'publishedTime', label: 'iot-hub.sort-newest', direction: Direction.DESC }, { value: 'name', label: 'iot-hub.sort-name', direction: Direction.ASC } diff --git a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-browse.component.ts b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-browse.component.ts index 11352f1d04..785bd48660 100644 --- a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-browse.component.ts +++ b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-browse.component.ts @@ -126,7 +126,17 @@ export class TbIotHubBrowseComponent implements OnInit, AfterViewInit, OnDestroy activeHardwareTypes = new Set(); activeVendors = new Set(); + /** + * Relevance leads, and is therefore the default (selectedSortIndex starts at 0). A type page + * carries a search field, which is the only thing relevance ranks by; with the field empty the + * backend substitutes the install count, so browsing keeps the order it always had. + * + * Kept in step by hand with TbIotHubSearchComponent's list and with IOT_HUB_SORT_OPTIONS on + * thingsboard.io — three copies, because the two products share no code and this component + * predates the search page's list. + */ sortOptions: SortOption[] = [ + { value: 'relevance', label: 'iot-hub.sort-most-relevant', direction: Direction.DESC }, { value: 'totalInstallCount', label: 'iot-hub.sort-most-installed', direction: Direction.DESC }, { value: 'publishedTime', label: 'iot-hub.sort-newest', direction: Direction.DESC }, { value: 'name', label: 'iot-hub.sort-name', direction: Direction.ASC } @@ -176,6 +186,12 @@ export class TbIotHubBrowseComponent implements OnInit, AfterViewInit, OnDestroy if (params['search']) { this.textSearch = params['search']; } + // A search section header on a creator profile lands here scoped to that creator. The + // bound input wins: an embedded host (the add-item dialog) sets its own scope, and must + // not pick one up from whatever URL happens to be open behind the dialog. + if (!this.creatorId && !this.embedded && params['creatorId']) { + this.creatorId = params['creatorId']; + } if (this.fixedSubType) { const subtypes = this.getActiveSubtypes(); if (subtypes) { diff --git a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-components.module.ts b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-components.module.ts index 53e2493651..00ce18b4c0 100644 --- a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-components.module.ts +++ b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-components.module.ts @@ -14,6 +14,7 @@ import { TbIotHubUnpublishedWarningDialogComponent } from './iot-hub-unpublished import { TbDeviceInstallDialogComponent } from './device-install-dialog/device-install-dialog.component'; import { InstallFormRendererComponent } from './device-install-dialog/install-form-renderer/install-form-renderer.component'; import { TbIotHubSearchComponent } from './iot-hub-search.component'; +import { TbIotHubFacetListComponent } from './iot-hub-facet-list.component'; import { TbIotHubInstalledItemsTableComponent } from './iot-hub-installed-items-table.component'; import { TbIotHubInstalledItemsDialogComponent } from './iot-hub-installed-items-dialog.component'; import { TbPeConnectivityMethodPromptComponent } from './pe-connectivity-method-prompt.component'; @@ -36,6 +37,7 @@ import { IotHubItemLinkModule } from './iot-hub-item-link-card/iot-hub-item-link TbIotHubUnpublishedWarningDialogComponent, TbDeviceInstallDialogComponent, TbIotHubSearchComponent, + TbIotHubFacetListComponent, TbIotHubInstalledItemsTableComponent, TbIotHubInstalledItemsDialogComponent, TbPeConnectivityMethodPromptComponent, @@ -64,6 +66,7 @@ import { IotHubItemLinkModule } from './iot-hub-item-link-card/iot-hub-item-link TbIotHubUnpublishedWarningDialogComponent, TbDeviceInstallDialogComponent, TbIotHubSearchComponent, + TbIotHubFacetListComponent, TbIotHubInstalledItemsTableComponent, TbIotHubInstalledItemsDialogComponent, TbPeConnectivityMethodPromptComponent, diff --git a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-facet-list.component.html b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-facet-list.component.html new file mode 100644 index 0000000000..dfde943c22 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-facet-list.component.html @@ -0,0 +1,31 @@ + + + + {{ label | translate }} + + + @if (searchable) { +

+ } + +
+ @for (option of visibleOptions; track trackByKey($index, option)) { + + {{ labelFor(option.key) }} + + } +
+ diff --git a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-facet-list.component.scss b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-facet-list.component.scss new file mode 100644 index 0000000000..e5fc43f803 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-facet-list.component.scss @@ -0,0 +1,92 @@ +// SPDX-FileCopyrightText: Copyright The Thingsboard Authors +// SPDX-License-Identifier: Apache-2.0 +@import "./iot-hub-common"; + +// Values follow the type pages' filter panel so the two read as one control, minus its deep +// left indent: that indent exists because the panel there sits in a wider rail. +.tb-iot-hub-facet-panel.mat-expansion-panel { + box-shadow: none; + border-radius: 0; + background: transparent; + + // Indented from the column's edges, because the rules between facets are not: they span the + // whole column, as they do on the type pages. The host sets --tb-facet-indent to whatever + // puts this text on the page's own left margin. + .mat-expansion-panel-header { + padding: 8px 16px 8px var(--tb-facet-indent, 16px); + height: 48px; + min-height: 48px; + } + + ::ng-deep .mat-expansion-panel-header-title { + font-size: 14px; + font-weight: 500; + color: rgba(0, 0, 0, 0.87); + } + + ::ng-deep .mat-expansion-panel-body { + padding: 0 8px 8px var(--tb-facet-indent, 16px); + } + + mat-checkbox { + display: block; + overflow: hidden; + + &:hover { + background: rgba(0, 0, 0, 0.04); + } + } + + .tb-iot-hub-facet-items { + // Uncapped until the list is long enough to need it, so a three-option facet does not + // reserve a scroll area it never uses. + &.scrollable { + max-height: 280px; + overflow-y: auto; + } + + &::-webkit-scrollbar { + width: 6px; + } + + &::-webkit-scrollbar-track { + background-color: transparent; + } + + &::-webkit-scrollbar-thumb { + background-color: transparent; + border-radius: 3px; + } + + &:hover { + &::-webkit-scrollbar-track { + background-color: rgba(0, 0, 0, 0.04); + } + + &::-webkit-scrollbar-thumb { + background-color: rgba(0, 0, 0, 0.2); + + &:hover { + background-color: rgba(0, 0, 0, 0.35); + } + } + } + } + + .tb-iot-hub-facet-search { + @include tb-iot-hub-search-container; + margin: 4px 8px 8px 0; + + mat-icon { + @include tb-iot-hub-search-icon(rgba(0, 0, 0, 0.54)); + } + + input { + @include tb-iot-hub-search-input-text(0.2px); + } + + .tb-iot-hub-facet-search-clear.mat-mdc-icon-button { + @include tb-iot-hub-search-clear; + } + } +} diff --git a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-facet-list.component.ts b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-facet-list.component.ts new file mode 100644 index 0000000000..b9b5625fce --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-facet-list.component.ts @@ -0,0 +1,83 @@ +// SPDX-FileCopyrightText: Copyright The Thingsboard Authors +// SPDX-License-Identifier: Apache-2.0 +import { Component, EventEmitter, Input, Output } from '@angular/core'; +import { FilterParamInfo } from '@shared/models/iot-hub/iot-hub-item.models'; + +/** + * One checkbox facet of a filter panel: a title, the options with their item counts, and the + * set of keys currently selected. Presentational only - it owns no filter state and issues no + * request; the host decides what a toggle means. + * + * Written for the cross-type search page, which needs three plain facets (item type, category, + * use case). The type pages keep their own panel in TbIotHubBrowseComponent: theirs carries + * facets this one has no notion of - grouped connectivity, vendor lists, per-type subtypes - + * so folding the two together would mean parameterising that panel for a shape it never uses. + */ +@Component({ + selector: 'tb-iot-hub-facet-list', + standalone: false, + templateUrl: './iot-hub-facet-list.component.html', + styleUrls: ['./iot-hub-facet-list.component.scss'] +}) +export class TbIotHubFacetListComponent { + + /** Translation key for the facet's heading. */ + @Input() label: string; + + @Input() options: FilterParamInfo[] = []; + + /** Keys the host currently has selected. Read, never written. */ + @Input() selected = new Set(); + + /** + * Turns an option key into what the user reads. Defaults to the key, which is already the + * display value for categories and use cases; item types come through as enum names and need + * their translated plural. + */ + @Input() labelFor: (key: string) => string = (key) => key; + + /** + * Open on first render. The host decides: a short, always-relevant facet earns the space it + * takes, a long one costs the reader the facets below it — on the search page all three + * headings fit above the fold only because two of them start closed. + */ + @Input() expanded = true; + + @Output() toggled = new EventEmitter(); + + /** + * Above this many options the facet gets its own search box and a scroll cap. Matches the + * threshold the type pages' panel uses, so the two feel the same at the same list lengths. + */ + private static readonly SEARCH_THRESHOLD = 8; + + search = ''; + + get searchable(): boolean { + return this.options.length > TbIotHubFacetListComponent.SEARCH_THRESHOLD; + } + + get visibleOptions(): FilterParamInfo[] { + const needle = this.search.trim().toLowerCase(); + if (!needle) { + return this.options; + } + return this.options.filter(o => this.labelFor(o.key).toLowerCase().includes(needle)); + } + + get scrollable(): boolean { + return this.visibleOptions.length > TbIotHubFacetListComponent.SEARCH_THRESHOLD; + } + + isSelected(key: string): boolean { + return this.selected.has(key); + } + + onToggle(key: string): void { + this.toggled.emit(key); + } + + trackByKey(_index: number, option: FilterParamInfo): string { + return option.key; + } +} diff --git a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-item-card.component.html b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-item-card.component.html index cbde4bbf83..16bca59bf7 100644 --- a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-item-card.component.html +++ b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-item-card.component.html @@ -78,7 +78,9 @@ } @else {
- {{ getPlaceholderIcon() }} + + {{ getPlaceholderIcon() }}
} diff --git a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-item-card.component.ts b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-item-card.component.ts index 22a4eaf323..f57582fb29 100644 --- a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-item-card.component.ts +++ b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-item-card.component.ts @@ -23,6 +23,16 @@ export class TbIotHubItemCardComponent { @Input() showTypeChip = true; @Input() showSubtype = false; @Input() mode: 'default' | 'add' = 'default'; + /** + * `auto` lets the item's type choose, which is what a single-type grid wants: calculated + * fields, alarm rules and rule chains have nothing to preview, so they get a compact row and + * the grid gives them wider cells. + * + * `preview` forces the tall card on every type. A grid that mixes types cannot widen its + * cells for some rows only, and a horizontal row squeezed into a cell sized for a preview + * truncates its own title and leaves the rest of the cell empty. + */ + @Input() layout: 'auto' | 'preview' = 'auto'; @Output() cardClick = new EventEmitter(); @Output() creatorClick = new EventEmitter(); @Output() installClick = new EventEmitter(); @@ -47,6 +57,9 @@ export class TbIotHubItemCardComponent { } isCompactLayout(): boolean { + if (this.layout === 'preview') { + return false; + } return this.item.type === ItemType.CALCULATED_FIELD || this.item.type === ItemType.ALARM_RULE || this.item.type === ItemType.RULE_CHAIN; diff --git a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-search.component.html b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-search.component.html index c737e1e96c..5963b7c003 100644 --- a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-search.component.html +++ b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-search.component.html @@ -4,14 +4,26 @@ SPDX-License-Identifier: Apache-2.0 --> -
+
{{ 'iot-hub.results-count' | translate:{ count: totalElements } }}
- -
+ + + + +
+ @if (showFilters) { + + }
-
+
{{ 'iot-hub.results-count' | translate:{ count: totalElements } }} @@ -76,7 +88,59 @@
-
+ + +
+ @if (activeFilterCount > 0) { + + } + + + @if (categoryOptions.length > 0) { + + + + } + @if (useCaseOptions.length > 0) { + + + } +
+
+ +
+ + +
+ @if (showFilters) { + + }
@@ -100,39 +164,27 @@
} - - @if (resultGroups.length > 0) { -
- @for (group of resultGroups; track group.type) { -
- - - -
- @for (item of group.items; track item.id) { - - - } -
-
+ + @if (results.length > 0) { +
+ @for (item of results; track item.id) { + + }
}
+
@if (isLoading) { diff --git a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-search.component.scss b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-search.component.scss index 4b43ad5b3c..2556d03f3d 100644 --- a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-search.component.scss +++ b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-search.component.scss @@ -8,6 +8,14 @@ flex-direction: column; } +// The page hands this component the card's full width and its own side padding as a variable. +// Rows that are ordinary content pad themselves back in; the divider and the filter rail are +// the two things that are supposed to reach the edge, so they do not. +.tb-search-pad { + padding-left: var(--tb-search-side-pad, 0px); + padding-right: var(--tb-search-side-pad, 0px); +} + .tb-search-results-count-mobile { display: none; margin-left: auto; @@ -143,49 +151,135 @@ overflow: auto; } -// Categories / sections -.tb-search-categories { +// Card grid +.tb-search-card-grid { + display: grid; + grid-template-columns: repeat(5, 1fr); + gap: 20px; + + // Probe: zero-height element used only to read the computed column count. + // Keeps display: grid and non-zero width so grid-template-columns resolves. + &.tb-search-card-grid-probe { + width: 100%; + height: 0; + gap: 0; + overflow: hidden; + visibility: hidden; + pointer-events: none; + } +} + +// Filter button — the drawer's trigger, and where the active count is shown +.tb-search-filter-btn { + flex-shrink: 0; +} + +.tb-search-filter-count { + margin-left: 6px; + min-width: 18px; + height: 18px; + padding: 0 5px; + border-radius: 9px; + background: rgba(0, 0, 0, 0.08); + font-size: 12px; + line-height: 18px; + font-variant-numeric: tabular-nums; +} + +// Content: facet sidebar beside the grid +// The page gives this component the viewport's remaining height and expects its body to scroll +// inside, not to grow past the white card. So the row takes that height and BOTH columns scroll +// themselves — the grid as it always did, the facets likewise. A facet list can then be any +// length at all without reaching the page behind it. +.tb-search-layout { display: flex; - flex-direction: column; - gap: 48px; + gap: 24px; + height: 100%; + min-height: 0; + + .tb-results-container { + flex: 1; + min-width: 0; + // Only on the right: the gap to the rail already separates it on the left. + padding-right: var(--tb-search-side-pad, 0px); + } } -// Section header -.tb-search-section-header { - font-size: 18px; - font-weight: 500; - line-height: 24px; - color: rgba(0, 0, 0, 0.87); - padding: 0; - margin-bottom: 12px; +.tb-search-facets-desktop { + width: 232px; + flex-shrink: 0; + border-right: 1px solid rgba(0, 0, 0, 0.12); + + // The component is already full-bleed, so this column starts at the card's edge with no + // margin of its own and every rule drawn across it reaches that edge. The indent goes INSIDE + // each facet — padding here would inset the rules too — and matches the page's own margin, so + // the words line up with the heading above them. + --tb-facet-indent: var(--tb-search-side-pad, 16px); + + align-self: stretch; + height: 100%; + overflow-y: auto; + padding-top: 20px; + + &::-webkit-scrollbar { + width: 6px; + } + + &::-webkit-scrollbar-track { + background-color: transparent; + } + + &::-webkit-scrollbar-thumb { + background-color: transparent; + border-radius: 3px; + } + + &:hover { + &::-webkit-scrollbar-track { + background-color: rgba(0, 0, 0, 0.04); + } - mat-icon { - font-size: 24px; - width: 24px; - height: 24px; + &::-webkit-scrollbar-thumb { + background-color: rgba(0, 0, 0, 0.2); + + &:hover { + background-color: rgba(0, 0, 0, 0.35); + } + } } } -// Card grid -.tb-search-card-grid { - display: grid; - grid-template-columns: repeat(5, 1fr); - gap: 20px; +// The close button and heading belong to the narrow layout only. +.tb-search-facets-header { + display: none; + height: 48px; + font-size: 16px; + font-weight: 500; +} - &.tb-search-card-grid-compact { - grid-template-columns: repeat(3, 1fr); +.tb-search-facets { + display: flex; + flex-direction: column; + padding-bottom: 24px; + + // The type pages put a rule between filter sections. No gap and no padding around it: the + // rule sits flush between two sections, edge to edge, rather than floating inside a gap. + tb-iot-hub-facet-list + tb-iot-hub-facet-list { + border-top: 1px solid rgba(0, 0, 0, 0.12); } } +.tb-search-facets-clear { + align-self: flex-start; + margin-left: calc(var(--tb-facet-indent, 16px) - 16px); +} + // Responsive @media #{$mat-gt-xxl} { .tb-search-card-grid { grid-template-columns: repeat(6, 1fr); - &.tb-search-card-grid-compact { - grid-template-columns: repeat(4, 1fr); - } } } @@ -193,9 +287,6 @@ .tb-search-card-grid { grid-template-columns: repeat(4, 1fr); - &.tb-search-card-grid-compact { - grid-template-columns: repeat(3, 1fr); - } } } @@ -203,9 +294,6 @@ .tb-search-card-grid { grid-template-columns: repeat(3, 1fr); - &.tb-search-card-grid-compact { - grid-template-columns: repeat(2, 1fr); - } } } @@ -229,9 +317,6 @@ .tb-search-card-grid { grid-template-columns: repeat(2, 1fr); - &.tb-search-card-grid-compact { - grid-template-columns: repeat(1, 1fr); - } } } @@ -268,3 +353,38 @@ margin-left: 0; } } + +// The sidebar costs a whole card column, so below this width it stops being a column: the +// panel collapses, and the Filter button opens it as a block above the results. +@media #{$mat-lt-lg} { + .tb-search-layout { + flex-direction: column; + } + + .tb-search-facets-desktop { + display: none; + // As a block above the results it is ordinary content, not a rail, so it lines up with + // the rows above it rather than with the card's edge. + width: 100%; + height: auto; + max-height: 60vh; + border-right: none; + border-bottom: 1px solid rgba(0, 0, 0, 0.12); + padding-right: 0; + + &.opened { + display: block; + } + } + + .tb-search-facets-header { + display: flex; + } +} + +// Wide enough for the sidebar, so the button that opens the block has nothing to open. +@media #{$mat-gt-md} { + .tb-search-filter-btn { + display: none; + } +} diff --git a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-search.component.ts b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-search.component.ts index f915be77e1..6326a52010 100644 --- a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-search.component.ts +++ b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-search.component.ts @@ -1,6 +1,6 @@ // SPDX-FileCopyrightText: Copyright The Thingsboard Authors // SPDX-License-Identifier: Apache-2.0 -import { Component, OnInit, OnDestroy, Input, Output, EventEmitter } from '@angular/core'; +import { Component, OnInit, OnDestroy, Input, Output, EventEmitter, ViewChild, ElementRef } from '@angular/core'; import { Router } from '@angular/router'; import { TranslateService } from '@ngx-translate/core'; import { forkJoin, Subject, Subscription } from 'rxjs'; @@ -8,27 +8,38 @@ import { debounceTime, distinctUntilChanged } from 'rxjs/operators'; import { PageLink } from '@shared/models/page/page-link'; import { Direction, SortOrder } from '@shared/models/page/sort-order'; import { MpItemVersionQuery, MpItemVersionView } from '@shared/models/iot-hub/iot-hub-version.models'; -import { ItemType, itemTypeTranslations } from '@shared/models/iot-hub/iot-hub-item.models'; +import { FilterParamInfo, ItemType, itemTypeTranslations } from '@shared/models/iot-hub/iot-hub-item.models'; import { IotHubInstalledItem } from '@shared/models/iot-hub/iot-hub-installed-item.models'; import { IotHubApiService } from '@core/http/iot-hub-api.service'; import { IotHubActionsService } from './iot-hub-actions.service'; -interface SearchResultGroup { - type: ItemType; - items: MpItemVersionView[]; -} - interface SortOption { value: string; label: string; direction: Direction; } -const TYPE_ORDER: ItemType[] = [ +/** Sort property served by relevance ranking. With no text the backend substitutes the + * install count, so it is a safe default in both states. */ +const RELEVANCE = 'relevance'; + +/** + * Item types the Type facet offers, in the order every other cross-type surface uses (the hero + * popup's sections, the site's). Fixed rather than sorted by count: the counts move with the + * catalogue and a facet whose options reshuffle under the pointer is hard to use. + */ +const FACET_ITEM_TYPES: ItemType[] = [ ItemType.DEVICE, ItemType.SOLUTION_TEMPLATE, ItemType.WIDGET, ItemType.CALCULATED_FIELD, ItemType.ALARM_RULE, ItemType.RULE_CHAIN ]; +/** + * Rows a page holds, as a multiple of the column count, so a page always ends on a complete row. + * The floor keeps a one- or two-column phone layout from falling to three cards a page. + */ +const ROWS_PER_PAGE = 3; +const MIN_PAGE_SIZE = 12; + @Component({ selector: 'tb-iot-hub-search', standalone: false, @@ -37,32 +48,64 @@ const TYPE_ORDER: ItemType[] = [ }) export class TbIotHubSearchComponent implements OnInit, OnDestroy { - readonly ItemType = ItemType; - @Input() searchText = ''; @Input() creatorId: string; @Input() showCreator = true; + /** + * Render the filter panel. The search page does; the creator profile does not - it is already + * scoped to one creator, and the site's profile has no panel either. + */ + @Input() showFilters = true; @Output() searchTextChange = new EventEmitter(); get searchPlaceholderKey(): string { return this.creatorId ? 'iot-hub.search-published-items' : 'iot-hub.search'; } - resultGroups: SearchResultGroup[] = []; + results: MpItemVersionView[] = []; totalElements = 0; isLoading = false; hasError = false; private retryTimer: any = null; - pageSize = 15; pageIndex = 0; - pageSizeOptions = [15, 30, 60]; + + /** + * Read from a hidden probe that carries the real grid's classes, not guessed from breakpoints: + * the grid's column count is a CSS fact, and duplicating its media queries in TypeScript is a + * second source of truth that drifts the first time someone edits the stylesheet. + */ + @ViewChild('cardGridProbe', { static: true }) cardGridProbe!: ElementRef; + cols = 5; + pageSize = MIN_PAGE_SIZE; + + get pageSizeOptions(): number[] { + const base = Math.max(MIN_PAGE_SIZE, this.cols * ROWS_PER_PAGE); + return [base, base * 2, base * 4]; + } + + /** Filter panel state. Empty sets mean "no filter", which is what the query object expects. */ + /** Narrow widths only: the facet panel is a block above the results, not a sidebar. */ + filtersOpen = false; + typeOptions: FilterParamInfo[] = []; + categoryOptions: FilterParamInfo[] = []; + useCaseOptions: FilterParamInfo[] = []; + activeTypes = new Set(); + activeCategories = new Set(); + activeUseCases = new Set(); sortOptions: SortOption[] = [ + { value: RELEVANCE, label: 'iot-hub.sort-most-relevant', direction: Direction.DESC }, { value: 'totalInstallCount', label: 'iot-hub.sort-most-installed', direction: Direction.DESC }, { value: 'publishedTime', label: 'iot-hub.sort-newest', direction: Direction.DESC }, { value: 'name', label: 'iot-hub.sort-name', direction: Direction.ASC } ]; + /** + * Relevance is the default in BOTH states, which is why nothing here switches on whether the + * search field has text. With text it ranks the answer; without it the backend substitutes the + * install count, so a user who never opens this menu sees the order they always saw while + * browsing and the best matches once they type. + */ selectedSortIndex = 0; installedWidgets: IotHubInstalledItem[] = []; @@ -83,6 +126,11 @@ export class TbIotHubSearchComponent implements OnInit, OnDestroy { ) {} ngOnInit(): void { + this.measureCols(); + this.observeGridWidth(); + if (this.showFilters) { + this.loadFilterInfo(); + } this.loadInstalledItems(); this.searchSubscription = this.searchSubject.pipe( debounceTime(300), @@ -96,6 +144,148 @@ export class TbIotHubSearchComponent implements OnInit, OnDestroy { ngOnDestroy(): void { this.searchSubscription?.unsubscribe(); + this.resizeSubscription?.unsubscribe(); + this.resizeObserver?.disconnect(); + } + + // Filters + + getTypeLabel = (key: string): string => { + const translationKey = itemTypeTranslations.get(key as ItemType); + return translationKey ? this.translate.instant(translationKey + '-plural') : key; + }; + + onTypeToggle(key: string): void { + this.toggle(this.activeTypes, key); + } + + onCategoryToggle(key: string): void { + this.toggle(this.activeCategories, key); + } + + onUseCaseToggle(key: string): void { + this.toggle(this.activeUseCases, key); + } + + get activeFilterCount(): number { + return this.activeTypes.size + this.activeCategories.size + this.activeUseCases.size; + } + + clearFilters(): void { + if (this.activeFilterCount === 0) { + return; + } + this.activeTypes.clear(); + this.activeCategories.clear(); + this.activeUseCases.clear(); + this.pageIndex = 0; + this.loadResults(); + } + + private toggle(set: Set, key: string): void { + if (set.has(key)) { + set.delete(key); + } else { + set.add(key); + } + this.pageIndex = 0; + this.loadResults(); + } + + /** + * There is no catalogue-wide filterInfo endpoint - it answers per item type - so the six + * answers are merged here, the way the site merges the same six at build time. Counts are + * deliberately not rendered: filterInfo takes no text query, so beside a searched result they + * would be the whole catalogue's numbers pretending to describe this answer. + */ + private loadFilterInfo(): void { + const config = { ignoreLoading: true, ignoreErrors: true }; + forkJoin( + FACET_ITEM_TYPES.map(type => this.iotHubApiService.getFilterInfo(type, config)) + ).subscribe({ + next: infos => { + // Every item type is offered, not only the ones filterInfo reports facets for: the + // endpoint describes a type's categories and vendors, never how many items it has, and + // a type whose items carry no categories would vanish from its own facet. + this.typeOptions = FACET_ITEM_TYPES.map(type => ({ + key: type as string, + totalItems: 0, + totalInstallCount: 0 + })); + this.categoryOptions = this.mergeFacet(infos.map(i => i?.categories)); + this.useCaseOptions = this.mergeFacet(infos.map(i => i?.useCases)); + }, + // A facet panel that failed to load is an empty panel, never a broken page: the grid + // beside it answers the query perfectly well without it. + error: () => {} + }); + } + + private mergeFacet(lists: (FilterParamInfo[] | undefined)[]): FilterParamInfo[] { + const byKey = new Map(); + for (const list of lists) { + for (const option of list || []) { + const seen = byKey.get(option.key); + if (seen) { + seen.totalItems += option.totalItems; + seen.totalInstallCount += option.totalInstallCount; + } else { + byKey.set(option.key, { ...option }); + } + } + } + return [...byKey.values()] + .filter(o => o.totalItems > 0) + .sort((a, b) => a.key.localeCompare(b.key)); + } + + // Column count -> page size + + private resizeObserver?: ResizeObserver; + private resizeSubject = new Subject(); + private resizeSubscription?: Subscription; + + private observeGridWidth(): void { + const el = this.cardGridProbe?.nativeElement; + if (!el || typeof ResizeObserver === 'undefined') { + return; + } + this.resizeSubscription = this.resizeSubject.pipe(debounceTime(150)).subscribe(() => { + const before = this.pageSizeOptions[0]; + this.measureCols(); + if (this.pageSizeOptions[0] === before) { + return; + } + // Keep the user roughly where they were in the list rather than on the same page number: + // page 4 of 12-card pages is a different place from page 4 of 18-card pages. + const firstItem = this.pageIndex * this.pageSize; + this.pageSize = this.pageSizeOptions[0]; + this.pageIndex = Math.floor(firstItem / this.pageSize); + this.loadResults(); + }); + this.resizeObserver = new ResizeObserver(() => this.resizeSubject.next()); + this.resizeObserver.observe(el); + } + + private measureCols(): void { + const el = this.cardGridProbe?.nativeElement; + if (!el) { + return; + } + // Force layout so grid-template-columns resolves to pixel tracks rather than `repeat(...)`. + void el.offsetWidth; + const tracks = getComputedStyle(el).gridTemplateColumns; + if (!tracks || tracks === 'none') { + this.cols = 1; + } else if (tracks.startsWith('repeat(')) { + const match = tracks.match(/^repeat\(\s*(\d+)\s*,/); + this.cols = match ? parseInt(match[1], 10) : 1; + } else { + this.cols = Math.max(1, tracks.trim().split(/\s+/).filter(t => t.length > 0).length); + } + if (!this.pageSizeOptions.includes(this.pageSize)) { + this.pageSize = this.pageSizeOptions[0]; + } } onSearchInput(): void { @@ -159,33 +349,9 @@ export class TbIotHubSearchComponent implements OnInit, OnDestroy { } // Type helpers - isCompactType(type: ItemType): boolean { - return type === ItemType.CALCULATED_FIELD - || type === ItemType.ALARM_RULE - || type === ItemType.RULE_CHAIN; - } - - getTypeLabel(type: ItemType): string { - const key = itemTypeTranslations.get(type); - return key ? this.translate.instant(key + '-plural') : type; - } - - getTypeRoute(type: ItemType): string { - switch (type) { - case ItemType.WIDGET: return 'widgets'; - case ItemType.SOLUTION_TEMPLATE: return 'solution-templates'; - case ItemType.CALCULATED_FIELD: return 'calculated-fields'; - case ItemType.ALARM_RULE: return 'alarm-rules'; - case ItemType.RULE_CHAIN: return 'rule-chains'; - case ItemType.DEVICE: return 'devices'; - default: return 'widgets'; - } - } - navigateToType(type: ItemType): void { - const search = this.searchText?.trim() || undefined; - void this.router.navigate(['/iot-hub', this.getTypeRoute(type)], { queryParams: { search } }); - } + + // Installed items getInstalledItem(item: MpItemVersionView): IotHubInstalledItem | undefined { @@ -281,7 +447,7 @@ export class TbIotHubSearchComponent implements OnInit, OnDestroy { error: () => { this.isLoading = false; this.hasError = true; - this.resultGroups = []; + this.results = []; this.totalElements = 0; } }); @@ -291,30 +457,22 @@ export class TbIotHubSearchComponent implements OnInit, OnDestroy { const sort = this.sortOptions[this.selectedSortIndex]; const sortOrder: SortOrder = { property: sort.value, direction: sort.direction }; const pageLink = new PageLink(this.pageSize, this.pageIndex, text.trim() || null, sortOrder); - const query = new MpItemVersionQuery(pageLink, { creatorId: this.creatorId || undefined }); + const query = new MpItemVersionQuery(pageLink, { + creatorId: this.creatorId || undefined, + // Empty sets are left off the query entirely - an empty array would narrow to nothing. + types: this.activeTypes.size ? [...this.activeTypes] : undefined, + categories: this.activeCategories.size ? [...this.activeCategories] : undefined, + useCases: this.activeUseCases.size ? [...this.activeUseCases] : undefined + }); return this.iotHubApiService.getPublishedVersions(query, { ignoreLoading: true, ignoreErrors: true }); } private applyResults(data: MpItemVersionView[], totalElements: number): void { this.totalElements = totalElements; - this.resultGroups = this.groupResults(data); + this.results = data; this.isLoading = false; } - private groupResults(items: MpItemVersionView[]): SearchResultGroup[] { - const groupMap = new Map(); - for (const item of items) { - let list = groupMap.get(item.type); - if (!list) { - list = []; - groupMap.set(item.type, list); - } - list.push(item); - } - return TYPE_ORDER - .filter(type => groupMap.has(type)) - .map(type => ({ type, items: groupMap.get(type) })); - } private loadInstalledItems(): void { const config = { ignoreLoading: true }; diff --git a/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-creator-profile.component.html b/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-creator-profile.component.html index d91164a6c3..51d834e8ed 100644 --- a/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-creator-profile.component.html +++ b/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-creator-profile.component.html @@ -96,7 +96,10 @@
- + +

{{ 'iot-hub.published-items' | translate }} ({{ creator.publishedCount }})

diff --git a/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-home.component.html b/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-home.component.html index cf4007b511..995ee4395d 100644 --- a/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-home.component.html +++ b/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-home.component.html @@ -85,37 +85,54 @@ } @else { @for (group of searchResultGroups; track group.type) { - - @for (item of group.items; track item.id) { - - @if (isCompactType(item.type)) { -
- {{ getCompactIcon(item) }} + + + {{ getSearchGroupLabel(group.type) }} + @if (group.remaining > 0) { + + {{ 'iot-hub.section-more' | translate:{ count: group.remaining } }} + chevron_right + + } + + + @for (item of group.items; track item.id) { + + @if (isCompactType(item.type)) { +
+ {{ getCompactIcon(item) }} +
+ } @else { +
+ @if (getItemImage(item); as imgUrl) { + + } @else { + {{ getItemTypeIcon(item.type) }} + } +
+ } +
+ {{ item.name }} + + person + {{ item.creatorDisplayName }} +
- } @else { -
- @if (getItemImage(item); as imgUrl) { - - } @else { - {{ getItemTypeIcon(item.type) }} - } -
- } -
- {{ item.name }} - - person - {{ item.creatorDisplayName }} - -
-
- } + + } +
} }
diff --git a/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-home.component.scss b/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-home.component.scss index de032d8f1a..d8934e82ff 100644 --- a/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-home.component.scss +++ b/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-home.component.scss @@ -242,6 +242,41 @@ line-height: 20px; letter-spacing: 0.25px; color: rgba(0, 0, 0, 0.54); + // The header spans the panel so the count can sit against the right edge. Material's own + // label span is only as wide as its text. + width: 100%; + } + } + + // Section header — the label IS the link into the type page: title left, how much is not shown + // plus a chevron right. There is deliberately no per-section "see all" row under the items; + // six of those on one panel is what this variant was chosen to avoid. + .tb-search-popup-group-header { + display: flex; + align-items: center; + justify-content: space-between; + gap: 16px; + width: 100%; + cursor: pointer; + outline: none; + } + + .tb-search-popup-group-more { + display: flex; + align-items: center; + gap: 2px; + flex-shrink: 0; + font-size: 12px; + font-weight: 500; + line-height: 16px; + letter-spacing: 0.25px; + color: $tb-primary-color; + + .mat-icon { + width: 18px; + height: 18px; + font-size: 18px; + line-height: 18px; } } diff --git a/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-home.component.ts b/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-home.component.ts index fffd19c021..b4ecd8ca98 100644 --- a/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-home.component.ts +++ b/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-home.component.ts @@ -35,6 +35,10 @@ interface HeroTypeConfig { interface SearchResultGroup { type: ItemType; items: MpItemVersionView[]; + /** Rows of this type behind the answer, from the response's typeTotal. */ + total: number; + /** total - items.length, floored at 0. Zero means the header shows no "+N more". */ + remaining: number; } const SEARCH_GROUP_ORDER: ItemType[] = [ @@ -42,6 +46,11 @@ const SEARCH_GROUP_ORDER: ItemType[] = [ ItemType.CALCULATED_FIELD, ItemType.ALARM_RULE, ItemType.RULE_CHAIN ]; +/** Relevance ranking. Sent only while the field has text: with an empty field the backend + * substitutes the install count anyway, and this component knows the field state, so it sends + * the honest value rather than leaning on that safety net. */ +const RELEVANCE = 'relevance'; + @Component({ selector: 'tb-iot-hub-home', standalone: false, @@ -156,9 +165,16 @@ export class TbIotHubHomeComponent implements OnInit, OnDestroy { distinctUntilChanged(), switchMap(text => { this.searchLoading = true; - const sortOrder: SortOrder = { property: 'totalInstallCount', direction: Direction.DESC }; - const pageLink = new PageLink(10, 0, text.trim() || null, sortOrder); - const query = new MpItemVersionQuery(pageLink); + const trimmed = text.trim(); + // Two states, one panel: popularity answers "what is worth looking at" with an empty + // field, relevance answers "what did I ask for" once there is one. + const sortOrder: SortOrder = trimmed + ? { property: RELEVANCE, direction: Direction.DESC } + : { property: 'totalInstallCount', direction: Direction.DESC }; + // The server sizes a grouped answer itself - the top rows of every type, one screen - so + // this page size is ignored, and page must stay 0 (a non-zero page is a 400). + const pageLink = new PageLink(10, 0, trimmed || null, sortOrder); + const query = new MpItemVersionQuery(pageLink, { grouped: true }); return this.iotHubApiService.getPublishedVersions(query, { ignoreLoading: true }); }) ).subscribe(result => { @@ -237,6 +253,17 @@ export class TbIotHubHomeComponent implements OnInit, OnDestroy { void this.router.navigate(['/iot-hub/search'], { queryParams: { search } }); } + /** + * The section header is the way into the rest of a type - the panel carries no per-section + * "see all" row, which would put six identical calls to action on one panel. The query goes + * with it, so the type page opens on the same search rather than on the whole type. + */ + navigateToSection(type: ItemType): void { + this.searchAutoTrigger?.closePanel(); + const search = this.searchText?.trim() || undefined; + void this.router.navigate(['/iot-hub', this.getTypeRoute(type)], { queryParams: { search } }); + } + isCompactType(type: ItemType): boolean { return type === ItemType.CALCULATED_FIELD || type === ItemType.ALARM_RULE @@ -523,6 +550,11 @@ export class TbIotHubHomeComponent implements OnInit, OnDestroy { }); } + /** + * Reads the sections the server built. It no longer decides membership - a grouped response + * arrives already capped at four per type - so all this does is put the types in the panel's + * fixed order and carry each one's typeTotal onto the header. + */ private groupSearchResults(items: MpItemVersionView[]): SearchResultGroup[] { const groupMap = new Map(); for (const item of items) { @@ -538,6 +570,12 @@ export class TbIotHubHomeComponent implements OnInit, OnDestroy { } return SEARCH_GROUP_ORDER .filter(type => groupMap.has(type)) - .map(type => ({ type, items: groupMap.get(type) })); + .map(type => { + const groupItems = groupMap.get(type); + // Every row of a type carries the same typeTotal. The fallback keeps a non-grouped + // response rendering correctly - which is what a stale backend would send. + const total = groupItems[0].typeTotal ?? groupItems.length; + return { type, items: groupItems, total, remaining: Math.max(0, total - groupItems.length) }; + }); } } diff --git a/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-search-page.component.scss b/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-search-page.component.scss index 1e617fb1f3..b824aade8c 100644 --- a/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-search-page.component.scss +++ b/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-search-page.component.scss @@ -8,12 +8,18 @@ height: 100%; } +// Same frame as the type pages (iot-hub-items-page): one even padding on the card, the hero +// inside it, and the component below pulled out to the card's edges. It replaces four +// breakpoints' worth of hand-written negative margins — one per element that needed to reach +// an edge — and is why the filter rail, the heading and the grid now line up by construction. +.tb-search-page { + padding: 40px 40px 48px; +} // Back button .tb-search-back-btn { align-self: flex-start; - margin-top: 40px; - margin-left: 123px; + margin-left: -8px; } // Title @@ -30,100 +36,37 @@ color: rgba(0, 0, 0, 0.54); } +// Full bleed, and it pads its own rows back in through --tb-search-side-pad. The rail and the +// dividers are the parts that must reach the edge; everything else lines up with the hero. tb-iot-hub-search { flex: 1; min-height: 0; - padding-left: 123px; - padding-right: 123px; - - ::ng-deep { - .tb-search-divider { - margin-left: -123px; - margin-right: -123px; - } - - .tb-results-container { - padding-right: 123px; - padding-bottom: 40px; - margin-right: -123px; - } - } -} - -// Responsive -@media #{$mat-lt-xxl} { - .tb-search-back-btn { - margin-left: 40px; - } - - tb-iot-hub-search { - padding-left: 40px; - padding-right: 40px; - - ::ng-deep { - .tb-search-divider { - margin-left: -40px; - margin-right: -40px; - } - - .tb-results-container { - padding-right: 40px; - margin-right: -40px; - } - } - } + --tb-search-side-pad: 40px; + margin-left: -40px; + margin-right: -40px; } @media #{$mat-lt-lg} { - .tb-search-back-btn { - margin-top: 24px; - margin-left: 24px; + .tb-search-page { + padding: 24px 24px 32px; } tb-iot-hub-search { - padding-left: 24px; - padding-right: 24px; - - ::ng-deep { - .tb-search-divider { - margin-left: -24px; - margin-right: -24px; - } - - .tb-results-container { - padding-right: 24px; - padding-bottom: 24px; - margin-right: -24px; - } - } + --tb-search-side-pad: 24px; + margin-left: -24px; + margin-right: -24px; } } @media #{$mat-lt-sm} { .tb-search-page { + padding: 16px 16px 24px; gap: 16px; } - .tb-search-back-btn { - margin-top: 16px; - margin-left: 16px; - } - tb-iot-hub-search { - padding-left: 16px; - padding-right: 16px; - - ::ng-deep { - .tb-search-divider { - margin-left: -16px; - margin-right: -16px; - } - - .tb-results-container { - padding-right: 16px; - padding-bottom: 16px; - margin-right: -16px; - } - } + --tb-search-side-pad: 16px; + margin-left: -16px; + margin-right: -16px; } } diff --git a/ui-ngx/src/app/shared/models/iot-hub/iot-hub-version.models.ts b/ui-ngx/src/app/shared/models/iot-hub/iot-hub-version.models.ts index 349a4f62e8..b98fc30952 100644 --- a/ui-ngx/src/app/shared/models/iot-hub/iot-hub-version.models.ts +++ b/ui-ngx/src/app/shared/models/iot-hub/iot-hub-version.models.ts @@ -106,6 +106,12 @@ export interface MpItemVersionView { resources: MpItemVersionResource[]; relatedItems?: string[]; checksum?: string; + /** + * Rows of this item's type behind a grouped response. A flat read does not omit it — the + * column is projected as NULL and serialised, so the field arrives as `null` there. Read it + * with `??`, never with a truthiness test. + */ + typeTotal?: number | null; } // 404 body shapes returned by the public listing item-version endpoint @@ -118,7 +124,15 @@ export interface ListingItemVersionNotFound { } export interface MpItemVersionQueryOptions { + /** Single item type, for a surface pinned to one (the type pages, the add-item dialog). */ type?: string; + /** + * Several item types at once, for a cross-type surface whose Type facet is multi-select. + * Emitted as a repeated `type` parameter, which is the shape the backend reads + * (`@RequestParam List type`). Kept separate from `type` rather than widening it, + * so a caller that means "exactly this type" cannot be handed an array by accident. + */ + types?: string[]; peOnly?: boolean; creatorId?: string; categories?: string[]; @@ -131,6 +145,13 @@ export interface MpItemVersionQueryOptions { connectivity?: string[]; vendors?: string[]; scadaFirst?: boolean; + /** + * Ask for the top four of each item type in one response instead of a flat page. + * Every row then carries `typeTotal`, the number of rows of its type behind the answer, + * which is what the section header's "+N more" counts. Grouped responses are one screen: + * the backend rejects a non-zero `page`. + */ + grouped?: boolean; } export class MpItemVersionQuery { @@ -142,6 +163,9 @@ export class MpItemVersionQuery { if (o.type) { query += `&type=${o.type}`; } + if (o.types?.length) { + query += o.types.map(t => `&type=${encodeURIComponent(t)}`).join(''); + } if (o.peOnly != null) { query += `&peOnly=${o.peOnly}`; } @@ -178,6 +202,9 @@ export class MpItemVersionQuery { if (o.scadaFirst != null) { query += `&scadaFirst=${o.scadaFirst}`; } + if (o.grouped != null) { + query += `&grouped=${o.grouped}`; + } return query; } } diff --git a/ui-ngx/src/assets/locale/locale.constant-en_US.json b/ui-ngx/src/assets/locale/locale.constant-en_US.json index 98f59ec8a9..e19cb64cff 100644 --- a/ui-ngx/src/assets/locale/locale.constant-en_US.json +++ b/ui-ngx/src/assets/locale/locale.constant-en_US.json @@ -3708,6 +3708,7 @@ "search": "Search...", "search-published-items": "Search published items...", "see-all-results": "See all results", + "see-results-for": "See results for \"{{ search }}\"", "no-search-results": "No results found for '{{ search }}'", "no-items-available": "No items available", "search-results": "Search results", @@ -3730,6 +3731,7 @@ "type": "Type", "items-per-page": "Items per page", "filter": "Filter", + "clear-filters": "Clear filters", "available": "Available", "items-page-desc-widgets": "Jumpstart your IoT journey with pre-configured widgets designed for your industry. Deploy proven architectures instantly and focus your energy on what matters: your unique business logic.", "items-page-desc-dashboards": "Explore dashboards to find pre-built visualization templates and interactive UI layouts you can deploy in minutes to bring your IoT data to life.", @@ -3774,9 +3776,11 @@ "search-alarm-rules": "Search alarm rules...", "search-rule-chains": "Search rule chains...", "search-devices": "Search devices...", + "sort-most-relevant": "Most relevant", "sort-most-installed": "Most installed", "sort-newest": "Newest", "sort-name": "Name (A-Z)", + "section-more": "{ count, plural, =1 {+1 more} other {+# more} }", "type-filter-label": "Type", "category": "Category", "use-case": "Use case", From 27e7aed25e064df8e512a9b8fa2290cda93ee48b Mon Sep 17 00:00:00 2001 From: nickAS21 Date: Tue, 15 Sep 2026 11:49:13 +0300 Subject: [PATCH 038/159] lwm2m: fix bootstrap-short-server-id = null - tests --- .../validator/DeviceProfileDataValidator.java | 1 - .../DeviceProfileDataValidatorTest.java | 60 +++++++++++++------ 2 files changed, 43 insertions(+), 18 deletions(-) diff --git a/dao/src/main/java/org/thingsboard/server/dao/service/validator/DeviceProfileDataValidator.java b/dao/src/main/java/org/thingsboard/server/dao/service/validator/DeviceProfileDataValidator.java index 9a6cda8a1d..bf72cf286c 100644 --- a/dao/src/main/java/org/thingsboard/server/dao/service/validator/DeviceProfileDataValidator.java +++ b/dao/src/main/java/org/thingsboard/server/dao/service/validator/DeviceProfileDataValidator.java @@ -367,7 +367,6 @@ public class DeviceProfileDataValidator extends AbstractHasOtaPackageValidator validator.validateDataImpl(tenantId, deviceProfile)) .hasMessageContaining(msgError); From bb43fffa04ab6f3d62101e260b02ad2e359910f3 Mon Sep 17 00:00:00 2001 From: dshvaika Date: Tue, 15 Sep 2026 12:45:34 +0300 Subject: [PATCH 039/159] fix(iot-hub): call the grouped versions endpoint The Hub answers a sectioned search at /api/versions/published/grouped rather than through a flag on the flat read. That endpoint takes the filters and a sort key only - it sizes its own answer - so the popup asks through its own API method and its own query string, and sends no page, page size or sort order. MpItemVersionGroupedView mirrors what comes back: the view plus typeTotal, always set, rather than the flat view with a nullable field and a comment about when it is null. MpItemVersionQueryOptions loses grouped with it. --- .../src/app/core/http/iot-hub-api.service.ts | 21 +++++++- .../pages/iot-hub/iot-hub-home.component.ts | 22 ++++----- .../models/iot-hub/iot-hub-version.models.ts | 49 +++++++++++++------ 3 files changed, 65 insertions(+), 27 deletions(-) diff --git a/ui-ngx/src/app/core/http/iot-hub-api.service.ts b/ui-ngx/src/app/core/http/iot-hub-api.service.ts index 33f19d285f..f4d87a5ce5 100644 --- a/ui-ngx/src/app/core/http/iot-hub-api.service.ts +++ b/ui-ngx/src/app/core/http/iot-hub-api.service.ts @@ -6,7 +6,7 @@ import { Store } from '@ngrx/store'; import { Observable } from 'rxjs'; import { PageData } from '@shared/models/page/page-data'; import { PageLink } from '@shared/models/page/page-link'; -import { MpItemVersionQuery, MpItemVersionView } from '@shared/models/iot-hub/iot-hub-version.models'; +import { MpItemVersionGroupedView, MpItemVersionQuery, MpItemVersionView } from '@shared/models/iot-hub/iot-hub-version.models'; import { CreatorView } from '@shared/models/iot-hub/iot-hub-creator.models'; import { IotHubInstalledItem, InstallItemVersionResult, InstallPlan, InstallPlanResult, UpdateItemVersionResult, ItemPublishedVersionInfo } from '@shared/models/iot-hub/iot-hub-installed-item.models'; import { ItemType, ItemTypeFilterInfo, WidgetCategory } from '@shared/models/iot-hub/iot-hub-item.models'; @@ -81,6 +81,25 @@ export class IotHubApiService { ); } + /** + * The sectioned answer: at most four rows of each item type, every row carrying the size of its + * section. Its own endpoint, which is why this is its own method - it takes no page, page size + * or sort direction, and sending them would be sending what the server does not read. + */ + public getPublishedVersionsGrouped(query: MpItemVersionQuery, + config?: IotHubRequestConfig): Observable> { + if (query.options.tbVersion == null) { + query.options.tbVersion = tbVersionToInt(env.tbVersion); + } + if (query.options.peOnly == null) { + query.options.peOnly = false; + } + return this.http.get>( + `${this.baseUrl}/api/versions/published/grouped${query.toGroupedQuery()}`, + { params: this.buildParams(config) } + ); + } + public getFilterInfo(itemType: ItemType, config?: IotHubRequestConfig): Observable { const url = `${this.baseUrl}/api/item-listing/filterInfo/${itemType}` + `?peOnly=false&tbVersion=${tbVersionToInt(env.tbVersion)}`; diff --git a/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-home.component.ts b/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-home.component.ts index b4ecd8ca98..cf26d52bbe 100644 --- a/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-home.component.ts +++ b/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-home.component.ts @@ -9,7 +9,7 @@ import { debounceTime, distinctUntilChanged, switchMap } from 'rxjs/operators'; import { MediaBreakpoints } from '@shared/models/constants'; import { PageLink } from '@shared/models/page/page-link'; import { Direction, SortOrder } from '@shared/models/page/sort-order'; -import { MpItemVersionQuery, MpItemVersionView } from '@shared/models/iot-hub/iot-hub-version.models'; +import { MpItemVersionGroupedView, MpItemVersionQuery, MpItemVersionView } from '@shared/models/iot-hub/iot-hub-version.models'; import { getItemTypeIcon, ItemType, itemTypeTranslations } from '@shared/models/iot-hub/iot-hub-item.models'; import { IotHubInstalledItem } from '@shared/models/iot-hub/iot-hub-installed-item.models'; import { IotHubApiService } from '@core/http/iot-hub-api.service'; @@ -34,7 +34,7 @@ interface HeroTypeConfig { interface SearchResultGroup { type: ItemType; - items: MpItemVersionView[]; + items: MpItemVersionGroupedView[]; /** Rows of this type behind the answer, from the response's typeTotal. */ total: number; /** total - items.length, floored at 0. Zero means the header shows no "+N more". */ @@ -62,7 +62,7 @@ export class TbIotHubHomeComponent implements OnInit, OnDestroy { readonly ItemType = ItemType; searchText = ''; - searchResults: MpItemVersionView[] = []; + searchResults: MpItemVersionGroupedView[] = []; searchResultGroups: SearchResultGroup[] = []; searchLoaded = false; searchLoading = false; @@ -171,11 +171,10 @@ export class TbIotHubHomeComponent implements OnInit, OnDestroy { const sortOrder: SortOrder = trimmed ? { property: RELEVANCE, direction: Direction.DESC } : { property: 'totalInstallCount', direction: Direction.DESC }; - // The server sizes a grouped answer itself - the top rows of every type, one screen - so - // this page size is ignored, and page must stay 0 (a non-zero page is a 400). + // The grouped endpoint sizes its own answer, so the page size here is never sent. const pageLink = new PageLink(10, 0, trimmed || null, sortOrder); - const query = new MpItemVersionQuery(pageLink, { grouped: true }); - return this.iotHubApiService.getPublishedVersions(query, { ignoreLoading: true }); + const query = new MpItemVersionQuery(pageLink); + return this.iotHubApiService.getPublishedVersionsGrouped(query, { ignoreLoading: true }); }) ).subscribe(result => { this.searchResults = result.data; @@ -555,8 +554,8 @@ export class TbIotHubHomeComponent implements OnInit, OnDestroy { * arrives already capped at four per type - so all this does is put the types in the panel's * fixed order and carry each one's typeTotal onto the header. */ - private groupSearchResults(items: MpItemVersionView[]): SearchResultGroup[] { - const groupMap = new Map(); + private groupSearchResults(items: MpItemVersionGroupedView[]): SearchResultGroup[] { + const groupMap = new Map(); for (const item of items) { if (!SEARCH_GROUP_ORDER.includes(item.type)) { continue; @@ -572,8 +571,9 @@ export class TbIotHubHomeComponent implements OnInit, OnDestroy { .filter(type => groupMap.has(type)) .map(type => { const groupItems = groupMap.get(type); - // Every row of a type carries the same typeTotal. The fallback keeps a non-grouped - // response rendering correctly - which is what a stale backend would send. + // Every row of a type carries the same typeTotal, so the first one answers for the + // section. The fallback covers a backend too old to have the grouped endpoint, whose + // rows arrive without it. const total = groupItems[0].typeTotal ?? groupItems.length; return { type, items: groupItems, total, remaining: Math.max(0, total - groupItems.length) }; }); diff --git a/ui-ngx/src/app/shared/models/iot-hub/iot-hub-version.models.ts b/ui-ngx/src/app/shared/models/iot-hub/iot-hub-version.models.ts index b98fc30952..4aaaeeaa62 100644 --- a/ui-ngx/src/app/shared/models/iot-hub/iot-hub-version.models.ts +++ b/ui-ngx/src/app/shared/models/iot-hub/iot-hub-version.models.ts @@ -106,12 +106,18 @@ export interface MpItemVersionView { resources: MpItemVersionResource[]; relatedItems?: string[]; checksum?: string; +} + +/** + * A row of a grouped search: the view plus the size of the section it belongs to. Its own type + * rather than a nullable field on the view, matching what the endpoint returns. + */ +export interface MpItemVersionGroupedView extends MpItemVersionView { /** - * Rows of this item's type behind a grouped response. A flat read does not omit it — the - * column is projected as NULL and serialised, so the field arrives as `null` there. Read it - * with `??`, never with a truthiness test. + * Rows of this row's item type behind the answer — what a "+N more" header subtracts the + * shown rows from. Always set: the grouped endpoint projects it for every row it returns. */ - typeTotal?: number | null; + typeTotal: number; } // 404 body shapes returned by the public listing item-version endpoint @@ -145,20 +151,36 @@ export interface MpItemVersionQueryOptions { connectivity?: string[]; vendors?: string[]; scadaFirst?: boolean; - /** - * Ask for the top four of each item type in one response instead of a flat page. - * Every row then carries `typeTotal`, the number of rows of its type behind the answer, - * which is what the section header's "+N more" counts. Grouped responses are one screen: - * the backend rejects a non-zero `page`. - */ - grouped?: boolean; } export class MpItemVersionQuery { constructor(public pageLink: PageLink, public options: MpItemVersionQueryOptions = {}) {} + /** + * The grouped endpoint's query string: the filters, plus a sort key. It sizes its own answer, + * so it declares no page or page size, and each key's direction is fixed by its chain, so it + * declares no sort order either - sending any of the three would be sending something the + * server does not read. + */ + public toGroupedQuery(): string { + const text = this.pageLink.textSearch?.trim(); + let query = '?'; + if (text?.length) { + query += `textSearch=${encodeURIComponent(text)}&`; + } + if (this.pageLink.sortOrder) { + query += `sortProperty=${this.pageLink.sortOrder.property}&`; + } + return query + this.filtersToQuery(); + } + public toQuery(): string { - let query = this.pageLink.toQuery(); + return this.pageLink.toQuery() + this.filtersToQuery(); + } + + /** Every filter, as `&name=value` pairs - shared by both query strings above. */ + private filtersToQuery(): string { + let query = ''; const o = this.options; if (o.type) { query += `&type=${o.type}`; @@ -202,9 +224,6 @@ export class MpItemVersionQuery { if (o.scadaFirst != null) { query += `&scadaFirst=${o.scadaFirst}`; } - if (o.grouped != null) { - query += `&grouped=${o.grouped}`; - } return query; } } From 6eaf10dfd4572a6ec9e4fc3e9a6998b08e7c7b55 Mon Sep 17 00:00:00 2001 From: dshvaika Date: Tue, 15 Sep 2026 13:01:05 +0300 Subject: [PATCH 040/159] fix(iot-hub): keep the hero search alive when a request fails --- .../home/pages/iot-hub/iot-hub-home.component.ts | 16 ++++++++++------ 1 file changed, 10 insertions(+), 6 deletions(-) diff --git a/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-home.component.ts b/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-home.component.ts index cf26d52bbe..6108a9bd4e 100644 --- a/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-home.component.ts +++ b/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-home.component.ts @@ -4,9 +4,10 @@ import { Component, OnInit, OnDestroy, ViewChild, ElementRef } from '@angular/co import { Router } from '@angular/router'; import { MatAutocompleteTrigger } from '@angular/material/autocomplete'; import { BreakpointObserver } from '@angular/cdk/layout'; -import { forkJoin, Subject, Subscription } from 'rxjs'; -import { debounceTime, distinctUntilChanged, switchMap } from 'rxjs/operators'; +import { forkJoin, of, Subject, Subscription } from 'rxjs'; +import { catchError, debounceTime, distinctUntilChanged, switchMap } from 'rxjs/operators'; import { MediaBreakpoints } from '@shared/models/constants'; +import { emptyPageData } from '@shared/models/page/page-data'; import { PageLink } from '@shared/models/page/page-link'; import { Direction, SortOrder } from '@shared/models/page/sort-order'; import { MpItemVersionGroupedView, MpItemVersionQuery, MpItemVersionView } from '@shared/models/iot-hub/iot-hub-version.models'; @@ -174,7 +175,11 @@ export class TbIotHubHomeComponent implements OnInit, OnDestroy { // The grouped endpoint sizes its own answer, so the page size here is never sent. const pageLink = new PageLink(10, 0, trimmed || null, sortOrder); const query = new MpItemVersionQuery(pageLink); - return this.iotHubApiService.getPublishedVersionsGrouped(query, { ignoreLoading: true }); + // A failed request must not end the subscription: the interceptor reports it, and the + // panel goes back to an empty answer the next keystroke can replace. + return this.iotHubApiService.getPublishedVersionsGrouped(query, { ignoreLoading: true }).pipe( + catchError(() => of(emptyPageData())) + ); }) ).subscribe(result => { this.searchResults = result.data; @@ -572,9 +577,8 @@ export class TbIotHubHomeComponent implements OnInit, OnDestroy { .map(type => { const groupItems = groupMap.get(type); // Every row of a type carries the same typeTotal, so the first one answers for the - // section. The fallback covers a backend too old to have the grouped endpoint, whose - // rows arrive without it. - const total = groupItems[0].typeTotal ?? groupItems.length; + // section. + const total = groupItems[0].typeTotal; return { type, items: groupItems, total, remaining: Math.max(0, total - groupItems.length) }; }); } From 09dbf7b0c06e40c5d16e1e3f7568b6cb1cd3d4a3 Mon Sep 17 00:00:00 2001 From: dshvaika Date: Tue, 15 Sep 2026 13:20:56 +0300 Subject: [PATCH 041/159] refactor(iot-hub): read the hero popup's sections as sections --- .../src/app/core/http/iot-hub-api.service.ts | 13 ++--- .../pages/iot-hub/iot-hub-home.component.html | 2 +- .../pages/iot-hub/iot-hub-home.component.ts | 51 +++++++------------ .../models/iot-hub/iot-hub-version.models.ts | 15 +++--- 4 files changed, 34 insertions(+), 47 deletions(-) diff --git a/ui-ngx/src/app/core/http/iot-hub-api.service.ts b/ui-ngx/src/app/core/http/iot-hub-api.service.ts index f4d87a5ce5..987f9f214b 100644 --- a/ui-ngx/src/app/core/http/iot-hub-api.service.ts +++ b/ui-ngx/src/app/core/http/iot-hub-api.service.ts @@ -6,7 +6,7 @@ import { Store } from '@ngrx/store'; import { Observable } from 'rxjs'; import { PageData } from '@shared/models/page/page-data'; import { PageLink } from '@shared/models/page/page-link'; -import { MpItemVersionGroupedView, MpItemVersionQuery, MpItemVersionView } from '@shared/models/iot-hub/iot-hub-version.models'; +import { MpItemVersionQuery, MpItemVersionSection, MpItemVersionView } from '@shared/models/iot-hub/iot-hub-version.models'; import { CreatorView } from '@shared/models/iot-hub/iot-hub-creator.models'; import { IotHubInstalledItem, InstallItemVersionResult, InstallPlan, InstallPlanResult, UpdateItemVersionResult, ItemPublishedVersionInfo } from '@shared/models/iot-hub/iot-hub-installed-item.models'; import { ItemType, ItemTypeFilterInfo, WidgetCategory } from '@shared/models/iot-hub/iot-hub-item.models'; @@ -82,19 +82,20 @@ export class IotHubApiService { } /** - * The sectioned answer: at most four rows of each item type, every row carrying the size of its - * section. Its own endpoint, which is why this is its own method - it takes no page, page size - * or sort direction, and sending them would be sending what the server does not read. + * The sectioned answer: one section per item type, in the server's order, each holding at most + * four rows and the total behind them. Its own endpoint, which is why this is its own method - + * it takes no page, page size or sort direction, and sending them would be sending what the + * server does not read. */ public getPublishedVersionsGrouped(query: MpItemVersionQuery, - config?: IotHubRequestConfig): Observable> { + config?: IotHubRequestConfig): Observable { if (query.options.tbVersion == null) { query.options.tbVersion = tbVersionToInt(env.tbVersion); } if (query.options.peOnly == null) { query.options.peOnly = false; } - return this.http.get>( + return this.http.get( `${this.baseUrl}/api/versions/published/grouped${query.toGroupedQuery()}`, { params: this.buildParams(config) } ); diff --git a/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-home.component.html b/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-home.component.html index 995ee4395d..07905a8d21 100644 --- a/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-home.component.html +++ b/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-home.component.html @@ -72,7 +72,7 @@ - } @else if (searchResults.length === 0 && searchLoaded) { + } @else if (searchResultGroups.length === 0 && searchLoaded) {
search_off diff --git a/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-home.component.ts b/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-home.component.ts index 6108a9bd4e..47c1ca06e1 100644 --- a/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-home.component.ts +++ b/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-home.component.ts @@ -7,10 +7,9 @@ import { BreakpointObserver } from '@angular/cdk/layout'; import { forkJoin, of, Subject, Subscription } from 'rxjs'; import { catchError, debounceTime, distinctUntilChanged, switchMap } from 'rxjs/operators'; import { MediaBreakpoints } from '@shared/models/constants'; -import { emptyPageData } from '@shared/models/page/page-data'; import { PageLink } from '@shared/models/page/page-link'; import { Direction, SortOrder } from '@shared/models/page/sort-order'; -import { MpItemVersionGroupedView, MpItemVersionQuery, MpItemVersionView } from '@shared/models/iot-hub/iot-hub-version.models'; +import { MpItemVersionQuery, MpItemVersionSection, MpItemVersionView } from '@shared/models/iot-hub/iot-hub-version.models'; import { getItemTypeIcon, ItemType, itemTypeTranslations } from '@shared/models/iot-hub/iot-hub-item.models'; import { IotHubInstalledItem } from '@shared/models/iot-hub/iot-hub-installed-item.models'; import { IotHubApiService } from '@core/http/iot-hub-api.service'; @@ -35,14 +34,16 @@ interface HeroTypeConfig { interface SearchResultGroup { type: ItemType; - items: MpItemVersionGroupedView[]; - /** Rows of this type behind the answer, from the response's typeTotal. */ + items: MpItemVersionView[]; + /** Rows of this type behind the answer, from the section's total. */ total: number; /** total - items.length, floored at 0. Zero means the header shows no "+N more". */ remaining: number; } -const SEARCH_GROUP_ORDER: ItemType[] = [ +/** The types this popup lays out. A section of anything else is dropped rather than rendered + * without a label - the platform publishes no dashboards. Order comes from the server. */ +const SEARCH_GROUP_TYPES: ItemType[] = [ ItemType.DEVICE, ItemType.SOLUTION_TEMPLATE, ItemType.WIDGET, ItemType.CALCULATED_FIELD, ItemType.ALARM_RULE, ItemType.RULE_CHAIN ]; @@ -63,7 +64,6 @@ export class TbIotHubHomeComponent implements OnInit, OnDestroy { readonly ItemType = ItemType; searchText = ''; - searchResults: MpItemVersionGroupedView[] = []; searchResultGroups: SearchResultGroup[] = []; searchLoaded = false; searchLoading = false; @@ -178,12 +178,11 @@ export class TbIotHubHomeComponent implements OnInit, OnDestroy { // A failed request must not end the subscription: the interceptor reports it, and the // panel goes back to an empty answer the next keystroke can replace. return this.iotHubApiService.getPublishedVersionsGrouped(query, { ignoreLoading: true }).pipe( - catchError(() => of(emptyPageData())) + catchError(() => of([] as MpItemVersionSection[])) ); }) - ).subscribe(result => { - this.searchResults = result.data; - this.searchResultGroups = this.groupSearchResults(result.data); + ).subscribe(sections => { + this.searchResultGroups = this.toResultGroups(sections); this.searchLoaded = true; this.searchLoading = false; }); @@ -559,27 +558,15 @@ export class TbIotHubHomeComponent implements OnInit, OnDestroy { * arrives already capped at four per type - so all this does is put the types in the panel's * fixed order and carry each one's typeTotal onto the header. */ - private groupSearchResults(items: MpItemVersionGroupedView[]): SearchResultGroup[] { - const groupMap = new Map(); - for (const item of items) { - if (!SEARCH_GROUP_ORDER.includes(item.type)) { - continue; - } - let list = groupMap.get(item.type); - if (!list) { - list = []; - groupMap.set(item.type, list); - } - list.push(item); - } - return SEARCH_GROUP_ORDER - .filter(type => groupMap.has(type)) - .map(type => { - const groupItems = groupMap.get(type); - // Every row of a type carries the same typeTotal, so the first one answers for the - // section. - const total = groupItems[0].typeTotal; - return { type, items: groupItems, total, remaining: Math.max(0, total - groupItems.length) }; - }); + private toResultGroups(sections: MpItemVersionSection[]): SearchResultGroup[] { + return sections + .filter(section => SEARCH_GROUP_TYPES.includes(section.itemType)) + .map(section => ({ + type: section.itemType, + items: section.items, + total: section.total, + remaining: Math.max(0, section.total - section.items.length) + })); } + } diff --git a/ui-ngx/src/app/shared/models/iot-hub/iot-hub-version.models.ts b/ui-ngx/src/app/shared/models/iot-hub/iot-hub-version.models.ts index 4aaaeeaa62..4c1f79718b 100644 --- a/ui-ngx/src/app/shared/models/iot-hub/iot-hub-version.models.ts +++ b/ui-ngx/src/app/shared/models/iot-hub/iot-hub-version.models.ts @@ -109,15 +109,14 @@ export interface MpItemVersionView { } /** - * A row of a grouped search: the view plus the size of the section it belongs to. Its own type - * rather than a nullable field on the view, matching what the endpoint returns. + * One item type's share of a grouped search: the rows to show and how many exist behind them. + * A grouped answer is a list of these, in the server's section order, and a type nothing matched + * has no section — so a "+N more" header is `total - items.length`. */ -export interface MpItemVersionGroupedView extends MpItemVersionView { - /** - * Rows of this row's item type behind the answer — what a "+N more" header subtracts the - * shown rows from. Always set: the grouped endpoint projects it for every row it returns. - */ - typeTotal: number; +export interface MpItemVersionSection { + itemType: ItemType; + total: number; + items: MpItemVersionView[]; } // 404 body shapes returned by the public listing item-version endpoint From 19cbfc403a7da9076a7250ce8ffcdae728914da9 Mon Sep 17 00:00:00 2001 From: dshvaika Date: Tue, 15 Sep 2026 13:44:36 +0300 Subject: [PATCH 042/159] fix(iot-hub): keep the grouped query string well-formed without text --- .../shared/models/iot-hub/iot-hub-version.models.ts | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/ui-ngx/src/app/shared/models/iot-hub/iot-hub-version.models.ts b/ui-ngx/src/app/shared/models/iot-hub/iot-hub-version.models.ts index 4c1f79718b..c48a232098 100644 --- a/ui-ngx/src/app/shared/models/iot-hub/iot-hub-version.models.ts +++ b/ui-ngx/src/app/shared/models/iot-hub/iot-hub-version.models.ts @@ -163,14 +163,16 @@ export class MpItemVersionQuery { */ public toGroupedQuery(): string { const text = this.pageLink.textSearch?.trim(); - let query = '?'; + const parts: string[] = []; if (text?.length) { - query += `textSearch=${encodeURIComponent(text)}&`; + parts.push(`textSearch=${encodeURIComponent(text)}`); } if (this.pageLink.sortOrder) { - query += `sortProperty=${this.pageLink.sortOrder.property}&`; + parts.push(`sortProperty=${this.pageLink.sortOrder.property}`); } - return query + this.filtersToQuery(); + // filtersToQuery() emits leading ampersands, which is what toQuery() needs after a page link; + // here they may be the whole query string, so the first one is dropped. + return `?${`${parts.join('&')}${this.filtersToQuery()}`.replace(/^&/, '')}`; } public toQuery(): string { From 3af7b71740c6a3541a584b568247ee09c3b1c6ac Mon Sep 17 00:00:00 2001 From: dshvaika Date: Tue, 15 Sep 2026 14:00:41 +0300 Subject: [PATCH 043/159] refactor(iot-hub): give the grouped read its own query, without a page link --- .../src/app/core/http/iot-hub-api.service.ts | 39 +++-- .../pages/iot-hub/iot-hub-home.component.ts | 15 +- .../models/iot-hub/iot-hub-version.models.ts | 137 +++++++++--------- 3 files changed, 104 insertions(+), 87 deletions(-) diff --git a/ui-ngx/src/app/core/http/iot-hub-api.service.ts b/ui-ngx/src/app/core/http/iot-hub-api.service.ts index 987f9f214b..25c6253bae 100644 --- a/ui-ngx/src/app/core/http/iot-hub-api.service.ts +++ b/ui-ngx/src/app/core/http/iot-hub-api.service.ts @@ -6,7 +6,13 @@ import { Store } from '@ngrx/store'; import { Observable } from 'rxjs'; import { PageData } from '@shared/models/page/page-data'; import { PageLink } from '@shared/models/page/page-link'; -import { MpItemVersionQuery, MpItemVersionSection, MpItemVersionView } from '@shared/models/iot-hub/iot-hub-version.models'; +import { + MpItemVersionGroupedQuery, + MpItemVersionQuery, + MpItemVersionQueryOptions, + MpItemVersionSection, + MpItemVersionView +} from '@shared/models/iot-hub/iot-hub-version.models'; import { CreatorView } from '@shared/models/iot-hub/iot-hub-creator.models'; import { IotHubInstalledItem, InstallItemVersionResult, InstallPlan, InstallPlanResult, UpdateItemVersionResult, ItemPublishedVersionInfo } from '@shared/models/iot-hub/iot-hub-installed-item.models'; import { ItemType, ItemTypeFilterInfo, WidgetCategory } from '@shared/models/iot-hub/iot-hub-item.models'; @@ -69,12 +75,7 @@ export class IotHubApiService { } public getPublishedVersions(query: MpItemVersionQuery, config?: IotHubRequestConfig): Observable> { - if (query.options.tbVersion == null) { - query.options.tbVersion = tbVersionToInt(env.tbVersion); - } - if (query.options.peOnly == null) { - query.options.peOnly = false; - } + this.applyPlatformFilters(query.options); return this.http.get>( `${this.baseUrl}/api/versions/published${query.toQuery()}`, { params: this.buildParams(config) } @@ -87,20 +88,28 @@ export class IotHubApiService { * it takes no page, page size or sort direction, and sending them would be sending what the * server does not read. */ - public getPublishedVersionsGrouped(query: MpItemVersionQuery, + public getPublishedVersionsGrouped(query: MpItemVersionGroupedQuery, config?: IotHubRequestConfig): Observable { - if (query.options.tbVersion == null) { - query.options.tbVersion = tbVersionToInt(env.tbVersion); - } - if (query.options.peOnly == null) { - query.options.peOnly = false; - } + this.applyPlatformFilters(query.options); return this.http.get( - `${this.baseUrl}/api/versions/published/grouped${query.toGroupedQuery()}`, + `${this.baseUrl}/api/versions/published/grouped${query.toQuery()}`, { params: this.buildParams(config) } ); } + /** + * What this platform can install, filled in for a caller that did not say: items built for a + * newer ThingsBoard, and PE-only items on a CE instance, cannot be installed from here. + */ + private applyPlatformFilters(options: MpItemVersionQueryOptions): void { + if (options.tbVersion == null) { + options.tbVersion = tbVersionToInt(env.tbVersion); + } + if (options.peOnly == null) { + options.peOnly = false; + } + } + public getFilterInfo(itemType: ItemType, config?: IotHubRequestConfig): Observable { const url = `${this.baseUrl}/api/item-listing/filterInfo/${itemType}` + `?peOnly=false&tbVersion=${tbVersionToInt(env.tbVersion)}`; diff --git a/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-home.component.ts b/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-home.component.ts index 47c1ca06e1..f36a8738a1 100644 --- a/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-home.component.ts +++ b/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-home.component.ts @@ -9,7 +9,12 @@ import { catchError, debounceTime, distinctUntilChanged, switchMap } from 'rxjs/ import { MediaBreakpoints } from '@shared/models/constants'; import { PageLink } from '@shared/models/page/page-link'; import { Direction, SortOrder } from '@shared/models/page/sort-order'; -import { MpItemVersionQuery, MpItemVersionSection, MpItemVersionView } from '@shared/models/iot-hub/iot-hub-version.models'; +import { + MpItemVersionGroupedQuery, + MpItemVersionQuery, + MpItemVersionSection, + MpItemVersionView +} from '@shared/models/iot-hub/iot-hub-version.models'; import { getItemTypeIcon, ItemType, itemTypeTranslations } from '@shared/models/iot-hub/iot-hub-item.models'; import { IotHubInstalledItem } from '@shared/models/iot-hub/iot-hub-installed-item.models'; import { IotHubApiService } from '@core/http/iot-hub-api.service'; @@ -169,12 +174,8 @@ export class TbIotHubHomeComponent implements OnInit, OnDestroy { const trimmed = text.trim(); // Two states, one panel: popularity answers "what is worth looking at" with an empty // field, relevance answers "what did I ask for" once there is one. - const sortOrder: SortOrder = trimmed - ? { property: RELEVANCE, direction: Direction.DESC } - : { property: 'totalInstallCount', direction: Direction.DESC }; - // The grouped endpoint sizes its own answer, so the page size here is never sent. - const pageLink = new PageLink(10, 0, trimmed || null, sortOrder); - const query = new MpItemVersionQuery(pageLink); + const sortProperty = trimmed ? RELEVANCE : 'totalInstallCount'; + const query = new MpItemVersionGroupedQuery({}, trimmed, sortProperty); // A failed request must not end the subscription: the interceptor reports it, and the // panel goes back to an empty answer the next keystroke can replace. return this.iotHubApiService.getPublishedVersionsGrouped(query, { ignoreLoading: true }).pipe( diff --git a/ui-ngx/src/app/shared/models/iot-hub/iot-hub-version.models.ts b/ui-ngx/src/app/shared/models/iot-hub/iot-hub-version.models.ts index c48a232098..b194ab0371 100644 --- a/ui-ngx/src/app/shared/models/iot-hub/iot-hub-version.models.ts +++ b/ui-ngx/src/app/shared/models/iot-hub/iot-hub-version.models.ts @@ -152,79 +152,86 @@ export interface MpItemVersionQueryOptions { scadaFirst?: boolean; } +/** Every filter, as `&name=value` pairs - shared by both query shapes below. */ +function filtersToQuery(o: MpItemVersionQueryOptions): string { + let query = ''; + if (o.type) { + query += `&type=${o.type}`; + } + if (o.types?.length) { + query += o.types.map(t => `&type=${encodeURIComponent(t)}`).join(''); + } + if (o.peOnly != null) { + query += `&peOnly=${o.peOnly}`; + } + if (o.creatorId) { + query += `&creatorId=${o.creatorId}`; + } + if (o.categories?.length) { + query += o.categories.map(c => `&categories=${encodeURIComponent(c)}`).join(''); + } + if (o.useCases?.length) { + query += o.useCases.map(u => `&useCases=${encodeURIComponent(u)}`).join(''); + } + if (o.cfTypes?.length) { + query += o.cfTypes.map(t => `&cfTypes=${encodeURIComponent(t)}`).join(''); + } + if (o.widgetTypes?.length) { + query += o.widgetTypes.map(t => `&widgetTypes=${encodeURIComponent(t)}`).join(''); + } + if (o.ruleChainTypes?.length) { + query += o.ruleChainTypes.map(t => `&ruleChainTypes=${encodeURIComponent(t)}`).join(''); + } + if (o.tbVersion != null) { + query += `&tbVersion=${o.tbVersion}`; + } + if (o.hardwareTypes?.length) { + query += o.hardwareTypes.map(ht => `&hardwareTypes=${encodeURIComponent(ht)}`).join(''); + } + if (o.connectivity?.length) { + query += o.connectivity.map(c => `&connectivity=${encodeURIComponent(c)}`).join(''); + } + if (o.vendors?.length) { + query += o.vendors.map(v => `&vendors=${encodeURIComponent(v)}`).join(''); + } + if (o.scadaFirst != null) { + query += `&scadaFirst=${o.scadaFirst}`; + } + return query; +} + +/** A paged read: the filters, and the page to cut out of them. */ export class MpItemVersionQuery { constructor(public pageLink: PageLink, public options: MpItemVersionQueryOptions = {}) {} - /** - * The grouped endpoint's query string: the filters, plus a sort key. It sizes its own answer, - * so it declares no page or page size, and each key's direction is fixed by its chain, so it - * declares no sort order either - sending any of the three would be sending something the - * server does not read. - */ - public toGroupedQuery(): string { - const text = this.pageLink.textSearch?.trim(); + public toQuery(): string { + return this.pageLink.toQuery() + filtersToQuery(this.options); + } +} + +/** + * A sectioned read: the filters, what to search for, and which key orders a section. + * + * No `PageLink`, because the grouped endpoint takes no page and no page size - it sizes its own + * answer from the section limit - and no sort direction either, each key's direction being fixed + * by the chain the server switches on. A page link here could only carry values nobody sends. + */ +export class MpItemVersionGroupedQuery { + constructor(public options: MpItemVersionQueryOptions = {}, + public textSearch?: string, + public sortProperty?: string) {} + + public toQuery(): string { const parts: string[] = []; + const text = this.textSearch?.trim(); if (text?.length) { parts.push(`textSearch=${encodeURIComponent(text)}`); } - if (this.pageLink.sortOrder) { - parts.push(`sortProperty=${this.pageLink.sortOrder.property}`); + if (this.sortProperty) { + parts.push(`sortProperty=${this.sortProperty}`); } - // filtersToQuery() emits leading ampersands, which is what toQuery() needs after a page link; + // filtersToQuery() emits leading ampersands, which is what a page link needs in front of it; // here they may be the whole query string, so the first one is dropped. - return `?${`${parts.join('&')}${this.filtersToQuery()}`.replace(/^&/, '')}`; - } - - public toQuery(): string { - return this.pageLink.toQuery() + this.filtersToQuery(); - } - - /** Every filter, as `&name=value` pairs - shared by both query strings above. */ - private filtersToQuery(): string { - let query = ''; - const o = this.options; - if (o.type) { - query += `&type=${o.type}`; - } - if (o.types?.length) { - query += o.types.map(t => `&type=${encodeURIComponent(t)}`).join(''); - } - if (o.peOnly != null) { - query += `&peOnly=${o.peOnly}`; - } - if (o.creatorId) { - query += `&creatorId=${o.creatorId}`; - } - if (o.categories?.length) { - query += o.categories.map(c => `&categories=${encodeURIComponent(c)}`).join(''); - } - if (o.useCases?.length) { - query += o.useCases.map(u => `&useCases=${encodeURIComponent(u)}`).join(''); - } - if (o.cfTypes?.length) { - query += o.cfTypes.map(t => `&cfTypes=${encodeURIComponent(t)}`).join(''); - } - if (o.widgetTypes?.length) { - query += o.widgetTypes.map(t => `&widgetTypes=${encodeURIComponent(t)}`).join(''); - } - if (o.ruleChainTypes?.length) { - query += o.ruleChainTypes.map(t => `&ruleChainTypes=${encodeURIComponent(t)}`).join(''); - } - if (o.tbVersion != null) { - query += `&tbVersion=${o.tbVersion}`; - } - if (o.hardwareTypes?.length) { - query += o.hardwareTypes.map(ht => `&hardwareTypes=${encodeURIComponent(ht)}`).join(''); - } - if (o.connectivity?.length) { - query += o.connectivity.map(c => `&connectivity=${encodeURIComponent(c)}`).join(''); - } - if (o.vendors?.length) { - query += o.vendors.map(v => `&vendors=${encodeURIComponent(v)}`).join(''); - } - if (o.scadaFirst != null) { - query += `&scadaFirst=${o.scadaFirst}`; - } - return query; + return `?${`${parts.join('&')}${filtersToQuery(this.options)}`.replace(/^&/, '')}`; } } From 26aad8e47500093f841cfd3d824a99dd955ec568 Mon Sep 17 00:00:00 2001 From: dshvaika Date: Tue, 15 Sep 2026 16:31:42 +0300 Subject: [PATCH 044/159] docs(iot-hub): say what the section mapper does now --- .../app/modules/home/pages/iot-hub/iot-hub-home.component.ts | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-home.component.ts b/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-home.component.ts index f36a8738a1..ebd8485dd7 100644 --- a/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-home.component.ts +++ b/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-home.component.ts @@ -555,9 +555,8 @@ export class TbIotHubHomeComponent implements OnInit, OnDestroy { } /** - * Reads the sections the server built. It no longer decides membership - a grouped response - * arrives already capped at four per type - so all this does is put the types in the panel's - * fixed order and carry each one's typeTotal onto the header. + * Reads the sections the server built: they arrive capped and in the order to render them, so + * this only drops the types this panel has no layout for and works out each header's "+N more". */ private toResultGroups(sections: MpItemVersionSection[]): SearchResultGroup[] { return sections From e5a4a7e48920f32a046755df2794060157f3cc3a Mon Sep 17 00:00:00 2001 From: dshvaika Date: Wed, 16 Sep 2026 13:26:27 +0300 Subject: [PATCH 045/159] refactor(iot-hub): one sort menu and one cross-type list, and two failures the panels now survive The sort options lived in three arrays behind three identical local interfaces, and 'relevance' was spelled four ways; the six cross-type item types lived in two more arrays, byte-identical and renamed by this branch on both sides. Adding one option here meant editing three places, and a seventh item type would have needed two. All of it moves to iot-hub-item.models.ts as SortOption, IOT_HUB_SORT_OPTIONS, RELEVANCE_SORT_PROPERTY and CROSS_TYPE_ITEM_TYPES. The type list stays separate from CREATOR_VISIBLE_ITEM_TYPES, which holds the same six: that one is a membership test carrying the type tabs' order, this one is display order with DEVICE leading, and folding them together would have silently reordered the Type facet. The hero popup now sends relevance in both states like every other surface, rather than switching on whether the field has text. Both spellings ask the server for the same rows - with no text it substitutes the install count either way - so this is the code agreeing with the decision recorded on TBIOH-33, not a behaviour change. Two failures that were not survivable: - One of the six getFilterInfo calls failing emptied the whole filter panel. forkJoin is all-or-nothing, so typeOptions went unassigned although it needs no server data, and the i?.categories guards below could never fire. Each request now carries its own catchError, which is what those guards already expected. - A section arriving without items would have thrown inside a subscribe callback, out of reach of the catchError upstream, leaving the popup on its spinner. The response is an unvalidated cast of a new endpoint, so items is defaulted. The facet list held a Set the host mutated in place, which works only while that component is on default change detection. The host now hands over a new Set per toggle. SearchResultGroup.total went unread, and @for takes a track expression rather than a TrackByFunction. --- .../src/app/core/http/iot-hub-api.service.ts | 7 +- .../dashboard-widget-select.component.ts | 31 ++--- .../iot-hub/iot-hub-browse.component.ts | 31 ++--- .../iot-hub/iot-hub-facet-list.component.html | 2 +- .../iot-hub/iot-hub-facet-list.component.ts | 7 +- .../iot-hub/iot-hub-search.component.ts | 106 ++++++++---------- .../pages/iot-hub/iot-hub-home.component.ts | 55 +++++---- .../models/iot-hub/iot-hub-item.models.ts | 44 ++++++++ 8 files changed, 139 insertions(+), 144 deletions(-) diff --git a/ui-ngx/src/app/core/http/iot-hub-api.service.ts b/ui-ngx/src/app/core/http/iot-hub-api.service.ts index 25c6253bae..7f3b299962 100644 --- a/ui-ngx/src/app/core/http/iot-hub-api.service.ts +++ b/ui-ngx/src/app/core/http/iot-hub-api.service.ts @@ -83,10 +83,9 @@ export class IotHubApiService { } /** - * The sectioned answer: one section per item type, in the server's order, each holding at most - * four rows and the total behind them. Its own endpoint, which is why this is its own method - - * it takes no page, page size or sort direction, and sending them would be sending what the - * server does not read. + * The sectioned answer: one section per item type, in the server's order, each capped by the + * server and carrying the total behind that cap. Its own endpoint, which takes no page, page + * size or sort direction. */ public getPublishedVersionsGrouped(query: MpItemVersionGroupedQuery, config?: IotHubRequestConfig): Observable { diff --git a/ui-ngx/src/app/modules/home/components/dashboard-page/dashboard-widget-select.component.ts b/ui-ngx/src/app/modules/home/components/dashboard-page/dashboard-widget-select.component.ts index 57c621eb8d..7cb0eddd2b 100644 --- a/ui-ngx/src/app/modules/home/components/dashboard-page/dashboard-widget-select.component.ts +++ b/ui-ngx/src/app/modules/home/components/dashboard-page/dashboard-widget-select.component.ts @@ -21,7 +21,12 @@ import { ItemSizeStrategy } from '@shared/components/grid/scroll-grid.component' import { coerceBoolean } from '@shared/decorators/coercion'; import { TranslateService } from '@ngx-translate/core'; import { MpItemVersionQuery, MpItemVersionView, widgetTypeTranslations } from '@shared/models/iot-hub/iot-hub-version.models'; -import { ItemType, FilterParamInfo, WidgetCategory } from '@shared/models/iot-hub/iot-hub-item.models'; +import { + FilterParamInfo, + IOT_HUB_SORT_OPTIONS, + ItemType, + WidgetCategory +} from '@shared/models/iot-hub/iot-hub-item.models'; import { IotHubInstalledItem } from '@shared/models/iot-hub/iot-hub-installed-item.models'; import { IotHubApiService } from '@core/http/iot-hub-api.service'; import { IotHubActionsService } from '@home/components/iot-hub/iot-hub-actions.service'; @@ -38,12 +43,6 @@ type selectWidgetMode = 'installed' | 'iotHub'; type installedSubMode = 'default' | 'allWidgets'; type iotHubSubMode = 'default' | 'allWidgets' | 'installed' | 'category'; -interface WidgetSelectSortOption { - value: string; - label: string; - direction: Direction; -} - const LOGICAL_ALL_WIDGETS = '__logical_all_widgets__'; const LOGICAL_INSTALLED_FROM_IOT_HUB = '__logical_installed_from_iot_hub__'; @@ -89,22 +88,10 @@ export class DashboardWidgetSelectComponent { searchFocused = false; /** - * Relevance leads, and is therefore the default (iotHubSelectedSortIndex starts at 0). This - * panel has a search field, which is the only thing relevance ranks by; with the field empty - * the backend substitutes the install count, so the picker opens on the order it always had. - * - * scadaFirst is unaffected: the backend prepends it ahead of the caller's sort AND ahead of - * relevance, so a SCADA context still lists SCADA widgets first. - * - * Fourth copy of this list — the others are in TbIotHubSearchComponent, TbIotHubBrowseComponent - * and IOT_HUB_SORT_OPTIONS on thingsboard.io. Kept in step by hand. + * scadaFirst is unaffected by the sort: the backend prepends it ahead of the caller's key AND + * ahead of relevance, so a SCADA context still lists SCADA widgets first. */ - iotHubSortOptions: WidgetSelectSortOption[] = [ - { value: 'relevance', label: 'iot-hub.sort-most-relevant', direction: Direction.DESC }, - { value: 'totalInstallCount', label: 'iot-hub.sort-most-installed', direction: Direction.DESC }, - { value: 'publishedTime', label: 'iot-hub.sort-newest', direction: Direction.DESC }, - { value: 'name', label: 'iot-hub.sort-name', direction: Direction.ASC } - ]; + readonly iotHubSortOptions = IOT_HUB_SORT_OPTIONS; iotHubSelectedSortIndex = 0; @Input() diff --git a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-browse.component.ts b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-browse.component.ts index 785bd48660..63f561ddad 100644 --- a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-browse.component.ts +++ b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-browse.component.ts @@ -4,10 +4,15 @@ import { AfterViewInit, Component, ElementRef, EventEmitter, Input, NgZone, OnDe import { Subject } from 'rxjs'; import { debounceTime, takeUntil } from 'rxjs/operators'; import { PageLink } from '@shared/models/page/page-link'; -import { Direction, SortOrder } from '@shared/models/page/sort-order'; +import { SortOrder } from '@shared/models/page/sort-order'; import { PageData } from '@shared/models/page/page-data'; import { MpItemVersionQuery, MpItemVersionView } from '@shared/models/iot-hub/iot-hub-version.models'; -import { ItemType, FilterParamInfo, CREATOR_VISIBLE_ITEM_TYPES } from '@shared/models/iot-hub/iot-hub-item.models'; +import { + CREATOR_VISIBLE_ITEM_TYPES, + FilterParamInfo, + IOT_HUB_SORT_OPTIONS, + ItemType +} from '@shared/models/iot-hub/iot-hub-item.models'; import { widgetTypeTranslations, cfTypeTranslations, ruleChainTypeTranslations } from '@shared/models/iot-hub/iot-hub-version.models'; import { IotHubInstalledItem, DeviceInstalledItemDescriptor } from '@shared/models/iot-hub/iot-hub-installed-item.models'; import { IotHubApiService } from '@core/http/iot-hub-api.service'; @@ -16,12 +21,6 @@ import { ActivatedRoute, Router } from '@angular/router'; import { IotHubActionsService } from '@home/components/iot-hub/iot-hub-actions.service'; import { filterIotHubItemsBySearch, groupIotHubFilterItems, IotHubFilterGroup } from '@home/components/iot-hub/iot-hub-utils'; -interface SortOption { - value: string; - label: string; - direction: Direction; -} - @Component({ selector: 'tb-iot-hub-browse', standalone: false, @@ -126,21 +125,7 @@ export class TbIotHubBrowseComponent implements OnInit, AfterViewInit, OnDestroy activeHardwareTypes = new Set(); activeVendors = new Set(); - /** - * Relevance leads, and is therefore the default (selectedSortIndex starts at 0). A type page - * carries a search field, which is the only thing relevance ranks by; with the field empty the - * backend substitutes the install count, so browsing keeps the order it always had. - * - * Kept in step by hand with TbIotHubSearchComponent's list and with IOT_HUB_SORT_OPTIONS on - * thingsboard.io — three copies, because the two products share no code and this component - * predates the search page's list. - */ - sortOptions: SortOption[] = [ - { value: 'relevance', label: 'iot-hub.sort-most-relevant', direction: Direction.DESC }, - { value: 'totalInstallCount', label: 'iot-hub.sort-most-installed', direction: Direction.DESC }, - { value: 'publishedTime', label: 'iot-hub.sort-newest', direction: Direction.DESC }, - { value: 'name', label: 'iot-hub.sort-name', direction: Direction.ASC } - ]; + readonly sortOptions = IOT_HUB_SORT_OPTIONS; typeTabs: { type: ItemType; label: string }[] = CREATOR_VISIBLE_ITEM_TYPES.map(t => ({ type: t, diff --git a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-facet-list.component.html b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-facet-list.component.html index dfde943c22..8468ddc04b 100644 --- a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-facet-list.component.html +++ b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-facet-list.component.html @@ -22,7 +22,7 @@ }
- @for (option of visibleOptions; track trackByKey($index, option)) { + @for (option of visibleOptions; track option.key) { {{ labelFor(option.key) }} diff --git a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-facet-list.component.ts b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-facet-list.component.ts index b9b5625fce..7bcafacccc 100644 --- a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-facet-list.component.ts +++ b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-facet-list.component.ts @@ -26,7 +26,8 @@ export class TbIotHubFacetListComponent { @Input() options: FilterParamInfo[] = []; - /** Keys the host currently has selected. Read, never written. */ + /** Keys the host currently has selected. Read, never written - the host hands over a new Set + * on every toggle rather than mutating this one. */ @Input() selected = new Set(); /** @@ -76,8 +77,4 @@ export class TbIotHubFacetListComponent { onToggle(key: string): void { this.toggled.emit(key); } - - trackByKey(_index: number, option: FilterParamInfo): string { - return option.key; - } } diff --git a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-search.component.ts b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-search.component.ts index 6326a52010..7378d45d60 100644 --- a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-search.component.ts +++ b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-search.component.ts @@ -3,36 +3,22 @@ import { Component, OnInit, OnDestroy, Input, Output, EventEmitter, ViewChild, ElementRef } from '@angular/core'; import { Router } from '@angular/router'; import { TranslateService } from '@ngx-translate/core'; -import { forkJoin, Subject, Subscription } from 'rxjs'; -import { debounceTime, distinctUntilChanged } from 'rxjs/operators'; +import { forkJoin, of, Subject, Subscription } from 'rxjs'; +import { catchError, debounceTime, distinctUntilChanged } from 'rxjs/operators'; import { PageLink } from '@shared/models/page/page-link'; -import { Direction, SortOrder } from '@shared/models/page/sort-order'; +import { SortOrder } from '@shared/models/page/sort-order'; import { MpItemVersionQuery, MpItemVersionView } from '@shared/models/iot-hub/iot-hub-version.models'; -import { FilterParamInfo, ItemType, itemTypeTranslations } from '@shared/models/iot-hub/iot-hub-item.models'; +import { + CROSS_TYPE_ITEM_TYPES, + FilterParamInfo, + IOT_HUB_SORT_OPTIONS, + ItemType, + itemTypeTranslations +} from '@shared/models/iot-hub/iot-hub-item.models'; import { IotHubInstalledItem } from '@shared/models/iot-hub/iot-hub-installed-item.models'; import { IotHubApiService } from '@core/http/iot-hub-api.service'; import { IotHubActionsService } from './iot-hub-actions.service'; -interface SortOption { - value: string; - label: string; - direction: Direction; -} - -/** Sort property served by relevance ranking. With no text the backend substitutes the - * install count, so it is a safe default in both states. */ -const RELEVANCE = 'relevance'; - -/** - * Item types the Type facet offers, in the order every other cross-type surface uses (the hero - * popup's sections, the site's). Fixed rather than sorted by count: the counts move with the - * catalogue and a facet whose options reshuffle under the pointer is hard to use. - */ -const FACET_ITEM_TYPES: ItemType[] = [ - ItemType.DEVICE, ItemType.SOLUTION_TEMPLATE, ItemType.WIDGET, - ItemType.CALCULATED_FIELD, ItemType.ALARM_RULE, ItemType.RULE_CHAIN -]; - /** * Rows a page holds, as a multiple of the column count, so a page always ends on a complete row. * The floor keeps a one- or two-column phone layout from falling to three cards a page. @@ -84,7 +70,8 @@ export class TbIotHubSearchComponent implements OnInit, OnDestroy { return [base, base * 2, base * 4]; } - /** Filter panel state. Empty sets mean "no filter", which is what the query object expects. */ + // Filter panel state. Empty sets mean "no filter", which is what the query object expects. + /** Narrow widths only: the facet panel is a block above the results, not a sidebar. */ filtersOpen = false; typeOptions: FilterParamInfo[] = []; @@ -94,18 +81,7 @@ export class TbIotHubSearchComponent implements OnInit, OnDestroy { activeCategories = new Set(); activeUseCases = new Set(); - sortOptions: SortOption[] = [ - { value: RELEVANCE, label: 'iot-hub.sort-most-relevant', direction: Direction.DESC }, - { value: 'totalInstallCount', label: 'iot-hub.sort-most-installed', direction: Direction.DESC }, - { value: 'publishedTime', label: 'iot-hub.sort-newest', direction: Direction.DESC }, - { value: 'name', label: 'iot-hub.sort-name', direction: Direction.ASC } - ]; - /** - * Relevance is the default in BOTH states, which is why nothing here switches on whether the - * search field has text. With text it ranks the answer; without it the backend substitutes the - * install count, so a user who never opens this menu sees the order they always saw while - * browsing and the best matches once they type. - */ + readonly sortOptions = IOT_HUB_SORT_OPTIONS; selectedSortIndex = 0; installedWidgets: IotHubInstalledItem[] = []; @@ -156,15 +132,18 @@ export class TbIotHubSearchComponent implements OnInit, OnDestroy { }; onTypeToggle(key: string): void { - this.toggle(this.activeTypes, key); + this.activeTypes = this.toggled(this.activeTypes, key); + this.reloadFromFirstPage(); } onCategoryToggle(key: string): void { - this.toggle(this.activeCategories, key); + this.activeCategories = this.toggled(this.activeCategories, key); + this.reloadFromFirstPage(); } onUseCaseToggle(key: string): void { - this.toggle(this.activeUseCases, key); + this.activeUseCases = this.toggled(this.activeUseCases, key); + this.reloadFromFirstPage(); } get activeFilterCount(): number { @@ -175,19 +154,26 @@ export class TbIotHubSearchComponent implements OnInit, OnDestroy { if (this.activeFilterCount === 0) { return; } - this.activeTypes.clear(); - this.activeCategories.clear(); - this.activeUseCases.clear(); - this.pageIndex = 0; - this.loadResults(); + this.activeTypes = new Set(); + this.activeCategories = new Set(); + this.activeUseCases = new Set(); + this.reloadFromFirstPage(); } - private toggle(set: Set, key: string): void { - if (set.has(key)) { - set.delete(key); - } else { - set.add(key); + /** + * Returns a new Set rather than mutating the one passed in: TbIotHubFacetListComponent holds + * this very instance as an @Input, and a mutation it cannot see is a trap for the first person + * to put that component on OnPush. + */ + private toggled(set: Set, key: string): Set { + const next = new Set(set); + if (!next.delete(key)) { + next.add(key); } + return next; + } + + private reloadFromFirstPage(): void { this.pageIndex = 0; this.loadResults(); } @@ -197,27 +183,30 @@ export class TbIotHubSearchComponent implements OnInit, OnDestroy { * answers are merged here, the way the site merges the same six at build time. Counts are * deliberately not rendered: filterInfo takes no text query, so beside a searched result they * would be the whole catalogue's numbers pretending to describe this answer. + * + * Each request carries its own catchError so one type's failure costs that type's categories + * and use cases, not the panel: a bare forkJoin is all-or-nothing, and the Type facet needs no + * server data at all. */ private loadFilterInfo(): void { const config = { ignoreLoading: true, ignoreErrors: true }; forkJoin( - FACET_ITEM_TYPES.map(type => this.iotHubApiService.getFilterInfo(type, config)) + CROSS_TYPE_ITEM_TYPES.map(type => + this.iotHubApiService.getFilterInfo(type, config).pipe(catchError(() => of(null))) + ) ).subscribe({ next: infos => { // Every item type is offered, not only the ones filterInfo reports facets for: the // endpoint describes a type's categories and vendors, never how many items it has, and // a type whose items carry no categories would vanish from its own facet. - this.typeOptions = FACET_ITEM_TYPES.map(type => ({ + this.typeOptions = CROSS_TYPE_ITEM_TYPES.map(type => ({ key: type as string, totalItems: 0, totalInstallCount: 0 })); this.categoryOptions = this.mergeFacet(infos.map(i => i?.categories)); this.useCaseOptions = this.mergeFacet(infos.map(i => i?.useCases)); - }, - // A facet panel that failed to load is an empty panel, never a broken page: the grid - // beside it answers the query perfectly well without it. - error: () => {} + } }); } @@ -348,11 +337,6 @@ export class TbIotHubSearchComponent implements OnInit, OnDestroy { this.loadResults(); } - // Type helpers - - - - // Installed items getInstalledItem(item: MpItemVersionView): IotHubInstalledItem | undefined { switch (item.type) { diff --git a/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-home.component.ts b/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-home.component.ts index ebd8485dd7..577ed03a08 100644 --- a/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-home.component.ts +++ b/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-home.component.ts @@ -15,7 +15,13 @@ import { MpItemVersionSection, MpItemVersionView } from '@shared/models/iot-hub/iot-hub-version.models'; -import { getItemTypeIcon, ItemType, itemTypeTranslations } from '@shared/models/iot-hub/iot-hub-item.models'; +import { + CROSS_TYPE_ITEM_TYPES, + getItemTypeIcon, + ItemType, + itemTypeTranslations, + RELEVANCE_SORT_PROPERTY +} from '@shared/models/iot-hub/iot-hub-item.models'; import { IotHubInstalledItem } from '@shared/models/iot-hub/iot-hub-installed-item.models'; import { IotHubApiService } from '@core/http/iot-hub-api.service'; import { TranslateService } from '@ngx-translate/core'; @@ -40,24 +46,10 @@ interface HeroTypeConfig { interface SearchResultGroup { type: ItemType; items: MpItemVersionView[]; - /** Rows of this type behind the answer, from the section's total. */ - total: number; - /** total - items.length, floored at 0. Zero means the header shows no "+N more". */ + /** How many rows of this type the header offers beyond the ones shown. Zero renders no "+N more". */ remaining: number; } -/** The types this popup lays out. A section of anything else is dropped rather than rendered - * without a label - the platform publishes no dashboards. Order comes from the server. */ -const SEARCH_GROUP_TYPES: ItemType[] = [ - ItemType.DEVICE, ItemType.SOLUTION_TEMPLATE, ItemType.WIDGET, - ItemType.CALCULATED_FIELD, ItemType.ALARM_RULE, ItemType.RULE_CHAIN -]; - -/** Relevance ranking. Sent only while the field has text: with an empty field the backend - * substitutes the install count anyway, and this component knows the field state, so it sends - * the honest value rather than leaning on that safety net. */ -const RELEVANCE = 'relevance'; - @Component({ selector: 'tb-iot-hub-home', standalone: false, @@ -172,10 +164,10 @@ export class TbIotHubHomeComponent implements OnInit, OnDestroy { switchMap(text => { this.searchLoading = true; const trimmed = text.trim(); - // Two states, one panel: popularity answers "what is worth looking at" with an empty - // field, relevance answers "what did I ask for" once there is one. - const sortProperty = trimmed ? RELEVANCE : 'totalInstallCount'; - const query = new MpItemVersionGroupedQuery({}, trimmed, sortProperty); + // Relevance in both states, the same value every other IoT Hub surface sends: with an + // empty field the backend substitutes the install count, so this panel opens on + // popularity without having to say so. See TBIOH-33 for the decision. + const query = new MpItemVersionGroupedQuery({}, trimmed, RELEVANCE_SORT_PROPERTY); // A failed request must not end the subscription: the interceptor reports it, and the // panel goes back to an empty answer the next keystroke can replace. return this.iotHubApiService.getPublishedVersionsGrouped(query, { ignoreLoading: true }).pipe( @@ -556,17 +548,24 @@ export class TbIotHubHomeComponent implements OnInit, OnDestroy { /** * Reads the sections the server built: they arrive capped and in the order to render them, so - * this only drops the types this panel has no layout for and works out each header's "+N more". + * this only drops the types this panel has no layout for - the platform publishes no dashboards + * - and works out each header's "+N more". + * + * `items` is defaulted because the response is an unvalidated cast of a new endpoint, and a + * throw here lands in a subscribe callback, where it would leave the panel on its spinner + * rather than reaching the catchError upstream. */ private toResultGroups(sections: MpItemVersionSection[]): SearchResultGroup[] { return sections - .filter(section => SEARCH_GROUP_TYPES.includes(section.itemType)) - .map(section => ({ - type: section.itemType, - items: section.items, - total: section.total, - remaining: Math.max(0, section.total - section.items.length) - })); + .filter(section => CROSS_TYPE_ITEM_TYPES.includes(section.itemType)) + .map(section => { + const items = section.items ?? []; + return { + type: section.itemType, + items, + remaining: Math.max(0, section.total - items.length) + }; + }); } } diff --git a/ui-ngx/src/app/shared/models/iot-hub/iot-hub-item.models.ts b/ui-ngx/src/app/shared/models/iot-hub/iot-hub-item.models.ts index abdddc1734..68ca5c0158 100644 --- a/ui-ngx/src/app/shared/models/iot-hub/iot-hub-item.models.ts +++ b/ui-ngx/src/app/shared/models/iot-hub/iot-hub-item.models.ts @@ -1,5 +1,7 @@ // SPDX-FileCopyrightText: Copyright The Thingsboard Authors // SPDX-License-Identifier: Apache-2.0 +import { Direction } from '@shared/models/page/sort-order'; + export enum ItemType { WIDGET = 'WIDGET', DASHBOARD = 'DASHBOARD', @@ -54,6 +56,48 @@ export const CREATOR_VISIBLE_ITEM_TYPES: ItemType[] = [ ItemType.RULE_CHAIN, ]; +/** + * Item types a surface that mixes them lays out, in the order they are shown. Distinct from + * CREATOR_VISIBLE_ITEM_TYPES, which is the same six as a membership test and carries the type + * tabs' own order: here DEVICE leads, matching the hero popup's sections and the website. + */ +export const CROSS_TYPE_ITEM_TYPES: ItemType[] = [ + ItemType.DEVICE, + ItemType.SOLUTION_TEMPLATE, + ItemType.WIDGET, + ItemType.CALCULATED_FIELD, + ItemType.ALARM_RULE, + ItemType.RULE_CHAIN, +]; + +/** Sort property served by relevance ranking. */ +export const RELEVANCE_SORT_PROPERTY = 'relevance'; + +export interface SortOption { + value: string; + label: string; + direction: Direction; +} + +/** + * The sort menu every IoT Hub surface carrying a search field offers, and the order it offers + * them in: the first entry is the default each surface opens on. + * + * Relevance is that default in both states. With text it ranks the answer; with none the backend + * substitutes the install count, so a surface opens on the order it opened on before and nothing + * switches on the field state. Agreed with the product owner and recorded on TBIOH-33, which + * supersedes that ticket's SCOPE-IN 2, SCOPE-IN 4 and AC-4. + * + * One list rather than one per surface: a new key must reach all of them, and the surface that + * missed it would keep a different default without failing. + */ +export const IOT_HUB_SORT_OPTIONS: SortOption[] = [ + { value: RELEVANCE_SORT_PROPERTY, label: 'iot-hub.sort-most-relevant', direction: Direction.DESC }, + { value: 'totalInstallCount', label: 'iot-hub.sort-most-installed', direction: Direction.DESC }, + { value: 'publishedTime', label: 'iot-hub.sort-newest', direction: Direction.DESC }, + { value: 'name', label: 'iot-hub.sort-name', direction: Direction.ASC } +]; + export interface FilterParamInfo { key: string; totalItems: number; From 2d72735070a4dca445ee832b1e58a9b5df37079b Mon Sep 17 00:00:00 2001 From: dshvaika Date: Wed, 16 Sep 2026 13:26:27 +0300 Subject: [PATCH 046/159] style(iot-hub): close the formatting left behind by the layout and grouping changes The results container kept its old indentation after being wrapped in .tb-search-layout, so it read as a sibling of the wrapper and the two closing tags lined up at the same depth while closing different elements. The popup's @for sat in an ng-container carrying no directive. Removing the -compact rule left a blank line before the closing brace in four places. --- .../iot-hub/iot-hub-search.component.html | 80 +++++++++---------- .../iot-hub/iot-hub-search.component.scss | 4 - .../pages/iot-hub/iot-hub-home.component.html | 48 ++++++----- 3 files changed, 63 insertions(+), 69 deletions(-) diff --git a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-search.component.html b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-search.component.html index 5963b7c003..ca98ed1c0c 100644 --- a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-search.component.html +++ b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-search.component.html @@ -142,48 +142,48 @@ } -
- - @if (hasError) { -
-
-

{{ 'iot-hub.network-server-unavailable' | translate }}

-

{{ 'iot-hub.network-server-unavailable-text' | translate }}

- -
- } +
+ + @if (hasError) { +
+
+

{{ 'iot-hub.network-server-unavailable' | translate }}

+

{{ 'iot-hub.network-server-unavailable-text' | translate }}

+ +
+ } - - @if (!hasError && totalElements === 0 && searchText?.trim()) { -
-
-

{{ 'iot-hub.no-items-found' | translate }}

-

{{ 'iot-hub.try-adjusting-search' | translate }}

-
- } + + @if (!hasError && totalElements === 0 && searchText?.trim()) { +
+
+

{{ 'iot-hub.no-items-found' | translate }}

+

{{ 'iot-hub.try-adjusting-search' | translate }}

+
+ } - - @if (results.length > 0) { -
- @for (item of results; track item.id) { - - - } -
- } -
+ + @if (results.length > 0) { +
+ @for (item of results; track item.id) { + + + } +
+ } +
diff --git a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-search.component.scss b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-search.component.scss index 2556d03f3d..32c7a51458 100644 --- a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-search.component.scss +++ b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-search.component.scss @@ -279,21 +279,18 @@ @media #{$mat-gt-xxl} { .tb-search-card-grid { grid-template-columns: repeat(6, 1fr); - } } @media #{$mat-lt-xl} { .tb-search-card-grid { grid-template-columns: repeat(4, 1fr); - } } @media #{$mat-lt-xmd} { .tb-search-card-grid { grid-template-columns: repeat(3, 1fr); - } } @@ -316,7 +313,6 @@ .tb-search-card-grid { grid-template-columns: repeat(2, 1fr); - } } diff --git a/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-home.component.html b/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-home.component.html index 07905a8d21..c4d720976b 100644 --- a/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-home.component.html +++ b/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-home.component.html @@ -97,32 +97,30 @@ } - - @for (item of group.items; track item.id) { - - @if (isCompactType(item.type)) { -
- {{ getCompactIcon(item) }} -
- } @else { -
- @if (getItemImage(item); as imgUrl) { - - } @else { - {{ getItemTypeIcon(item.type) }} - } -
- } -
- {{ item.name }} - - person - {{ item.creatorDisplayName }} - + @for (item of group.items; track item.id) { + + @if (isCompactType(item.type)) { +
+ {{ getCompactIcon(item) }}
-
- } - + } @else { +
+ @if (getItemImage(item); as imgUrl) { + + } @else { + {{ getItemTypeIcon(item.type) }} + } +
+ } +
+ {{ item.name }} + + person + {{ item.creatorDisplayName }} + +
+ + } } } From edf81221ad1bd23b70eb150b2ceaafe1fa04dc92 Mon Sep 17 00:00:00 2001 From: dshvaika Date: Wed, 16 Sep 2026 13:27:19 +0300 Subject: [PATCH 047/159] fix(iot-hub): encode creatorId and type into the query string These were the only two of the thirteen fields interpolated raw, and creatorId is not an internal value: iot-hub-browse and the creator profile both read it straight off the route with nothing between the URL and the request, so a crafted id could close the parameter and append its own. The UUID shape is a convention here, not something this code enforces. --- .../src/app/shared/models/iot-hub/iot-hub-version.models.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/ui-ngx/src/app/shared/models/iot-hub/iot-hub-version.models.ts b/ui-ngx/src/app/shared/models/iot-hub/iot-hub-version.models.ts index b194ab0371..a5afaea23c 100644 --- a/ui-ngx/src/app/shared/models/iot-hub/iot-hub-version.models.ts +++ b/ui-ngx/src/app/shared/models/iot-hub/iot-hub-version.models.ts @@ -156,7 +156,7 @@ export interface MpItemVersionQueryOptions { function filtersToQuery(o: MpItemVersionQueryOptions): string { let query = ''; if (o.type) { - query += `&type=${o.type}`; + query += `&type=${encodeURIComponent(o.type)}`; } if (o.types?.length) { query += o.types.map(t => `&type=${encodeURIComponent(t)}`).join(''); @@ -165,7 +165,7 @@ function filtersToQuery(o: MpItemVersionQueryOptions): string { query += `&peOnly=${o.peOnly}`; } if (o.creatorId) { - query += `&creatorId=${o.creatorId}`; + query += `&creatorId=${encodeURIComponent(o.creatorId)}`; } if (o.categories?.length) { query += o.categories.map(c => `&categories=${encodeURIComponent(c)}`).join(''); From 5f3c374036f6b3f30659cd5a07938783ad2a9763 Mon Sep 17 00:00:00 2001 From: Viacheslav Klimov Date: Wed, 16 Sep 2026 14:00:48 +0300 Subject: [PATCH 048/159] Stop installing and deploying boot jars, Windows zips and debs --- TEST_FAST.md | 2 +- msa/pom.xml | 11 ++++----- pom.xml | 65 +++++++++------------------------------------------- 3 files changed, 16 insertions(+), 62 deletions(-) diff --git a/TEST_FAST.md b/TEST_FAST.md index fbea72db9c..28f4b4059a 100644 --- a/TEST_FAST.md +++ b/TEST_FAST.md @@ -42,7 +42,7 @@ Use `-Dpkg.skip=true` to skip all packaging at once (equivalent to all four flag |----------------------------|-------------------------------------------|--------------------------------------------------------------| | `-Dpkg.skip=true` | All of the below (bootjar + deb + rpm + zip) | Yes | | `-Dpkg.skip.bootjar=true` | `spring-boot:repackage` (`*-boot.jar`) | Yes — tests use the regular `.jar`, not the fat boot jar | -| `-Dpkg.skip.deb=true` | Gradle `buildDeb` + Maven `attach-artifact` | Yes — MSA docker modules copy the DEB from `target/` directly | +| `-Dpkg.skip.deb=true` | Gradle `buildDeb` | Yes — MSA docker modules copy the DEB from `target/` directly | | `-Dpkg.skip.rpm=true` | Gradle `buildRpm` | Yes — no test depends on the RPM | | `-Dpkg.skip.zip=true` | `maven-assembly-plugin` Windows ZIP | Yes — no test depends on the ZIP | diff --git a/msa/pom.xml b/msa/pom.xml index 3ffd8ed28b..a44cbbb93c 100644 --- a/msa/pom.xml +++ b/msa/pom.xml @@ -55,10 +55,7 @@ - + skip-deb @@ -71,9 +68,9 @@ none - + skip-pkg diff --git a/pom.xml b/pom.xml index 6ecad4cd2c..0c563899c5 100755 --- a/pom.xml +++ b/pom.xml @@ -34,14 +34,13 @@ Individual flags below can be set independently for finer control. --> false - + false @@ -50,11 +49,6 @@ module depends on the ZIP artifact, so this flag can be toggled freely without breaking downstream modules. --> false - - ${pkg.package.phase} thingsboard ${project.name} /var/log/${pkg.name} @@ -215,26 +209,7 @@ - - - skip-deb - - - pkg.skip.deb - true - - - - none - - - - + skip-pkg @@ -248,7 +223,6 @@ true true true - none @@ -565,6 +539,8 @@ ${pkg.skip.bootjar} ${pkg.mainClass} boot + + false ZIP true true @@ -641,28 +617,9 @@ ${pkg.skip.zip} - - - - - - org.codehaus.mojo - build-helper-maven-plugin - - - attach-deb - ${pkg.deb.phase} - - attach-artifact - - - - - ${project.build.directory}/${pkg.name}.deb - deb - deb - - + + false From 87a6f3088181c5a91bcf512af3cc4e4a316d5abd Mon Sep 17 00:00:00 2001 From: Viacheslav Klimov Date: Wed, 16 Sep 2026 14:02:33 +0300 Subject: [PATCH 049/159] Stop deploying the ui-ngx jar --- ui-ngx/pom.xml | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/ui-ngx/pom.xml b/ui-ngx/pom.xml index 164ce0d056..42b0fac027 100644 --- a/ui-ngx/pom.xml +++ b/ui-ngx/pom.xml @@ -71,6 +71,14 @@ + + + org.apache.maven.plugins + maven-deploy-plugin + + true + + From dab4ec72f9df0089c6651b29e794c766e5e601e6 Mon Sep 17 00:00:00 2001 From: dshvaika Date: Wed, 16 Sep 2026 14:38:38 +0300 Subject: [PATCH 050/159] refactor(iot-hub): drop the creatorId query parameter nothing produces The type page adopted `?creatorId=` from the URL whenever its input was unbound. Nothing in the platform builds such a URL: the only navigations carrying query parameters send `search` and `itemType`, and the creator profile scopes its list by binding the component's input rather than by navigating. The branch was reachable only by typing the parameter in by hand, and there it rescoped a Hub-wide type page with no visible sign of why the counts had changed. Both live callers - the creator profile and the add-item dialog - bind the input, which the removed code deferred to in any case. --- .../home/components/iot-hub/iot-hub-browse.component.ts | 6 ------ 1 file changed, 6 deletions(-) diff --git a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-browse.component.ts b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-browse.component.ts index 63f561ddad..2be0408826 100644 --- a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-browse.component.ts +++ b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-browse.component.ts @@ -171,12 +171,6 @@ export class TbIotHubBrowseComponent implements OnInit, AfterViewInit, OnDestroy if (params['search']) { this.textSearch = params['search']; } - // A search section header on a creator profile lands here scoped to that creator. The - // bound input wins: an embedded host (the add-item dialog) sets its own scope, and must - // not pick one up from whatever URL happens to be open behind the dialog. - if (!this.creatorId && !this.embedded && params['creatorId']) { - this.creatorId = params['creatorId']; - } if (this.fixedSubType) { const subtypes = this.getActiveSubtypes(); if (subtypes) { From 6aae7899bf9c8a55bef1904b4a9be3db74153838 Mon Sep 17 00:00:00 2001 From: dshvaika Date: Wed, 16 Sep 2026 14:38:38 +0300 Subject: [PATCH 051/159] docs(iot-hub): cite what a reader can find Two comments explaining why relevance is the default in both states pointed at an internal ticket, one of them at three numbered sections of it that are being rewritten precisely because the code no longer matches them. Neither pointer is reachable from this repository, and the numbering is due to move. The reasoning stays inline, with the accepted cost named: the menu reads "Most relevant" over an install-ordered list until the user types. --- .../modules/home/pages/iot-hub/iot-hub-home.component.ts | 4 ++-- .../src/app/shared/models/iot-hub/iot-hub-item.models.ts | 9 +++++---- 2 files changed, 7 insertions(+), 6 deletions(-) diff --git a/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-home.component.ts b/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-home.component.ts index 577ed03a08..91511f533d 100644 --- a/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-home.component.ts +++ b/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-home.component.ts @@ -165,8 +165,8 @@ export class TbIotHubHomeComponent implements OnInit, OnDestroy { this.searchLoading = true; const trimmed = text.trim(); // Relevance in both states, the same value every other IoT Hub surface sends: with an - // empty field the backend substitutes the install count, so this panel opens on - // popularity without having to say so. See TBIOH-33 for the decision. + // empty field the backend serves the install count under this key, so the panel opens on + // popularity without this component having to know it. const query = new MpItemVersionGroupedQuery({}, trimmed, RELEVANCE_SORT_PROPERTY); // A failed request must not end the subscription: the interceptor reports it, and the // panel goes back to an empty answer the next keystroke can replace. diff --git a/ui-ngx/src/app/shared/models/iot-hub/iot-hub-item.models.ts b/ui-ngx/src/app/shared/models/iot-hub/iot-hub-item.models.ts index 68ca5c0158..8fbe84440b 100644 --- a/ui-ngx/src/app/shared/models/iot-hub/iot-hub-item.models.ts +++ b/ui-ngx/src/app/shared/models/iot-hub/iot-hub-item.models.ts @@ -83,10 +83,11 @@ export interface SortOption { * The sort menu every IoT Hub surface carrying a search field offers, and the order it offers * them in: the first entry is the default each surface opens on. * - * Relevance is that default in both states. With text it ranks the answer; with none the backend - * substitutes the install count, so a surface opens on the order it opened on before and nothing - * switches on the field state. Agreed with the product owner and recorded on TBIOH-33, which - * supersedes that ticket's SCOPE-IN 2, SCOPE-IN 4 and AC-4. + * Relevance is that default with or without text. With text it ranks the answer; with none the + * backend serves the install count under the same key, so a surface opens on the order it opened + * on before and nothing here switches on the field state. The cost is a menu reading "Most + * relevant" over an install-ordered list until the user types; the alternative - flipping the + * selector once text appears - moves a control the user did not touch and reorders nothing. * * One list rather than one per surface: a new key must reach all of them, and the surface that * missed it would keep a different default without failing. From 256c575b42519b24b05f9c14751f4f6b11f02865 Mon Sep 17 00:00:00 2001 From: dpinkevych Date: Wed, 16 Sep 2026 14:46:00 +0300 Subject: [PATCH 052/159] warn that updating a solution template recreates everything it installed Updating a solution template deletes and reinstalls every entity it created, and unlike the other item types it is not stopped by the modified-entity check, so a tenant's own edits to those dashboards, devices and rule chains are lost without warning. The dialog showed the generic "replace the current version" wording, which does not suggest anything is destroyed. A second, smaller mismatch: a listing renamed between releases shows one name in the installed-items table and another in the dialog that table opens, because the dialog took its title from the published version while the table reads the tracking row. - show a dedicated description for SOLUTION_TEMPLATE that names what is deleted and recreated, and says local changes are lost - take the item details title from the tracking row while the dialog shows exactly the installed version; any other displayed version keeps its own name --- .../iot-hub/iot-hub-item-detail-dialog.component.html | 2 +- .../iot-hub/iot-hub-item-detail-dialog.component.ts | 11 +++++++++++ .../iot-hub/iot-hub-update-dialog.component.html | 4 ++-- .../iot-hub/iot-hub-update-dialog.component.ts | 11 +++++++++++ ui-ngx/src/assets/locale/locale.constant-en_US.json | 1 + 5 files changed, 26 insertions(+), 3 deletions(-) diff --git a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-item-detail-dialog.component.html b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-item-detail-dialog.component.html index 28e7e74e6d..83f8b69dc4 100644 --- a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-item-detail-dialog.component.html +++ b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-item-detail-dialog.component.html @@ -13,7 +13,7 @@
}
- {{ item.name }} + {{ itemTitle }}
{{ getTypeIcon() }} diff --git a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-item-detail-dialog.component.ts b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-item-detail-dialog.component.ts index d1c6f4f194..12a8900610 100644 --- a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-item-detail-dialog.component.ts +++ b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-item-detail-dialog.component.ts @@ -172,6 +172,17 @@ export class TbIotHubItemDetailDialogComponent extends DialogComponent{{ 'iot-hub.update-confirm-title' | translate:{ name: data.itemName } }} -

{{ 'iot-hub.update-desc' | translate }}

+

{{ updateDescKey | translate }}

} @case ('updating') {

{{ 'iot-hub.update-confirm-title' | translate:{ name: data.itemName } }}

-

{{ 'iot-hub.update-desc' | translate }}

+

{{ updateDescKey | translate }}

} @case ('success') {

{{ 'iot-hub.update-success-title' | translate }}

diff --git a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-update-dialog.component.ts b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-update-dialog.component.ts index ec4a48cd2d..e5472c45a1 100644 --- a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-update-dialog.component.ts +++ b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-update-dialog.component.ts @@ -59,6 +59,17 @@ export class TbIotHubUpdateDialogComponent extends DialogComponent Date: Fri, 21 Aug 2026 15:35:03 +0300 Subject: [PATCH 053/159] Honour skip.yarn in the JS module tests and packaging The yarn test execution in msa/js-executor declared its own skip flag, which overrode the mojo default of ${skip.yarn}, so a build run with -Dskip.yarn=true still invoked yarn run test with no node_modules installed. The two JS packaging modules had the same gap: the ZIP assembly requires a launcher binary produced by yarn run pkg, so it failed on a missing file rather than being skipped along with the yarn work that would have produced it. Both now follow skip.yarn while continuing to honour maven.test.skip. --- msa/js-executor/pom.xml | 26 +++++++++++++++++++++++++- msa/web-ui/pom.xml | 5 +++++ 2 files changed, 30 insertions(+), 1 deletion(-) diff --git a/msa/js-executor/pom.xml b/msa/js-executor/pom.xml index 5d28be03f8..8c35b773db 100644 --- a/msa/js-executor/pom.xml +++ b/msa/js-executor/pom.xml @@ -30,6 +30,18 @@ package ${project.build.directory}/package/linux ${project.build.directory}/package/windows + + ${skip.yarn} + + ${skip.yarn} pre-integration-test @@ -112,7 +124,7 @@ test - ${maven.test.skip} + ${yarn.test.skip} --mutex network run test @@ -206,6 +218,18 @@ + + skip-yarn-test + + + maven.test.skip + true + + + + true + + yarn-start diff --git a/msa/web-ui/pom.xml b/msa/web-ui/pom.xml index b2d148d5b2..f2f5e31309 100644 --- a/msa/web-ui/pom.xml +++ b/msa/web-ui/pom.xml @@ -32,6 +32,11 @@ package ${project.build.directory}/package/linux ${project.build.directory}/package/windows + + ${skip.yarn} pre-integration-test From 6172ca8963f6feffe4ddcf80dc079f1dbbdd0e3c Mon Sep 17 00:00:00 2001 From: Viacheslav Klimov Date: Fri, 21 Aug 2026 15:54:50 +0300 Subject: [PATCH 054/159] Add a skip.ui.build flag that skips only the UI builds frontend-maven-plugin reads skip.yarn on its own, so -Dskip.yarn=true switches off every yarn invocation in the project at once. That is the right shortcut for a local backend build, but it is too blunt for CI: it also silences the msa/js-executor sandbox tests, which are the only yarn-driven tests worth keeping. skip.ui.build is declared once in the root pom and defaults to ${skip.yarn}. It is wired into the frontend-maven-plugin configuration of ui-ngx and msa/web-ui, and into the pkg.skip.zip of msa/web-ui, whose Windows ZIP bundles the launcher that `yarn run pkg` produces. It is deliberately NOT wired into msa/js-executor: with -Dskip.ui.build=true that module still runs its yarn install, its `yarn run pkg` and its sandbox tests. Behaviour: no flags everything builds and is tested as before -Dskip.ui.build=true ui-ngx and msa/web-ui skip; msa/js-executor still builds and runs its tests -Dskip.yarn=true everything skips, exactly as before The element is declared at plugin level rather than per execution so that it also covers the executions contributed by the yarn-build and yarn-start profiles, and so that node/yarn itself is no longer downloaded when there is nothing to run. --- msa/web-ui/pom.xml | 7 +++++-- pom.xml | 7 +++++++ ui-ngx/pom.xml | 3 +++ 3 files changed, 15 insertions(+), 2 deletions(-) diff --git a/msa/web-ui/pom.xml b/msa/web-ui/pom.xml index f2f5e31309..93d2ecff76 100644 --- a/msa/web-ui/pom.xml +++ b/msa/web-ui/pom.xml @@ -33,10 +33,10 @@ ${project.build.directory}/package/linux ${project.build.directory}/package/windows - ${skip.yarn} + ${skip.ui.build} pre-integration-test @@ -65,6 +65,9 @@ target ${basedir} + + ${skip.ui.build} diff --git a/pom.xml b/pom.xml index 0c563899c5..11c0e52c30 100755 --- a/pom.xml +++ b/pom.xml @@ -28,6 +28,13 @@ 17 17 ${basedir} + + ${skip.yarn} none none + ${skip.ui.build} From 21e5d93aeca3ffc038cee2f3290df0a59c86e826 Mon Sep 17 00:00:00 2001 From: Viacheslav Klimov Date: Wed, 16 Sep 2026 15:05:42 +0300 Subject: [PATCH 055/159] Skip all packaging when the UI build is skipped Packages built without the UI are incomplete, so -Dskip.yarn=true and -Dskip.ui.build=true now imply -Dpkg.skip=true through dedicated profiles in the root pom and msa/pom.xml. This replaces the module-level pkg.skip.zip properties in msa/js-executor and msa/web-ui, which shadowed the root skip-pkg profile and made -Dpkg.skip=true build their Windows ZIPs again. --- TEST_FAST.md | 2 ++ msa/js-executor/pom.xml | 5 ----- msa/pom.xml | 25 +++++++++++++++++++++++++ msa/web-ui/pom.xml | 5 ----- pom.xml | 37 ++++++++++++++++++++++++++++++++++++- 5 files changed, 63 insertions(+), 11 deletions(-) diff --git a/TEST_FAST.md b/TEST_FAST.md index 28f4b4059a..11f8969fca 100644 --- a/TEST_FAST.md +++ b/TEST_FAST.md @@ -46,6 +46,8 @@ Use `-Dpkg.skip=true` to skip all packaging at once (equivalent to all four flag | `-Dpkg.skip.rpm=true` | Gradle `buildRpm` | Yes — no test depends on the RPM | | `-Dpkg.skip.zip=true` | `maven-assembly-plugin` Windows ZIP | Yes — no test depends on the ZIP | +`-Dskip.yarn=true` and `-Dskip.ui.build=true` imply `-Dpkg.skip=true`: packages built without the UI are incomplete. + ## Testcontainers compatibility with the Docker API workaround In case your tests failed to run testcontainers due to unsupported Docker API version diff --git a/msa/js-executor/pom.xml b/msa/js-executor/pom.xml index 8c35b773db..3a4a1ccda4 100644 --- a/msa/js-executor/pom.xml +++ b/msa/js-executor/pom.xml @@ -30,11 +30,6 @@ package ${project.build.directory}/package/linux ${project.build.directory}/package/windows - - ${skip.yarn} + + skip-pkg-without-yarn + + + skip.yarn + true + + + + none + + + + skip-pkg-without-ui-build + + + skip.ui.build + true + + + + none + + black-box-tests diff --git a/msa/web-ui/pom.xml b/msa/web-ui/pom.xml index 93d2ecff76..9e616482cf 100644 --- a/msa/web-ui/pom.xml +++ b/msa/web-ui/pom.xml @@ -32,11 +32,6 @@ package ${project.build.directory}/package/linux ${project.build.directory}/package/windows - - ${skip.ui.build} pre-integration-test diff --git a/pom.xml b/pom.xml index 11c0e52c30..77706d1627 100755 --- a/pom.xml +++ b/pom.xml @@ -33,7 +33,8 @@ cover msa/js-executor, whose yarn install and sandbox tests keep running. frontend-maven-plugin reads skip.yarn itself, so that property cannot be narrowed to a subset of the modules; this one can, and it defaults to skip.yarn so that - -Dskip.yarn=true still skips every yarn invocation in the project exactly as before. --> + -Dskip.yarn=true still skips every yarn invocation in the project exactly as before. + Either flag also skips all packaging (see the skip-pkg-without-* profiles). --> ${skip.yarn} none none @@ -233,6 +234,40 @@ + + + skip-pkg-without-yarn + + + skip.yarn + true + + + + true + true + true + true + + + + skip-pkg-without-ui-build + + + skip.ui.build + true + + + + true + true + true + true + + + packaging From c5a3bea6dfed1da693bc6263c36e0fa2bc9708f1 Mon Sep 17 00:00:00 2001 From: dshvaika Date: Wed, 16 Sep 2026 15:22:10 +0300 Subject: [PATCH 056/159] fix(iot-hub): let the keyboard reach every row of the search popup The popup keeps focus in the input and walks its rows with an active-descendant key manager, which only knows about options. A section header written as a span with role="button" and tabindex="0" is therefore unreachable: the arrow keys skip it, its keyup.enter can never fire because it can never hold focus, and Tab does not help since leaving the input closes the panel. That header is the only way from the popup into a type page, so without a mouse there was no way in at all. The footer had the same shape, though its action is also on the input's own Enter. The header also sat inside the group's label element, which is presentational, so the section's name came out as the header's whole text - "Devices +12 more" - wrapping a control nobody could operate. Header and footer are now options like every other row. They take part in arrow navigation, they read as part of the list, and the group wrapper goes away with the label it was distorting. Rows also acted on (click) alone. Pressing Enter on a highlighted result runs _selectViaInteraction, which is not a DOM click, so the card never opened from the keyboard. Every row now acts on (onSelectionChange) guarded by isUserInput, one path for pointer and keyboard both. Enter in the field needed a guard to go with that: the trigger acts on keydown and this handler runs on keyup, which the trigger's preventDefault does not stop, so one Enter would have opened a result and then navigated away from it. --- .../pages/iot-hub/iot-hub-home.component.html | 76 +++++++++---------- .../pages/iot-hub/iot-hub-home.component.scss | 66 +++++++--------- .../pages/iot-hub/iot-hub-home.component.ts | 9 +++ 3 files changed, 75 insertions(+), 76 deletions(-) diff --git a/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-home.component.html b/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-home.component.html index c4d720976b..b2be21ac32 100644 --- a/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-home.component.html +++ b/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-home.component.html @@ -85,53 +85,51 @@ } @else { @for (group of searchResultGroups; track group.type) { - - - {{ getSearchGroupLabel(group.type) }} - @if (group.remaining > 0) { - - {{ 'iot-hub.section-more' | translate:{ count: group.remaining } }} - chevron_right - - } - - @for (item of group.items; track item.id) { - - @if (isCompactType(item.type)) { -
- {{ getCompactIcon(item) }} -
- } @else { -
- @if (getItemImage(item); as imgUrl) { - - } @else { - {{ getItemTypeIcon(item.type) }} - } -
- } -
- {{ item.name }} - - person - {{ item.creatorDisplayName }} - -
-
+ + {{ getSearchGroupLabel(group.type) }} + @if (group.remaining > 0) { + + {{ 'iot-hub.section-more' | translate:{ count: group.remaining } }} + chevron_right + } -
+ + @for (item of group.items; track item.id) { + + @if (isCompactType(item.type)) { +
+ {{ getCompactIcon(item) }} +
+ } @else { +
+ @if (getItemImage(item); as imgUrl) { + + } @else { + {{ getItemTypeIcon(item.type) }} + } +
+ } +
+ {{ item.name }} + + person + {{ item.creatorDisplayName }} + +
+
+ } } } - +
diff --git a/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-home.component.scss b/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-home.component.scss index d8934e82ff..98b4ab0389 100644 --- a/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-home.component.scss +++ b/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-home.component.scss @@ -220,45 +220,32 @@ 0 114px 46px 0 rgba(0, 0, 0, 0.01), 0 178px 50px 0 rgba(0, 0, 0, 0); - // Section group — 12px gap between groups - .mat-mdc-optgroup + .mat-mdc-optgroup .mat-mdc-optgroup-label { + // Section header — an option like every other row, not a button beside them, so the arrow keys + // reach it and a screen reader reads it in the list. It IS the way into the type page: title + // left, how much is not shown plus a chevron right. There is deliberately no per-section + // "see all" row under the items; six of those on one panel is what this variant avoids. + // Design: 14px Medium, 0.25 tracking, black-tertiary, 4px V / 16px H, 12px above each section. + .mat-mdc-option.tb-search-popup-group-header { + padding: 4px 16px; + min-height: 28px; margin-top: 12px; + + &:first-child { + margin-top: 0; + } + + .mdc-list-item__primary-text { + justify-content: space-between; + } } - // Section title — Design: 14px Medium, 0.25 tracking, black-tertiary, 4px V / 16px H - .mat-mdc-optgroup .mat-mdc-optgroup-label { - padding: 4px 16px; - min-height: 28px; + .tb-search-popup-group-label { font-size: 14px; font-weight: 500; line-height: 20px; letter-spacing: 0.25px; color: rgba(0, 0, 0, 0.54); white-space: nowrap; - - .mdc-list-item__primary-text { - font-size: 14px; - font-weight: 500; - line-height: 20px; - letter-spacing: 0.25px; - color: rgba(0, 0, 0, 0.54); - // The header spans the panel so the count can sit against the right edge. Material's own - // label span is only as wide as its text. - width: 100%; - } - } - - // Section header — the label IS the link into the type page: title left, how much is not shown - // plus a chevron right. There is deliberately no per-section "see all" row under the items; - // six of those on one panel is what this variant was chosen to avoid. - .tb-search-popup-group-header { - display: flex; - align-items: center; - justify-content: space-between; - gap: 16px; - width: 100%; - cursor: pointer; - outline: none; } .tb-search-popup-group-more { @@ -281,7 +268,7 @@ } // Item row — Design: 8px V / 16px H, 16px gap, centered - .mat-mdc-optgroup .mat-mdc-option:not(.mat-mdc-option-multiple) { + .mat-mdc-option:not(.mat-mdc-option-multiple) { padding: 8px 16px; min-height: auto; height: auto; @@ -426,26 +413,31 @@ } // Footer — Design: 40px h, 8px V / 16px H, 1px top border, tb-primary text - .tb-search-popup-footer { + .mat-mdc-option.tb-search-popup-footer { position: sticky; bottom: 0; + z-index: 1; border-top: 1px solid rgba(0, 0, 0, 0.12); height: 40px; min-height: 40px; padding: 8px 16px; - display: flex; - align-items: center; - justify-content: flex-start; font-size: 14px; font-weight: 500; line-height: 20px; letter-spacing: 0.25px; color: $tb-primary-color; - cursor: pointer; background: white; white-space: nowrap; - &:hover { + .mdc-list-item__primary-text { + justify-content: flex-start; + font: inherit; + letter-spacing: inherit; + color: inherit; + } + + &:hover:not(.mdc-list-item--disabled), + &.mat-mdc-option-active:not(.mdc-list-item--disabled) { background: #f5f5f5; } } diff --git a/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-home.component.ts b/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-home.component.ts index 91511f533d..8e6038ef96 100644 --- a/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-home.component.ts +++ b/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-home.component.ts @@ -239,7 +239,16 @@ export class TbIotHubHomeComponent implements OnInit, OnDestroy { setTimeout(() => this.searchAutoTrigger?.openPanel()); } + /** + * Enter in the field opens the search page - unless the panel has an option highlighted, which + * the trigger has already acted on during keydown. This runs on keyup, which preventDefault on + * the keydown does not stop, so without the guard one Enter would both open a result and + * navigate away from it. + */ onSearch(): void { + if (this.searchAutoTrigger?.activeOption) { + return; + } this.seeAllResults(); } From e0fd388da90d27008260911cac0ccf96e5502bf0 Mon Sep 17 00:00:00 2001 From: nickAS21 Date: Wed, 16 Sep 2026 15:50:46 +0300 Subject: [PATCH 057/159] lwm2m: fix bootstrap-short-server-id = null - tests 2 --- .../secure/LwM2MBootstrapConfig.java | 2 +- .../DeviceProfileDataValidatorTest.java | 67 ++++++++++--------- 2 files changed, 36 insertions(+), 33 deletions(-) diff --git a/common/transport/lwm2m/src/main/java/org/thingsboard/server/transport/lwm2m/bootstrap/secure/LwM2MBootstrapConfig.java b/common/transport/lwm2m/src/main/java/org/thingsboard/server/transport/lwm2m/bootstrap/secure/LwM2MBootstrapConfig.java index 285d6bc9f9..fe6701a1ed 100644 --- a/common/transport/lwm2m/src/main/java/org/thingsboard/server/transport/lwm2m/bootstrap/secure/LwM2MBootstrapConfig.java +++ b/common/transport/lwm2m/src/main/java/org/thingsboard/server/transport/lwm2m/bootstrap/secure/LwM2MBootstrapConfig.java @@ -114,7 +114,7 @@ public class LwM2MBootstrapConfig implements Serializable { private BootstrapConfig.ServerConfig setServerConfig (AbstractLwM2MBootstrapServerCredential serverCredential) { BootstrapConfig.ServerConfig serverConfig = new BootstrapConfig.ServerConfig(); - if (!serverCredential.isBootstrapServerIs()) { + if (!serverCredential.isBootstrapServerIs() && serverCredential.getShortServerId() != null) { serverConfig.shortId = serverCredential.getShortServerId(); } serverConfig.lifetime = serverCredential.getLifetime(); diff --git a/dao/src/test/java/org/thingsboard/server/dao/service/validator/DeviceProfileDataValidatorTest.java b/dao/src/test/java/org/thingsboard/server/dao/service/validator/DeviceProfileDataValidatorTest.java index 477b410d6c..3a4fa13281 100644 --- a/dao/src/test/java/org/thingsboard/server/dao/service/validator/DeviceProfileDataValidatorTest.java +++ b/dao/src/test/java/org/thingsboard/server/dao/service/validator/DeviceProfileDataValidatorTest.java @@ -33,6 +33,7 @@ import java.util.List; import java.util.UUID; import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.BDDMockito.willReturn; import static org.mockito.Mockito.verify; import static org.thingsboard.server.common.data.device.credentials.lwm2m.Lwm2mServerIdentifier.LWM2M_SERVER_MAX; @@ -115,7 +116,7 @@ class DeviceProfileDataValidatorTest { void testValidateDeviceProfile_Lwm2mBootstrap_ShortServerId_Ok() { Integer shortServerId = 123; Integer shortServerIdBs = null; - DeviceProfile deviceProfile = getDeviceProfile(shortServerId, shortServerIdBs, 1); + DeviceProfile deviceProfile = getDeviceProfile(shortServerId, shortServerIdBs, false); validator.validateDataImpl(tenantId, deviceProfile); verify(validator).validateString("Device profile name", deviceProfile.getName()); @@ -123,66 +124,49 @@ class DeviceProfileDataValidatorTest { @Test void testValidateDeviceProfile_Lwm2mShortServerId_Ok_BootstrapShortServerId_validate_0_to_null_Warn() { - Integer shortServerId = 123; - Integer shortServerIdBs = 0; - DeviceProfile deviceProfile = getDeviceProfile(shortServerId, shortServerIdBs, 1); - - validator.validateDataImpl(tenantId, deviceProfile); - verify(validator).validateString("Device profile name", deviceProfile.getName()); + validateDeviceProfile_Lwm2mShortServerId_Ok_BootstrapShortServerId_Number_to_null_Warn(0); } @Test void testValidateDeviceProfile_Lwm2mShortServerId_Ok_BootstrapShortServerId_More_65535_to_null_Warn() { - Integer shortServerId = 123; - Integer shortServerIdBs = 65536; - DeviceProfile deviceProfile = getDeviceProfile(shortServerId, shortServerIdBs, 1); - validator.validateDataImpl(tenantId, deviceProfile); - verify(validator).validateString("Device profile name", deviceProfile.getName()); + validateDeviceProfile_Lwm2mShortServerId_Ok_BootstrapShortServerId_Number_to_null_Warn(65536); } @Test void testValidateDeviceProfile_Lwm2mShortServerId_Ok_BootstrapShortServerId_111_to_null_Warn() { - Integer shortServerId = 123; - Integer shortServerIdBs = 111; - DeviceProfile deviceProfile = getDeviceProfile(shortServerId, shortServerIdBs, 1); - validator.validateDataImpl(tenantId, deviceProfile); - verify(validator).validateString("Device profile name", deviceProfile.getName()); + validateDeviceProfile_Lwm2mShortServerId_Ok_BootstrapShortServerId_Number_to_null_Warn(111); } @Test void testValidateDeviceProfile_Lwm2mShortServerId_Ok_BootstrapShortServerId_Less_0_to_null_Warn() { - Integer shortServerId = 123; - Integer shortServerIdBs = -1; - DeviceProfile deviceProfile = getDeviceProfile(shortServerId, shortServerIdBs, 1); - validator.validateDataImpl(tenantId, deviceProfile); - verify(validator).validateString("Device profile name", deviceProfile.getName()); + validateDeviceProfile_Lwm2mShortServerId_Ok_BootstrapShortServerId_Number_to_null_Warn(-1); } @Test void testValidateDeviceProfile_Lwm2mShortServerId_null_Error_BootstrapShortServerId_null_Ok() { - verifyValidationError(null, null, "LwM2M" + msgErrorNotNull, 1); + verifyValidationError(null, null, "LwM2M" + msgErrorNotNull, false); } @Test void testValidateDeviceProfile_Lwm2mShortServerId_More_65534_Error_BootstrapShortServerId_null_Ok() { - verifyValidationError(NOT_USED_IDENTIFYING_LWM2M_SERVER_MAX.getId(), null, msgErrorLwm2mRange, 1); + verifyValidationError(NOT_USED_IDENTIFYING_LWM2M_SERVER_MAX.getId(), null, msgErrorLwm2mRange, false); } @Test void testValidateDeviceProfile_Lwm2mShortServerId_Less_1_Error_BootstrapShortServerId_null_Ok() { - verifyValidationError(0, null, msgErrorLwm2mRange, 1); + verifyValidationError(0, null, msgErrorLwm2mRange, false); } @Test - void testValidateDeviceProfile_Lwm2mShortServerId_Ok_Cnt_BootstrapShortServerId_Less_1_Error() { - verifyValidationError(123, null, msgErrorBsOnlyOne, 2); + void testValidateDeviceProfile_MoreThanOneBootstrapServer_Error() { + verifyValidationError(123, null, msgErrorBsOnlyOne, true); } - private DeviceProfile getDeviceProfile(Integer shortServerId, Integer shortServerIdBs, int cntBsServer) { + private DeviceProfile getDeviceProfile(Integer shortServerId, Integer shortServerIdBs, boolean withSecondBsServer) { Lwm2mDeviceProfileTransportConfiguration transportConfiguration = getTransportConfiguration(OBSERVE_ATTRIBUTES_WITHOUT_PARAMS, getBootstrapServerCredentialsNoSec(shortServerId, shortServerIdBs)); - if (cntBsServer == 2) { - AbstractLwM2MBootstrapServerCredential bootstrapServerCredentialNoSecTwo = getBootstrapServerCredentialNoSec(true, shortServerId, shortServerIdBs == null ? 111 : shortServerIdBs++); + if (withSecondBsServer) { + AbstractLwM2MBootstrapServerCredential bootstrapServerCredentialNoSecTwo = getBootstrapServerCredentialNoSec(true, shortServerId, shortServerIdBs == null ? 111 : ++shortServerIdBs); transportConfiguration.getBootstrap().add(bootstrapServerCredentialNoSecTwo); } DeviceProfile deviceProfile = new DeviceProfile(); @@ -224,11 +208,30 @@ class DeviceProfileDataValidatorTest { return bootstrapServerCredential; } - private void verifyValidationError(Integer shortServerId, Integer shortServerIdBs, String msgError, int cntBsServer) { - DeviceProfile deviceProfile = getDeviceProfile(shortServerId, shortServerIdBs, cntBsServer); + private void verifyValidationError(Integer shortServerId, Integer shortServerIdBs, String msgError, boolean withSecondBsServer) { + DeviceProfile deviceProfile = getDeviceProfile(shortServerId, shortServerIdBs, withSecondBsServer); assertThatThrownBy(() -> validator.validateDataImpl(tenantId, deviceProfile)) .hasMessageContaining(msgError); } + private LwM2MBootstrapServerCredential getBootstrapCredential(DeviceProfile deviceProfile) { + Lwm2mDeviceProfileTransportConfiguration transportConfig = + (Lwm2mDeviceProfileTransportConfiguration) deviceProfile.getProfileData().getTransportConfiguration(); + + return transportConfig.getBootstrap().stream() + .filter(credential -> ((NoSecLwM2MBootstrapServerCredential)credential).isBootstrapServerIs()) + .findFirst() + .orElseThrow(() -> new AssertionError("Bootstrap server not found in profile")); + } + + + private void validateDeviceProfile_Lwm2mShortServerId_Ok_BootstrapShortServerId_Number_to_null_Warn(Integer shortServerIdBs) { + DeviceProfile deviceProfile = getDeviceProfile(123, shortServerIdBs, false); + validator.validateDataImpl(tenantId, deviceProfile); + verify(validator).validateString("Device profile name", deviceProfile.getName()); + LwM2MBootstrapServerCredential bsCredential = getBootstrapCredential(deviceProfile); + assertThat(((NoSecLwM2MBootstrapServerCredential)bsCredential).getShortServerId()); + } + } From ccf0581ac38f75461b8dc7511ddce557ef4701b2 Mon Sep 17 00:00:00 2001 From: Viacheslav Klimov Date: Wed, 16 Sep 2026 15:35:28 +0300 Subject: [PATCH 058/159] Generate build-info outside the packaging profile Activating any other root profile (skip-pkg, skip-pkg-without-*) switches off the activeByDefault packaging profile, which held the only build-info execution, so such builds had no build-info.properties and ProjectInfo failed at runtime. The jar plugin config (logback.xml exclusion, manifest) moves out of the profile for the same reason. --- pom.xml | 42 ++++++++++++++++++++++++++---------------- 1 file changed, 26 insertions(+), 16 deletions(-) diff --git a/pom.xml b/pom.xml index 77706d1627..0a46f54ab1 100755 --- a/pom.xml +++ b/pom.xml @@ -554,21 +554,6 @@ - - org.apache.maven.plugins - maven-jar-plugin - - - **/logback.xml - - - - ${pkg.implementationTitle} - ${project.version} - - - - org.springframework.boot spring-boot-maven-plugin @@ -597,7 +582,6 @@ repackage - build-info @@ -717,6 +701,18 @@ org.apache.maven.plugins maven-jar-plugin ${jar-plugin.version} + + + + **/logback.xml + + + + ${pkg.implementationTitle} + ${project.version} + + + org.apache.maven.plugins @@ -727,6 +723,20 @@ org.springframework.boot spring-boot-maven-plugin ${spring-boot.version} + + + + build-info + + build-info + + + + false + + + org.thingsboard From 7ef912dfadb43a6cd20d0ef7e6b886f798083234 Mon Sep 17 00:00:00 2001 From: nickAS21 Date: Wed, 16 Sep 2026 16:23:57 +0300 Subject: [PATCH 059/159] lwm2m: fix bootstrap-short-server-id = null - comments 2 --- .../lwm2m/bootstrap/secure/LwM2MBootstrapConfig.java | 2 +- .../validator/DeviceProfileDataValidator.java | 12 +++++------- 2 files changed, 6 insertions(+), 8 deletions(-) diff --git a/common/transport/lwm2m/src/main/java/org/thingsboard/server/transport/lwm2m/bootstrap/secure/LwM2MBootstrapConfig.java b/common/transport/lwm2m/src/main/java/org/thingsboard/server/transport/lwm2m/bootstrap/secure/LwM2MBootstrapConfig.java index fe6701a1ed..d592183440 100644 --- a/common/transport/lwm2m/src/main/java/org/thingsboard/server/transport/lwm2m/bootstrap/secure/LwM2MBootstrapConfig.java +++ b/common/transport/lwm2m/src/main/java/org/thingsboard/server/transport/lwm2m/bootstrap/secure/LwM2MBootstrapConfig.java @@ -38,7 +38,7 @@ public class LwM2MBootstrapConfig implements Serializable { * clientSecretKey?: string, * serverPublicKey?: string; * clientHoldOffTime?: number, - * shortServerId?: number for DM server; null for BS server, + * shortServerId?: number, // DM server only; null for the BS entry * bootstrapServerAccountTimeout: number * */ @Getter diff --git a/dao/src/main/java/org/thingsboard/server/dao/service/validator/DeviceProfileDataValidator.java b/dao/src/main/java/org/thingsboard/server/dao/service/validator/DeviceProfileDataValidator.java index bf72cf286c..938b15616b 100644 --- a/dao/src/main/java/org/thingsboard/server/dao/service/validator/DeviceProfileDataValidator.java +++ b/dao/src/main/java/org/thingsboard/server/dao/service/validator/DeviceProfileDataValidator.java @@ -169,7 +169,7 @@ public class DeviceProfileDataValidator extends AbstractHasOtaPackageValidator lwM2MBootstrapServersConfigurations = ((Lwm2mDeviceProfileTransportConfiguration) transportConfiguration).getBootstrap(); if (lwM2MBootstrapServersConfigurations != null) { validateLwm2mServersConfigOfBootstrapForClient(lwM2MBootstrapServersConfigurations, - ((Lwm2mDeviceProfileTransportConfiguration) transportConfiguration).isBootstrapServerUpdateEnable()); + ((Lwm2mDeviceProfileTransportConfiguration) transportConfiguration).isBootstrapServerUpdateEnable(), deviceProfile.getName(), tenantId); for (LwM2MBootstrapServerCredential bootstrapServerCredential : lwM2MBootstrapServersConfigurations) { validateLwm2mServersCredentialOfBootstrapForClient(bootstrapServerCredential); } @@ -344,12 +344,11 @@ public class DeviceProfileDataValidator extends AbstractHasOtaPackageValidator lwM2MBootstrapServersConfigurations, boolean isBootstrapServerUpdateEnable) { + private void validateLwm2mServersConfigOfBootstrapForClient(List lwM2MBootstrapServersConfigurations, + boolean isBootstrapServerUpdateEnable, String deviceProfileName, TenantId tenantId) { Set uris = new HashSet<>(); Set shortServerIds = new HashSet<>(); boolean hasBootstrapServer = false; @@ -363,14 +362,13 @@ public class DeviceProfileDataValidator extends AbstractHasOtaPackageValidator Date: Wed, 16 Sep 2026 16:27:28 +0300 Subject: [PATCH 060/159] lwm2m: fix bootstrap-short-server-id = null - comments 3 --- .../org/thingsboard/server/service/lwm2m/LwM2MServiceImpl.java | 3 +++ 1 file changed, 3 insertions(+) diff --git a/application/src/main/java/org/thingsboard/server/service/lwm2m/LwM2MServiceImpl.java b/application/src/main/java/org/thingsboard/server/service/lwm2m/LwM2MServiceImpl.java index 8c7deeea1b..6f8a39ce73 100644 --- a/application/src/main/java/org/thingsboard/server/service/lwm2m/LwM2MServiceImpl.java +++ b/application/src/main/java/org/thingsboard/server/service/lwm2m/LwM2MServiceImpl.java @@ -30,6 +30,9 @@ public class LwM2MServiceImpl implements LwM2MService { if (bsServerConfig!= null) { LwM2MServerSecurityConfigDefault result = getServerSecurityConfig(bsServerConfig); result.setBootstrapServerIs(bootstrapServer); + if (bootstrapServer) { + result.setShortServerId(null); + } return result; } else { From 14e3025a24842b66d4df2c67fec1faace5e6a4a1 Mon Sep 17 00:00:00 2001 From: dshvaika Date: Thu, 17 Sep 2026 13:15:27 +0300 Subject: [PATCH 061/159] fix(iot-hub): make the popup's Enter guard and row padding hold on their own Three things from the re-review, two of them introduced by the commit that turned the popup's header and footer into options. **The Enter guard never fired.** It asked the autocomplete trigger for its active option during keyup, but the trigger clears that inside the same keydown - it calls _selectViaInteraction and then _resetActiveItem, which with no autoActiveFirstOption sets the active index to -1. So the guard always fell through, and one Enter on a highlighted row opened it and then navigated away from it. That is worse than the behaviour before, where the click handler simply never ran. The row that acts now records it through rowSelectedByUser, which does not depend on the order the two handlers run in, and typing clears the flag since a pointer selection leaves no keyup behind it. **The header's own padding was overridden.** Under one ancestor chain, `.mat-mdc-option.tb-search-popup-group-header` and `.mat-mdc-option:not(.mat-mdc-option-multiple)` both weigh (0,4,0), and the second was declared later, so every section header shipped 8px taller than the 4px the comment above it documents - with up to six of them in a 424px panel. The catch-all could not match the old span header; it matches an option. Each row kind now carries its own class and the shared parts sit in one rule, so nothing here rests on source order. The footer had the same collision and only won by being declared last. **The hover-scrollbar block is a mixin.** This branch added a second byte-identical copy of it. Both now call tb-iot-hub-hover-scrollbar from the partial they already import. The mixin records what is deliberately NOT settled here: whether these panels should keep a thumb that is invisible until hover, and whether to add the standardised scrollbar-width / scrollbar-color that Firefox reads, is a question for the IoT Hub filter UI as a whole - iot-hub-browse and dashboard-widget-select carry the same treatment and predate this branch. --- .../components/iot-hub/_iot-hub-common.scss | 36 +++++++++++++++++ .../iot-hub/iot-hub-facet-list.component.scss | 27 +------------ .../iot-hub/iot-hub-search.component.scss | 27 +------------ .../pages/iot-hub/iot-hub-home.component.html | 8 ++-- .../pages/iot-hub/iot-hub-home.component.scss | 40 +++++++++++-------- .../pages/iot-hub/iot-hub-home.component.ts | 31 +++++++++++--- 6 files changed, 91 insertions(+), 78 deletions(-) diff --git a/ui-ngx/src/app/modules/home/components/iot-hub/_iot-hub-common.scss b/ui-ngx/src/app/modules/home/components/iot-hub/_iot-hub-common.scss index d247f20112..96697ebe74 100644 --- a/ui-ngx/src/app/modules/home/components/iot-hub/_iot-hub-common.scss +++ b/ui-ngx/src/app/modules/home/components/iot-hub/_iot-hub-common.scss @@ -119,3 +119,39 @@ pointer-events: none; } } + +// Scroll area that shows its thumb only while the container is hovered — the filter panels' +// own treatment, kept here so the two that use it cannot drift apart. +// +// Not the app-wide one: theme.scss keeps its thumb permanently visible. Whether these panels +// should do the same, and whether to add the standardised scrollbar-width / scrollbar-color +// that Firefox reads, is a question for the IoT Hub filter UI as a whole rather than for one +// panel; iot-hub-browse and dashboard-widget-select carry copies of this same treatment. +@mixin tb-iot-hub-hover-scrollbar { + &::-webkit-scrollbar { + width: 6px; + } + + &::-webkit-scrollbar-track { + background-color: transparent; + } + + &::-webkit-scrollbar-thumb { + background-color: transparent; + border-radius: 3px; + } + + &:hover { + &::-webkit-scrollbar-track { + background-color: rgba(0, 0, 0, 0.04); + } + + &::-webkit-scrollbar-thumb { + background-color: rgba(0, 0, 0, 0.2); + + &:hover { + background-color: rgba(0, 0, 0, 0.35); + } + } + } +} diff --git a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-facet-list.component.scss b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-facet-list.component.scss index e5fc43f803..4df80a68e1 100644 --- a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-facet-list.component.scss +++ b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-facet-list.component.scss @@ -45,32 +45,7 @@ overflow-y: auto; } - &::-webkit-scrollbar { - width: 6px; - } - - &::-webkit-scrollbar-track { - background-color: transparent; - } - - &::-webkit-scrollbar-thumb { - background-color: transparent; - border-radius: 3px; - } - - &:hover { - &::-webkit-scrollbar-track { - background-color: rgba(0, 0, 0, 0.04); - } - - &::-webkit-scrollbar-thumb { - background-color: rgba(0, 0, 0, 0.2); - - &:hover { - background-color: rgba(0, 0, 0, 0.35); - } - } - } + @include tb-iot-hub-hover-scrollbar; } .tb-iot-hub-facet-search { diff --git a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-search.component.scss b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-search.component.scss index 32c7a51458..3f946404ad 100644 --- a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-search.component.scss +++ b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-search.component.scss @@ -221,32 +221,7 @@ overflow-y: auto; padding-top: 20px; - &::-webkit-scrollbar { - width: 6px; - } - - &::-webkit-scrollbar-track { - background-color: transparent; - } - - &::-webkit-scrollbar-thumb { - background-color: transparent; - border-radius: 3px; - } - - &:hover { - &::-webkit-scrollbar-track { - background-color: rgba(0, 0, 0, 0.04); - } - - &::-webkit-scrollbar-thumb { - background-color: rgba(0, 0, 0, 0.2); - - &:hover { - background-color: rgba(0, 0, 0, 0.35); - } - } - } + @include tb-iot-hub-hover-scrollbar; } // The close button and heading belong to the narrow layout only. diff --git a/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-home.component.html b/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-home.component.html index b2be21ac32..564f89ca46 100644 --- a/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-home.component.html +++ b/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-home.component.html @@ -86,7 +86,7 @@ } @else { @for (group of searchResultGroups; track group.type) { + (onSelectionChange)="rowSelectedByUser($event) && navigateToSection(group.type)"> {{ getSearchGroupLabel(group.type) }} @if (group.remaining > 0) { @@ -96,8 +96,8 @@ } @for (item of group.items; track item.id) { - + @if (isCompactType(item.type)) {
{{ getCompactIcon(item) }} @@ -123,7 +123,7 @@ } } + (onSelectionChange)="rowSelectedByUser($event) && seeAllResults()"> @if (searchText?.trim(); as query) { {{ 'iot-hub.see-results-for' | translate:{ search: query } }} } @else { diff --git a/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-home.component.scss b/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-home.component.scss index 98b4ab0389..8a89ebae44 100644 --- a/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-home.component.scss +++ b/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-home.component.scss @@ -220,6 +220,27 @@ 0 114px 46px 0 rgba(0, 0, 0, 0.01), 0 178px 50px 0 rgba(0, 0, 0, 0); + // Every row of the panel shares the flex line and the highlight; the boxes differ per kind + // below. Each kind is selected by its own class rather than by leaning on source order, since + // .mat-mdc-option. and .mat-mdc-option:not(...) tie on specificity. + .mat-mdc-option { + .mdc-list-item__primary-text { + display: flex; + align-items: center; + gap: 16px; + width: 100%; + } + + &:hover:not(.mdc-list-item--disabled), + &.mat-mdc-option-active:not(.mdc-list-item--disabled) { + background: rgba(0, 0, 0, 0.04); + } + + .mat-icon, tb-icon { + margin-right: 0; + } + } + // Section header — an option like every other row, not a button beside them, so the arrow keys // reach it and a screen reader reads it in the list. It IS the way into the type page: title // left, how much is not shown plus a chevron right. There is deliberately no per-section @@ -268,26 +289,10 @@ } // Item row — Design: 8px V / 16px H, 16px gap, centered - .mat-mdc-option:not(.mat-mdc-option-multiple) { + .mat-mdc-option.tb-search-popup-item { padding: 8px 16px; min-height: auto; height: auto; - - &:hover:not(.mdc-list-item--disabled), - &.mat-mdc-option-active:not(.mdc-list-item--disabled) { - background: rgba(0, 0, 0, 0.04); - } - - .mat-icon, tb-icon { - margin-right: 0; - } - - .mdc-list-item__primary-text { - display: flex; - align-items: center; - gap: 16px; - width: 100%; - } } // Thumbnail — Design: 99px x 56px, 4px radius, 1px border, 4% bg @@ -392,6 +397,7 @@ .tb-search-popup-no-results { pointer-events: none; opacity: 1 !important; + padding: 8px 16px; } .tb-search-popup-no-results-content { diff --git a/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-home.component.ts b/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-home.component.ts index 8e6038ef96..4efb672e33 100644 --- a/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-home.component.ts +++ b/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-home.component.ts @@ -3,6 +3,7 @@ import { Component, OnInit, OnDestroy, ViewChild, ElementRef } from '@angular/core'; import { Router } from '@angular/router'; import { MatAutocompleteTrigger } from '@angular/material/autocomplete'; +import { MatOptionSelectionChange } from '@angular/material/core'; import { BreakpointObserver } from '@angular/cdk/layout'; import { forkJoin, of, Subject, Subscription } from 'rxjs'; import { catchError, debounceTime, distinctUntilChanged, switchMap } from 'rxjs/operators'; @@ -66,6 +67,7 @@ export class TbIotHubHomeComponent implements OnInit, OnDestroy { searchLoading = false; @ViewChild(MatAutocompleteTrigger) searchAutoTrigger: MatAutocompleteTrigger; @ViewChild('searchInput', {read: ElementRef}) searchInputRef: ElementRef; + private enterHandledByRow = false; private searchSubject = new Subject(); private searchSubscription: Subscription; @@ -217,6 +219,7 @@ export class TbIotHubHomeComponent implements OnInit, OnDestroy { } onSearchInput(): void { + this.enterHandledByRow = false; this.searchLoading = true; this.searchSubject.next(this.searchText || ''); } @@ -240,13 +243,31 @@ export class TbIotHubHomeComponent implements OnInit, OnDestroy { } /** - * Enter in the field opens the search page - unless the panel has an option highlighted, which - * the trigger has already acted on during keydown. This runs on keyup, which preventDefault on - * the keydown does not stop, so without the guard one Enter would both open a result and - * navigate away from it. + * Gate on every row's selection: false for the panel's own bookkeeping, true when the user + * picked the row - and then it records that this keystroke has been dealt with. + * + * One Enter reaches two handlers. The autocomplete trigger acts on keydown, the field's own + * handler on keyup, and preventDefault on the first does not stop the second. The trigger's + * activeOption cannot tell them apart either: it clears it inside that same keydown, so by + * keyup it reads empty whether or not a row acted. The row that acted says so instead, which + * does not depend on the order the two handlers run in. + */ + rowSelectedByUser(event: MatOptionSelectionChange): boolean { + if (!event.isUserInput) { + return false; + } + this.enterHandledByRow = true; + return true; + } + + /** + * Enter in the field opens the search page, unless a row has just acted on this same press. + * The flag is also cleared on input, since a pointer selection sets it with no keyup to follow + * and would otherwise swallow the next Enter. */ onSearch(): void { - if (this.searchAutoTrigger?.activeOption) { + if (this.enterHandledByRow) { + this.enterHandledByRow = false; return; } this.seeAllResults(); From dfd0c5c7fa98a1ae63761c7e3fa65e7f0e794ce7 Mon Sep 17 00:00:00 2001 From: nickAS21 Date: Thu, 17 Sep 2026 14:28:19 +0300 Subject: [PATCH 062/159] lwm2m: fix bootstrap-short-server-id = null - comments 4 --- .../service/lwm2m/LwM2MServiceImpl.java | 26 +++++++++++++------ .../DeviceProfileControllerTest.java | 24 +++++++++++++++++ .../bootstrap/LwM2MServerSecurityConfig.java | 2 +- .../DeviceProfileDataValidatorTest.java | 4 +-- 4 files changed, 45 insertions(+), 11 deletions(-) diff --git a/application/src/main/java/org/thingsboard/server/service/lwm2m/LwM2MServiceImpl.java b/application/src/main/java/org/thingsboard/server/service/lwm2m/LwM2MServiceImpl.java index 6f8a39ce73..33d0487fdd 100644 --- a/application/src/main/java/org/thingsboard/server/service/lwm2m/LwM2MServiceImpl.java +++ b/application/src/main/java/org/thingsboard/server/service/lwm2m/LwM2MServiceImpl.java @@ -28,23 +28,33 @@ public class LwM2MServiceImpl implements LwM2MService { public LwM2MServerSecurityConfigDefault getServerSecurityInfo(boolean bootstrapServer) { LwM2MSecureServerConfig bsServerConfig = bootstrapServer ? bootstrapConfig.orElse(null) : serverConfig; if (bsServerConfig!= null) { - LwM2MServerSecurityConfigDefault result = getServerSecurityConfig(bsServerConfig); - result.setBootstrapServerIs(bootstrapServer); - if (bootstrapServer) { - result.setShortServerId(null); - } - return result; + return getServerSecurityConfig(bsServerConfig, bootstrapServer); } else { return null; } } - private LwM2MServerSecurityConfigDefault getServerSecurityConfig(LwM2MSecureServerConfig bsServerConfig) { + private LwM2MServerSecurityConfigDefault getServerSecurityConfig(LwM2MSecureServerConfig bsServerConfig, boolean bootstrapServer) { LwM2MServerSecurityConfigDefault bsServ = new LwM2MServerSecurityConfigDefault(); - bsServ.setShortServerId(bsServerConfig.getId()); bsServ.setHost(bsServerConfig.getHost()); bsServ.setPort(bsServerConfig.getPort()); + bsServ.setBootstrapServerIs(bootstrapServer); + if (bootstrapServer) { + if (bsServerConfig.getId() != null) { + log.warn("Ignoring Short Server ID [{}] on the Bootstrap Server entry: cleared to null for backward compatibility (ThingsBoard <= 4.2).", + bsServerConfig.getId()); + } + bsServ.setShortServerId(null); + } else { + Integer configId = bsServerConfig.getId(); + if (configId == null || configId <= 0 || configId >= 65535) { + log.warn("Invalid Short Server ID [{}] for LwM2M Server entry: defaulting to [1] for backward compatibility (ThingsBoard <= 4.2).", + configId); + configId = 1; + } + bsServ.setShortServerId(configId); + } bsServ.setSecurityHost(bsServerConfig.getSecureHost()); bsServ.setSecurityPort(bsServerConfig.getSecurePort()); byte[] publicKeyBase64 = getPublicKey(bsServerConfig); diff --git a/application/src/test/java/org/thingsboard/server/controller/DeviceProfileControllerTest.java b/application/src/test/java/org/thingsboard/server/controller/DeviceProfileControllerTest.java index fa4d65b1a4..3d226d903a 100644 --- a/application/src/test/java/org/thingsboard/server/controller/DeviceProfileControllerTest.java +++ b/application/src/test/java/org/thingsboard/server/controller/DeviceProfileControllerTest.java @@ -34,6 +34,7 @@ import org.thingsboard.server.common.data.audit.ActionType; import org.thingsboard.server.common.data.device.profile.JsonTransportPayloadConfiguration; import org.thingsboard.server.common.data.device.profile.MqttDeviceProfileTransportConfiguration; import org.thingsboard.server.common.data.device.profile.ProtoTransportPayloadConfiguration; +import org.thingsboard.server.common.data.device.profile.lwm2m.bootstrap.LwM2MServerSecurityConfigDefault; import org.thingsboard.server.common.data.id.DeviceProfileId; import org.thingsboard.server.common.data.page.PageData; import org.thingsboard.server.common.data.page.PageLink; @@ -1167,6 +1168,29 @@ public class DeviceProfileControllerTest extends AbstractControllerTest { assertThat(deviceProfile.getVersion()).isEqualTo(3); } + @Test + public void testGetLwm2mBootstrapSecurityInfo_BootstrapServer_Returns_ShortServerId_Null() throws Exception { + LwM2MServerSecurityConfigDefault result = doGet( + "/api/lwm2m/deviceProfile/bootstrap/true", + LwM2MServerSecurityConfigDefault.class + ); + Assert.assertNotNull(result); + Assert.assertTrue(result.isBootstrapServerIs()); + Assert.assertNull(result.getShortServerId()); + } + + @Test + public void testGetLwm2mBootstrapSecurityInfo_BootstrapServer_Returns_ShortServerId_1() throws Exception { + LwM2MServerSecurityConfigDefault result = doGet( + "/api/lwm2m/deviceProfile/bootstrap/false", + LwM2MServerSecurityConfigDefault.class + ); + Assert.assertNotNull(result); + Assert.assertFalse(result.isBootstrapServerIs()); + Assert.assertNotNull(result.getShortServerId()); + Assert.assertEquals(Integer.valueOf(123), result.getShortServerId()); + } + private DeviceProfile saveDeviceProfile(String name) { DeviceProfile deviceProfile = createDeviceProfile(name); return saveDeviceProfile(deviceProfile); diff --git a/common/data/src/main/java/org/thingsboard/server/common/data/device/profile/lwm2m/bootstrap/LwM2MServerSecurityConfig.java b/common/data/src/main/java/org/thingsboard/server/common/data/device/profile/lwm2m/bootstrap/LwM2MServerSecurityConfig.java index 7b98bae597..e2bdb9a6fd 100644 --- a/common/data/src/main/java/org/thingsboard/server/common/data/device/profile/lwm2m/bootstrap/LwM2MServerSecurityConfig.java +++ b/common/data/src/main/java/org/thingsboard/server/common/data/device/profile/lwm2m/bootstrap/LwM2MServerSecurityConfig.java @@ -13,7 +13,7 @@ public class LwM2MServerSecurityConfig implements Serializable { @Schema(description = "Server short Id. Used as link to associate server Object Instance. This identifier uniquely identifies each LwM2M Server configured for the LwM2M Client. " + "This Resource MUST be set when the Bootstrap-Server Resource has a value of 'false' and MUST be null when Bootstrap-Server is 'true'. " + - "The values ID:0 and ID:65535 values MUST NOT be used for identifying the LwM2M Server.", example = "1", accessMode = Schema.AccessMode.READ_ONLY) + "The values 0 and 65535 MUST NOT be used for identifying the LwM2M Server.", example = "1", accessMode = Schema.AccessMode.READ_ONLY) protected Integer shortServerId; /** Security -> ObjectId = 0 'LWM2M Security' */ @Schema(description = "Is Bootstrap Server or Lwm2m Server. " + diff --git a/dao/src/test/java/org/thingsboard/server/dao/service/validator/DeviceProfileDataValidatorTest.java b/dao/src/test/java/org/thingsboard/server/dao/service/validator/DeviceProfileDataValidatorTest.java index 3a4fa13281..2231b52d2e 100644 --- a/dao/src/test/java/org/thingsboard/server/dao/service/validator/DeviceProfileDataValidatorTest.java +++ b/dao/src/test/java/org/thingsboard/server/dao/service/validator/DeviceProfileDataValidatorTest.java @@ -220,7 +220,7 @@ class DeviceProfileDataValidatorTest { (Lwm2mDeviceProfileTransportConfiguration) deviceProfile.getProfileData().getTransportConfiguration(); return transportConfig.getBootstrap().stream() - .filter(credential -> ((NoSecLwM2MBootstrapServerCredential)credential).isBootstrapServerIs()) + .filter(credential -> ((AbstractLwM2MBootstrapServerCredential)credential).isBootstrapServerIs()) .findFirst() .orElseThrow(() -> new AssertionError("Bootstrap server not found in profile")); } @@ -231,7 +231,7 @@ class DeviceProfileDataValidatorTest { validator.validateDataImpl(tenantId, deviceProfile); verify(validator).validateString("Device profile name", deviceProfile.getName()); LwM2MBootstrapServerCredential bsCredential = getBootstrapCredential(deviceProfile); - assertThat(((NoSecLwM2MBootstrapServerCredential)bsCredential).getShortServerId()); + assertThat(((AbstractLwM2MBootstrapServerCredential) bsCredential).getShortServerId()).isNull(); } } From c410558dcaa7ef4a793ad7ee11c2c1087cb2e366 Mon Sep 17 00:00:00 2001 From: dshvaika Date: Thu, 17 Sep 2026 15:29:46 +0300 Subject: [PATCH 063/159] fix(iot-hub): arm the popup's Enter flag only where a keyup is coming The flag was set by any user selection, but only the keyboard leaves a second half to deal with: the trigger acts on keydown, the field's own handler on keyup, and preventDefault on the first does not stop the second. A pointer selection is finished when it returns, so the flag stayed set with nothing to consume it, and the next onSearch took the early return - click a result, close the detail dialog, press the magnifier, and the search page did not open. The magnifier is the plain case because it calls onSearch with no keystroke at all; Enter in the field does the same once the dialog restores focus there. It is armed from the trigger's activeOption now, which is readable only at that moment - the trigger holds it while it calls _selectViaInteraction and clears it on the next line of its own handler - and which a pointer never sets. Focusing the field and clearing it drop the flag as well, which covers the one pointer selection that can still arm it: arrowing to a row and then clicking a different one. --- .../pages/iot-hub/iot-hub-home.component.ts | 22 ++++++++++++------- 1 file changed, 14 insertions(+), 8 deletions(-) diff --git a/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-home.component.ts b/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-home.component.ts index 4efb672e33..cf242faeb3 100644 --- a/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-home.component.ts +++ b/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-home.component.ts @@ -225,6 +225,7 @@ export class TbIotHubHomeComponent implements OnInit, OnDestroy { } onSearchFocus(): void { + this.enterHandledByRow = false; if (!this.searchLoaded) { this.searchLoading = true; this.searchSubject.next(this.searchText || ''); @@ -236,6 +237,7 @@ export class TbIotHubHomeComponent implements OnInit, OnDestroy { }; clearSearch(): void { + this.enterHandledByRow = false; this.searchText = ''; this.searchSubject.next(''); this.searchInputRef?.nativeElement?.focus(); @@ -244,26 +246,30 @@ export class TbIotHubHomeComponent implements OnInit, OnDestroy { /** * Gate on every row's selection: false for the panel's own bookkeeping, true when the user - * picked the row - and then it records that this keystroke has been dealt with. + * picked the row - and then it records whether a keyup is still coming for it. * * One Enter reaches two handlers. The autocomplete trigger acts on keydown, the field's own - * handler on keyup, and preventDefault on the first does not stop the second. The trigger's - * activeOption cannot tell them apart either: it clears it inside that same keydown, so by - * keyup it reads empty whether or not a row acted. The row that acted says so instead, which - * does not depend on the order the two handlers run in. + * handler on keyup, and preventDefault on the first does not stop the second. Only the + * keyboard leaves that second half to deal with, so only the keyboard arms the flag: a pointer + * selection is finished when it returns, and a flag left standing there would swallow the next + * onSearch - which the magnifier button can raise with no keystroke at all. + * + * activeOption is what tells the two apart, and it is readable only here: the trigger holds it + * while it calls _selectViaInteraction and clears it on the next line of its own handler, so by + * keyup it reads empty either way. A pointer never sets it. */ rowSelectedByUser(event: MatOptionSelectionChange): boolean { if (!event.isUserInput) { return false; } - this.enterHandledByRow = true; + this.enterHandledByRow = !!this.searchAutoTrigger?.activeOption; return true; } /** * Enter in the field opens the search page, unless a row has just acted on this same press. - * The flag is also cleared on input, since a pointer selection sets it with no keyup to follow - * and would otherwise swallow the next Enter. + * Every path that re-enters the field clears the flag too, so nothing survives the keystroke + * it belongs to - including an arrow-then-click, the one selection that arms it by pointer. */ onSearch(): void { if (this.enterHandledByRow) { From 73fdbdcd1576a2514c18f643edeebecbc77b72de Mon Sep 17 00:00:00 2001 From: nickAS21 Date: Thu, 17 Sep 2026 20:00:01 +0300 Subject: [PATCH 064/159] lwm2m: fix bootstrap-short-server-id = null - comments 5 --- application/src/main/resources/thingsboard.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/application/src/main/resources/thingsboard.yml b/application/src/main/resources/thingsboard.yml index 287d88a00d..05586b01f8 100644 --- a/application/src/main/resources/thingsboard.yml +++ b/application/src/main/resources/thingsboard.yml @@ -1333,7 +1333,7 @@ transport: bootstrap: # Enable/disable Bootstrap Server enabled: "${LWM2M_ENABLED_BS:true}" - # Short Server ID for Bootstrap Server is not applicable according to OMA LwM2M spec (Object 0 Resource 10 must be omitted/null); left empty by default, and any provided value is normalized to null by the validator upon save. + # Deprecated: Short Server ID is not applicable for Bootstrap Server per OMA LwM2M spec (Object 0 Resource 10 must be omitted/null); setting this property has no effect and any value is ignored and forced to null. id: "${LWM2M_SERVER_ID_BS:}" # LwM2M bootstrap server bind address. Bind to all interfaces by default bind_address: "${LWM2M_BS_BIND_ADDRESS:0.0.0.0}" From 5c5492793b8860b6a517b59569cbb48a648be13c Mon Sep 17 00:00:00 2001 From: nickAS21 Date: Thu, 17 Sep 2026 21:10:54 +0300 Subject: [PATCH 065/159] lwm2m: fix bootstrap-short-server-id = null - comments 6 --- .../service/lwm2m/LwM2MServiceImpl.java | 9 +- .../LwM2MServiceImplInvalidConfigTest.java | 95 +++++++++++++++++++ 2 files changed, 101 insertions(+), 3 deletions(-) create mode 100644 application/src/test/java/org/thingsboard/server/controller/LwM2MServiceImplInvalidConfigTest.java diff --git a/application/src/main/java/org/thingsboard/server/service/lwm2m/LwM2MServiceImpl.java b/application/src/main/java/org/thingsboard/server/service/lwm2m/LwM2MServiceImpl.java index 33d0487fdd..9071babb45 100644 --- a/application/src/main/java/org/thingsboard/server/service/lwm2m/LwM2MServiceImpl.java +++ b/application/src/main/java/org/thingsboard/server/service/lwm2m/LwM2MServiceImpl.java @@ -14,6 +14,8 @@ import org.thingsboard.server.transport.lwm2m.config.LwM2MTransportBootstrapConf import org.thingsboard.server.transport.lwm2m.config.LwM2MTransportServerConfig; import java.util.Optional; +import static org.thingsboard.server.common.data.device.credentials.lwm2m.Lwm2mServerIdentifier.LWM2M_SERVER_MAX; +import static org.thingsboard.server.common.data.device.credentials.lwm2m.Lwm2mServerIdentifier.PRIMARY_LWM2M_SERVER; @Slf4j @Service @@ -49,9 +51,10 @@ public class LwM2MServiceImpl implements LwM2MService { } else { Integer configId = bsServerConfig.getId(); if (configId == null || configId <= 0 || configId >= 65535) { - log.warn("Invalid Short Server ID [{}] for LwM2M Server entry: defaulting to [1] for backward compatibility (ThingsBoard <= 4.2).", - configId); - configId = 1; + throw new IllegalArgumentException(String.format( + "Invalid LwM2M Server ShortServerId [%s] in configuration (transport.lwm2m.server.id). Must be in range [%d - %d]!", + configId, PRIMARY_LWM2M_SERVER.getId(), LWM2M_SERVER_MAX.getId() + )); } bsServ.setShortServerId(configId); } diff --git a/application/src/test/java/org/thingsboard/server/controller/LwM2MServiceImplInvalidConfigTest.java b/application/src/test/java/org/thingsboard/server/controller/LwM2MServiceImplInvalidConfigTest.java new file mode 100644 index 0000000000..7273e2c558 --- /dev/null +++ b/application/src/test/java/org/thingsboard/server/controller/LwM2MServiceImplInvalidConfigTest.java @@ -0,0 +1,95 @@ +// SPDX-FileCopyrightText: Copyright The Thingsboard Authors +// SPDX-License-Identifier: Apache-2.0 +package org.thingsboard.server.controller; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; +import org.thingsboard.server.common.data.device.profile.lwm2m.bootstrap.LwM2MServerSecurityConfigDefault; +import org.thingsboard.server.service.lwm2m.LwM2MServiceImpl; +import org.thingsboard.server.transport.lwm2m.config.LwM2MTransportBootstrapConfig; +import org.thingsboard.server.transport.lwm2m.config.LwM2MTransportServerConfig; + +import java.util.Optional; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.BDDMockito.given; +import static org.thingsboard.server.common.data.device.credentials.lwm2m.Lwm2mServerIdentifier.NOT_USED_IDENTIFYING_LWM2M_SERVER_MAX; +import static org.thingsboard.server.common.data.device.credentials.lwm2m.Lwm2mServerIdentifier.PRIMARY_LWM2M_SERVER; + +@ExtendWith(MockitoExtension.class) +public class LwM2MServiceImplInvalidConfigTest { + + @Mock + private LwM2MTransportServerConfig serverConfig; + + @Mock + private LwM2MTransportBootstrapConfig bootstrapConfig; + + private LwM2MServiceImpl lwM2MService; + + @BeforeEach + void setUp() { + lwM2MService = new LwM2MServiceImpl(serverConfig, Optional.of(bootstrapConfig)); + } + + @Test + void testGetServerSecurityInfo_BsServerWithNonEmptyId_ClearsToNullAndLogsWarn() { + given(bootstrapConfig.getId()).willReturn(111); + given(bootstrapConfig.getHost()).willReturn("0.0.0.0"); + given(bootstrapConfig.getPort()).willReturn(5687); + + LwM2MServerSecurityConfigDefault result = lwM2MService.getServerSecurityInfo(true); + + assertThat(result).isNotNull(); + assertThat(result.isBootstrapServerIs()).isTrue(); + assertThat(result.getShortServerId()).isNull(); + } + + @Test + void testGetServerSecurityInfo_DmServerWithValidId_Success() { + Integer validShortServerId = 123; + given(serverConfig.getId()).willReturn(validShortServerId); + given(serverConfig.getHost()).willReturn("0.0.0.0"); + given(serverConfig.getPort()).willReturn(5685); + + LwM2MServerSecurityConfigDefault result = lwM2MService.getServerSecurityInfo(false); + + assertThat(result).isNotNull(); + assertThat(result.isBootstrapServerIs()).isFalse(); + assertThat(result.getShortServerId()).isEqualTo(validShortServerId); + } + + @Test + void testGetServerSecurityInfo_DmServer_Less_PRIMARY_LWM2M_SERVER_ThrowsIllegalArgumentException() { + Integer shortServerId = PRIMARY_LWM2M_SERVER.getId() - 1; + given(serverConfig.getId()).willReturn(shortServerId); + + assertThatThrownBy(() -> lwM2MService.getServerSecurityInfo(false)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("Invalid LwM2M Server ShortServerId [" + shortServerId + "] in configuration (transport.lwm2m.server.id). Must be in range [1 - 65534]!"); + } + + @Test + void testGetServerSecurityInfo_DmServer_NOT_USED_IDENTIFYING_LWM2M_SERVER_MAX_ThrowsIllegalArgumentException() { + Integer shortServerId = NOT_USED_IDENTIFYING_LWM2M_SERVER_MAX.getId(); + given(serverConfig.getId()).willReturn(shortServerId); + + assertThatThrownBy(() -> lwM2MService.getServerSecurityInfo(false)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("Invalid LwM2M Server ShortServerId [" + shortServerId + "] in configuration (transport.lwm2m.server.id). Must be in range [1 - 65534]!"); + } + + @Test + void testGetServerSecurityInfo_DmServerWithNullId_ThrowsIllegalArgumentException() { + Integer shortServerId = null; + given(serverConfig.getId()).willReturn(shortServerId); + + assertThatThrownBy(() -> lwM2MService.getServerSecurityInfo(false)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("Invalid LwM2M Server ShortServerId [" + shortServerId + "] in configuration (transport.lwm2m.server.id). Must be in range [1 - 65534]!"); + } +} \ No newline at end of file From 150c2a5fc6b5ac8d3b0518542a4420463450d634 Mon Sep 17 00:00:00 2001 From: nickAS21 Date: Thu, 17 Sep 2026 21:17:33 +0300 Subject: [PATCH 066/159] lwm2m: fix bootstrap-short-server-id = null - comments 7 --- .../dao/service/validator/DeviceProfileDataValidator.java | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/dao/src/main/java/org/thingsboard/server/dao/service/validator/DeviceProfileDataValidator.java b/dao/src/main/java/org/thingsboard/server/dao/service/validator/DeviceProfileDataValidator.java index 938b15616b..aba492ef07 100644 --- a/dao/src/main/java/org/thingsboard/server/dao/service/validator/DeviceProfileDataValidator.java +++ b/dao/src/main/java/org/thingsboard/server/dao/service/validator/DeviceProfileDataValidator.java @@ -169,7 +169,7 @@ public class DeviceProfileDataValidator extends AbstractHasOtaPackageValidator lwM2MBootstrapServersConfigurations = ((Lwm2mDeviceProfileTransportConfiguration) transportConfiguration).getBootstrap(); if (lwM2MBootstrapServersConfigurations != null) { validateLwm2mServersConfigOfBootstrapForClient(lwM2MBootstrapServersConfigurations, - ((Lwm2mDeviceProfileTransportConfiguration) transportConfiguration).isBootstrapServerUpdateEnable(), deviceProfile.getName(), tenantId); + ((Lwm2mDeviceProfileTransportConfiguration) transportConfiguration).isBootstrapServerUpdateEnable(), deviceProfile); for (LwM2MBootstrapServerCredential bootstrapServerCredential : lwM2MBootstrapServersConfigurations) { validateLwm2mServersCredentialOfBootstrapForClient(bootstrapServerCredential); } @@ -348,7 +348,7 @@ public class DeviceProfileDataValidator extends AbstractHasOtaPackageValidator lwM2MBootstrapServersConfigurations, - boolean isBootstrapServerUpdateEnable, String deviceProfileName, TenantId tenantId) { + boolean isBootstrapServerUpdateEnable, DeviceProfile deviceProfile) { Set uris = new HashSet<>(); Set shortServerIds = new HashSet<>(); boolean hasBootstrapServer = false; @@ -368,7 +368,7 @@ public class DeviceProfileDataValidator extends AbstractHasOtaPackageValidator Date: Thu, 17 Sep 2026 21:39:24 +0300 Subject: [PATCH 067/159] lwm2m: fix bootstrap-short-server-id = null - comments 8 --- application/src/main/resources/thingsboard.yml | 2 +- transport/lwm2m/src/main/resources/tb-lwm2m-transport.yml | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/application/src/main/resources/thingsboard.yml b/application/src/main/resources/thingsboard.yml index 05586b01f8..85ad4b1806 100644 --- a/application/src/main/resources/thingsboard.yml +++ b/application/src/main/resources/thingsboard.yml @@ -1333,7 +1333,7 @@ transport: bootstrap: # Enable/disable Bootstrap Server enabled: "${LWM2M_ENABLED_BS:true}" - # Deprecated: Short Server ID is not applicable for Bootstrap Server per OMA LwM2M spec (Object 0 Resource 10 must be omitted/null); setting this property has no effect and any value is ignored and forced to null. + # Deprecated: Short Server ID is not applicable for Bootstrap Server per OMA spec (Object 0 Resource 10) and is forced to null. id: "${LWM2M_SERVER_ID_BS:}" # LwM2M bootstrap server bind address. Bind to all interfaces by default bind_address: "${LWM2M_BS_BIND_ADDRESS:0.0.0.0}" diff --git a/transport/lwm2m/src/main/resources/tb-lwm2m-transport.yml b/transport/lwm2m/src/main/resources/tb-lwm2m-transport.yml index 3719947dac..b9c22ad5f2 100644 --- a/transport/lwm2m/src/main/resources/tb-lwm2m-transport.yml +++ b/transport/lwm2m/src/main/resources/tb-lwm2m-transport.yml @@ -216,7 +216,7 @@ transport: bootstrap: # Enable/disable Bootstrap Server enabled: "${LWM2M_ENABLED_BS:true}" - # Short Server ID for Bootstrap Server is not applicable according to OMA LwM2M spec (Object 0 Resource 10 must be omitted/null); left empty by default, and any provided value is normalized to null by the validator upon save. + # Deprecated: Short Server ID is not applicable for Bootstrap Server per OMA spec (Object 0 Resource 10) and is forced to null. id: "${LWM2M_SERVER_ID_BS:}" # LwM2M bootstrap server bind address. Bind to all interfaces by default bind_address: "${LWM2M_BS_BIND_ADDRESS:0.0.0.0}" From 3f37cb28b3e5caa1049bf2fae9f0bc708d1a4643 Mon Sep 17 00:00:00 2001 From: nickAS21 Date: Fri, 18 Sep 2026 11:16:29 +0300 Subject: [PATCH 068/159] lwm2m: fix bootstrap-short-server-id = null - comments 9 --- .../service/lwm2m/LwM2MServiceImpl.java | 11 ++++--- .../src/main/resources/thingsboard.yml | 2 +- .../LwM2MServiceImplInvalidConfigTest.java | 32 +++++++++++-------- .../config/LwM2MTransportServerConfig.java | 2 +- .../src/main/resources/tb-lwm2m-transport.yml | 2 +- 5 files changed, 27 insertions(+), 22 deletions(-) diff --git a/application/src/main/java/org/thingsboard/server/service/lwm2m/LwM2MServiceImpl.java b/application/src/main/java/org/thingsboard/server/service/lwm2m/LwM2MServiceImpl.java index 9071babb45..ae777fbff7 100644 --- a/application/src/main/java/org/thingsboard/server/service/lwm2m/LwM2MServiceImpl.java +++ b/application/src/main/java/org/thingsboard/server/service/lwm2m/LwM2MServiceImpl.java @@ -6,6 +6,7 @@ import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.apache.commons.codec.binary.Base64; import org.springframework.stereotype.Service; +import org.thingsboard.server.common.data.device.credentials.lwm2m.Lwm2mServerIdentifier; import org.thingsboard.server.common.data.device.profile.lwm2m.bootstrap.LwM2MServerSecurityConfigDefault; import org.thingsboard.server.common.transport.config.ssl.SslCredentials; import org.thingsboard.server.queue.util.TbCoreComponent; @@ -50,11 +51,11 @@ public class LwM2MServiceImpl implements LwM2MService { bsServ.setShortServerId(null); } else { Integer configId = bsServerConfig.getId(); - if (configId == null || configId <= 0 || configId >= 65535) { - throw new IllegalArgumentException(String.format( - "Invalid LwM2M Server ShortServerId [%s] in configuration (transport.lwm2m.server.id). Must be in range [%d - %d]!", - configId, PRIMARY_LWM2M_SERVER.getId(), LWM2M_SERVER_MAX.getId() - )); + if (Lwm2mServerIdentifier.isNotLwm2mServer(configId)) { + log.warn("Invalid LwM2M Server ShortServerId [{}] in configuration (transport.lwm2m.server.id). " + + "Must be in range [{} - {}]. Using [{}] instead.", + configId, PRIMARY_LWM2M_SERVER.getId(), LWM2M_SERVER_MAX.getId(), PRIMARY_LWM2M_SERVER.getId()); + configId = PRIMARY_LWM2M_SERVER.getId(); } bsServ.setShortServerId(configId); } diff --git a/application/src/main/resources/thingsboard.yml b/application/src/main/resources/thingsboard.yml index 85ad4b1806..beb29333ba 100644 --- a/application/src/main/resources/thingsboard.yml +++ b/application/src/main/resources/thingsboard.yml @@ -1291,7 +1291,7 @@ transport: #
  • A value that are > 4: MultiNodeConnectionIdGenerator is used
  • connection_id_length: "${LWM2M_DTLS_CONNECTION_ID_LENGTH:8}" server: - # LwM2M Server ID + # LwM2M Server Short Server ID [1 - 65534]: 0 and 65535 are reserved. An invalid or missing value is ignored and 1 is used instead. id: "${LWM2M_SERVER_ID:123}" # LwM2M server bind address. Bind to all interfaces by default bind_address: "${LWM2M_BIND_ADDRESS:0.0.0.0}" diff --git a/application/src/test/java/org/thingsboard/server/controller/LwM2MServiceImplInvalidConfigTest.java b/application/src/test/java/org/thingsboard/server/controller/LwM2MServiceImplInvalidConfigTest.java index 7273e2c558..6beeccb1af 100644 --- a/application/src/test/java/org/thingsboard/server/controller/LwM2MServiceImplInvalidConfigTest.java +++ b/application/src/test/java/org/thingsboard/server/controller/LwM2MServiceImplInvalidConfigTest.java @@ -15,7 +15,6 @@ import org.thingsboard.server.transport.lwm2m.config.LwM2MTransportServerConfig; import java.util.Optional; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.BDDMockito.given; import static org.thingsboard.server.common.data.device.credentials.lwm2m.Lwm2mServerIdentifier.NOT_USED_IDENTIFYING_LWM2M_SERVER_MAX; import static org.thingsboard.server.common.data.device.credentials.lwm2m.Lwm2mServerIdentifier.PRIMARY_LWM2M_SERVER; @@ -64,32 +63,37 @@ public class LwM2MServiceImplInvalidConfigTest { } @Test - void testGetServerSecurityInfo_DmServer_Less_PRIMARY_LWM2M_SERVER_ThrowsIllegalArgumentException() { + void testGetServerSecurityInfo_Server_Less_PRIMARY_LWM2M_SERVER_DefaultsToOneAndLogsWarn() { Integer shortServerId = PRIMARY_LWM2M_SERVER.getId() - 1; given(serverConfig.getId()).willReturn(shortServerId); - assertThatThrownBy(() -> lwM2MService.getServerSecurityInfo(false)) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("Invalid LwM2M Server ShortServerId [" + shortServerId + "] in configuration (transport.lwm2m.server.id). Must be in range [1 - 65534]!"); + LwM2MServerSecurityConfigDefault result = lwM2MService.getServerSecurityInfo(false); + + assertThat(result).isNotNull(); + assertThat(result.isBootstrapServerIs()).isFalse(); + assertThat(result.getShortServerId()).isEqualTo(PRIMARY_LWM2M_SERVER.getId()); } @Test - void testGetServerSecurityInfo_DmServer_NOT_USED_IDENTIFYING_LWM2M_SERVER_MAX_ThrowsIllegalArgumentException() { + void testGetServerSecurityInfo_Server_NOT_USED_IDENTIFYING_LWM2M_SERVER_MAX_DefaultsToOneAndLogsWarn() { Integer shortServerId = NOT_USED_IDENTIFYING_LWM2M_SERVER_MAX.getId(); given(serverConfig.getId()).willReturn(shortServerId); - assertThatThrownBy(() -> lwM2MService.getServerSecurityInfo(false)) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("Invalid LwM2M Server ShortServerId [" + shortServerId + "] in configuration (transport.lwm2m.server.id). Must be in range [1 - 65534]!"); + LwM2MServerSecurityConfigDefault result = lwM2MService.getServerSecurityInfo(false); + + assertThat(result).isNotNull(); + assertThat(result.isBootstrapServerIs()).isFalse(); + assertThat(result.getShortServerId()).isEqualTo(PRIMARY_LWM2M_SERVER.getId()); } @Test - void testGetServerSecurityInfo_DmServerWithNullId_ThrowsIllegalArgumentException() { + void testGetServerSecurityInfo_ServerWithNullId_DefaultsToOneAndLogsWarn() { Integer shortServerId = null; given(serverConfig.getId()).willReturn(shortServerId); - assertThatThrownBy(() -> lwM2MService.getServerSecurityInfo(false)) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("Invalid LwM2M Server ShortServerId [" + shortServerId + "] in configuration (transport.lwm2m.server.id). Must be in range [1 - 65534]!"); - } + LwM2MServerSecurityConfigDefault result = lwM2MService.getServerSecurityInfo(false); + + assertThat(result).isNotNull(); + assertThat(result.isBootstrapServerIs()).isFalse(); + assertThat(result.getShortServerId()).isEqualTo(PRIMARY_LWM2M_SERVER.getId()); } } \ No newline at end of file diff --git a/common/transport/lwm2m/src/main/java/org/thingsboard/server/transport/lwm2m/config/LwM2MTransportServerConfig.java b/common/transport/lwm2m/src/main/java/org/thingsboard/server/transport/lwm2m/config/LwM2MTransportServerConfig.java index 15f5a03555..6f2a510783 100644 --- a/common/transport/lwm2m/src/main/java/org/thingsboard/server/transport/lwm2m/config/LwM2MTransportServerConfig.java +++ b/common/transport/lwm2m/src/main/java/org/thingsboard/server/transport/lwm2m/config/LwM2MTransportServerConfig.java @@ -81,7 +81,7 @@ public class LwM2MTransportServerConfig implements LwM2MSecureServerConfig { private int cleanPeriodInSec; @Getter - @Value("${transport.lwm2m.server.id:}") + @Value("${transport.lwm2m.server.id:123}") private Integer id; @Getter diff --git a/transport/lwm2m/src/main/resources/tb-lwm2m-transport.yml b/transport/lwm2m/src/main/resources/tb-lwm2m-transport.yml index b9c22ad5f2..c7cf5100db 100644 --- a/transport/lwm2m/src/main/resources/tb-lwm2m-transport.yml +++ b/transport/lwm2m/src/main/resources/tb-lwm2m-transport.yml @@ -174,7 +174,7 @@ transport: #
  • A value that are > 4: MultiNodeConnectionIdGenerator is used
  • connection_id_length: "${LWM2M_DTLS_CONNECTION_ID_LENGTH:8}" server: - # LwM2M Server ID + # LwM2M Server Short Server ID [1 - 65534]: 0 and 65535 are reserved. An invalid or missing value is ignored and 1 is used instead. id: "${LWM2M_SERVER_ID:123}" # LwM2M server bind address. Bind to all interfaces by default bind_address: "${LWM2M_BIND_ADDRESS:0.0.0.0}" From a9e8f0fb3c23213d2b0d6cdde5a8c085a04fdca0 Mon Sep 17 00:00:00 2001 From: nickAS21 Date: Fri, 18 Sep 2026 16:14:45 +0300 Subject: [PATCH 069/159] lwm2m: fix bootstrap-short-server-id = null - comments 10 --- .../src/main/resources/thingsboard.yml | 2 +- .../LwM2MServiceImplInvalidConfigTest.java | 48 +++++++++++-------- .../src/main/resources/tb-lwm2m-transport.yml | 2 +- 3 files changed, 30 insertions(+), 22 deletions(-) diff --git a/application/src/main/resources/thingsboard.yml b/application/src/main/resources/thingsboard.yml index beb29333ba..fe454447c5 100644 --- a/application/src/main/resources/thingsboard.yml +++ b/application/src/main/resources/thingsboard.yml @@ -1291,7 +1291,7 @@ transport: #
  • A value that are > 4: MultiNodeConnectionIdGenerator is used
  • connection_id_length: "${LWM2M_DTLS_CONNECTION_ID_LENGTH:8}" server: - # LwM2M Server Short Server ID [1 - 65534]: 0 and 65535 are reserved. An invalid or missing value is ignored and 1 is used instead. + # LwM2M Server Short Server ID. Valid range [1 - 65534]; 0 and 65535 are reserved. Default: 123. id: "${LWM2M_SERVER_ID:123}" # LwM2M server bind address. Bind to all interfaces by default bind_address: "${LWM2M_BIND_ADDRESS:0.0.0.0}" diff --git a/application/src/test/java/org/thingsboard/server/controller/LwM2MServiceImplInvalidConfigTest.java b/application/src/test/java/org/thingsboard/server/controller/LwM2MServiceImplInvalidConfigTest.java index 6beeccb1af..0951f71b40 100644 --- a/application/src/test/java/org/thingsboard/server/controller/LwM2MServiceImplInvalidConfigTest.java +++ b/application/src/test/java/org/thingsboard/server/controller/LwM2MServiceImplInvalidConfigTest.java @@ -16,6 +16,7 @@ import java.util.Optional; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.BDDMockito.given; +import static org.thingsboard.server.common.data.device.credentials.lwm2m.Lwm2mServerIdentifier.LWM2M_SERVER_MAX; import static org.thingsboard.server.common.data.device.credentials.lwm2m.Lwm2mServerIdentifier.NOT_USED_IDENTIFYING_LWM2M_SERVER_MAX; import static org.thingsboard.server.common.data.device.credentials.lwm2m.Lwm2mServerIdentifier.PRIMARY_LWM2M_SERVER; @@ -38,11 +39,7 @@ public class LwM2MServiceImplInvalidConfigTest { @Test void testGetServerSecurityInfo_BsServerWithNonEmptyId_ClearsToNullAndLogsWarn() { given(bootstrapConfig.getId()).willReturn(111); - given(bootstrapConfig.getHost()).willReturn("0.0.0.0"); - given(bootstrapConfig.getPort()).willReturn(5687); - LwM2MServerSecurityConfigDefault result = lwM2MService.getServerSecurityInfo(true); - assertThat(result).isNotNull(); assertThat(result.isBootstrapServerIs()).isTrue(); assertThat(result.getShortServerId()).isNull(); @@ -52,11 +49,27 @@ public class LwM2MServiceImplInvalidConfigTest { void testGetServerSecurityInfo_DmServerWithValidId_Success() { Integer validShortServerId = 123; given(serverConfig.getId()).willReturn(validShortServerId); - given(serverConfig.getHost()).willReturn("0.0.0.0"); - given(serverConfig.getPort()).willReturn(5685); + LwM2MServerSecurityConfigDefault result = lwM2MService.getServerSecurityInfo(false); + assertThat(result).isNotNull(); + assertThat(result.isBootstrapServerIs()).isFalse(); + assertThat(result.getShortServerId()).isEqualTo(validShortServerId); + } + @Test + void testGetServerSecurityInfo_DmServerWithMinValidId_ReturnedUnchanged() { + Integer validShortServerId = PRIMARY_LWM2M_SERVER.getId(); + given(serverConfig.getId()).willReturn(validShortServerId); LwM2MServerSecurityConfigDefault result = lwM2MService.getServerSecurityInfo(false); + assertThat(result).isNotNull(); + assertThat(result.isBootstrapServerIs()).isFalse(); + assertThat(result.getShortServerId()).isEqualTo(validShortServerId); + } + @Test + void testGetServerSecurityInfo_DmServerWithMaxValidId_ReturnedUnchanged() { + Integer validShortServerId = LWM2M_SERVER_MAX.getId(); + given(serverConfig.getId()).willReturn(validShortServerId); + LwM2MServerSecurityConfigDefault result = lwM2MService.getServerSecurityInfo(false); assertThat(result).isNotNull(); assertThat(result.isBootstrapServerIs()).isFalse(); assertThat(result.getShortServerId()).isEqualTo(validShortServerId); @@ -64,11 +77,9 @@ public class LwM2MServiceImplInvalidConfigTest { @Test void testGetServerSecurityInfo_Server_Less_PRIMARY_LWM2M_SERVER_DefaultsToOneAndLogsWarn() { - Integer shortServerId = PRIMARY_LWM2M_SERVER.getId() - 1; - given(serverConfig.getId()).willReturn(shortServerId); - + Integer inValidShortServerId = PRIMARY_LWM2M_SERVER.getId() - 1; + given(serverConfig.getId()).willReturn(inValidShortServerId); LwM2MServerSecurityConfigDefault result = lwM2MService.getServerSecurityInfo(false); - assertThat(result).isNotNull(); assertThat(result.isBootstrapServerIs()).isFalse(); assertThat(result.getShortServerId()).isEqualTo(PRIMARY_LWM2M_SERVER.getId()); @@ -76,11 +87,9 @@ public class LwM2MServiceImplInvalidConfigTest { @Test void testGetServerSecurityInfo_Server_NOT_USED_IDENTIFYING_LWM2M_SERVER_MAX_DefaultsToOneAndLogsWarn() { - Integer shortServerId = NOT_USED_IDENTIFYING_LWM2M_SERVER_MAX.getId(); - given(serverConfig.getId()).willReturn(shortServerId); - + Integer inValidShortServerId = NOT_USED_IDENTIFYING_LWM2M_SERVER_MAX.getId(); + given(serverConfig.getId()).willReturn(inValidShortServerId); LwM2MServerSecurityConfigDefault result = lwM2MService.getServerSecurityInfo(false); - assertThat(result).isNotNull(); assertThat(result.isBootstrapServerIs()).isFalse(); assertThat(result.getShortServerId()).isEqualTo(PRIMARY_LWM2M_SERVER.getId()); @@ -88,12 +97,11 @@ public class LwM2MServiceImplInvalidConfigTest { @Test void testGetServerSecurityInfo_ServerWithNullId_DefaultsToOneAndLogsWarn() { - Integer shortServerId = null; - given(serverConfig.getId()).willReturn(shortServerId); - + Integer inValidShortServerId = null; + given(serverConfig.getId()).willReturn(inValidShortServerId); LwM2MServerSecurityConfigDefault result = lwM2MService.getServerSecurityInfo(false); - assertThat(result).isNotNull(); assertThat(result.isBootstrapServerIs()).isFalse(); - assertThat(result.getShortServerId()).isEqualTo(PRIMARY_LWM2M_SERVER.getId()); } -} \ No newline at end of file + assertThat(result.getShortServerId()).isEqualTo(PRIMARY_LWM2M_SERVER.getId()); + } +} diff --git a/transport/lwm2m/src/main/resources/tb-lwm2m-transport.yml b/transport/lwm2m/src/main/resources/tb-lwm2m-transport.yml index c7cf5100db..4380cf3fb1 100644 --- a/transport/lwm2m/src/main/resources/tb-lwm2m-transport.yml +++ b/transport/lwm2m/src/main/resources/tb-lwm2m-transport.yml @@ -174,7 +174,7 @@ transport: #
  • A value that are > 4: MultiNodeConnectionIdGenerator is used
  • connection_id_length: "${LWM2M_DTLS_CONNECTION_ID_LENGTH:8}" server: - # LwM2M Server Short Server ID [1 - 65534]: 0 and 65535 are reserved. An invalid or missing value is ignored and 1 is used instead. + # LwM2M Server Short Server ID. Valid range [1 - 65534]; 0 and 65535 are reserved. Default: 123. id: "${LWM2M_SERVER_ID:123}" # LwM2M server bind address. Bind to all interfaces by default bind_address: "${LWM2M_BIND_ADDRESS:0.0.0.0}" From 91025b11f1e710919020246182ed42007058dd5e Mon Sep 17 00:00:00 2001 From: nickAS21 Date: Fri, 18 Sep 2026 18:34:24 +0300 Subject: [PATCH 070/159] lwm2m: fix bootstrap-short-server-id = null - comments 11 --- ...plInvalidConfigTest.java => LwM2MServiceImplConfigTest.java} | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) rename application/src/test/java/org/thingsboard/server/controller/{LwM2MServiceImplInvalidConfigTest.java => LwM2MServiceImplConfigTest.java} (99%) diff --git a/application/src/test/java/org/thingsboard/server/controller/LwM2MServiceImplInvalidConfigTest.java b/application/src/test/java/org/thingsboard/server/controller/LwM2MServiceImplConfigTest.java similarity index 99% rename from application/src/test/java/org/thingsboard/server/controller/LwM2MServiceImplInvalidConfigTest.java rename to application/src/test/java/org/thingsboard/server/controller/LwM2MServiceImplConfigTest.java index 0951f71b40..30afb0e667 100644 --- a/application/src/test/java/org/thingsboard/server/controller/LwM2MServiceImplInvalidConfigTest.java +++ b/application/src/test/java/org/thingsboard/server/controller/LwM2MServiceImplConfigTest.java @@ -21,7 +21,7 @@ import static org.thingsboard.server.common.data.device.credentials.lwm2m.Lwm2mS import static org.thingsboard.server.common.data.device.credentials.lwm2m.Lwm2mServerIdentifier.PRIMARY_LWM2M_SERVER; @ExtendWith(MockitoExtension.class) -public class LwM2MServiceImplInvalidConfigTest { +public class LwM2MServiceImplConfigTest { @Mock private LwM2MTransportServerConfig serverConfig; From 191d7798143120f11e0c44e375d0c9d8099d7028 Mon Sep 17 00:00:00 2001 From: Dmytro Pinkevych <49400214+pinkevmladchy@users.noreply.github.com> Date: Mon, 21 Sep 2026 18:39:14 +0300 Subject: [PATCH 071/159] Keep IoT Hub markdown table columns from overlapping (#16138) * Keep IoT Hub markdown table columns from overlapping Long unbreakable values in solution instruction tables (logins, e-mails, passwords) overflowed their own column and ran under the copy icon. Cells now break such tokens with overflow-wrap: anywhere, cells holding a copy button reserve room for the icon, and the table is sized by its content instead of splitting the width equally between all columns. * Let preformatted content in markdown table cells wrap With auto layout a cell holding a preformatted block keeps the whole line as its min-content width, which the table cannot shrink below: in a 396px host the table measured 701px and a host that hides horizontal overflow, such as the item detail dialog's .dlg-body, cut the overflow off with no way to scroll to it. Relaxing the block and the code inside it to pre-wrap lets the cell shrink with the table. * Derive the copy icon space in table cells from the icon geometry The 44px reserved on the right of a copy-code cell was derived by hand from the copy icon chip declared 45 lines above it, so nudging the chip's width or offset would silently put the cell text back under the icon. Both numbers now live in $copy-icon-width and $copy-icon-offset, used by the chip itself and by the reservation, which is written as width plus the gap on either side. --- .../iot-hub/iot-hub-markdown.component.scss | 40 +++++++++++++++---- 1 file changed, 32 insertions(+), 8 deletions(-) diff --git a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-markdown.component.scss b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-markdown.component.scss index 2a946348ad..c25c67e729 100644 --- a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-markdown.component.scss +++ b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-markdown.component.scss @@ -3,6 +3,10 @@ $text-color: rgba(0,0,0,0.76); $link-color: #2a7dec; $copy-button-color: #2a7dec; +// Geometry of the copy icon chip, shared by the chip itself and by the space table +// cells reserve for it, so the two cannot drift apart. +$copy-icon-width: 38px; +$copy-icon-offset: 3px; $code-block-border-color: rgba(42, 125, 236, .2); $code-default-color: #212529; @@ -169,10 +173,10 @@ $gallery-border-hover-color: #2a7dec; div { background-color: #fff; position: absolute; - width: 38px; + width: $copy-icon-width; height: 28px; - top: 3px; - right: 3px; + top: $copy-icon-offset; + right: $copy-icon-offset; padding: 8px 10px 0; img { @@ -204,9 +208,30 @@ $gallery-border-hover-color: #2a7dec; } th, td { + // Long unbreakable tokens (logins, e-mails, passwords) must never overflow their + // own column. `anywhere` also drops the cell min-content width down to a single + // character, so auto layout can always squeeze the table into the available + // width instead of overflowing (and getting clipped by `overflow: hidden`). + overflow-wrap: break-word; // fallback for engines without `anywhere` + overflow-wrap: anywhere; + + // Text is not the only thing that can outgrow a column: a preformatted block keeps + // its whole line as min-content width, which auto layout cannot shrink, so the table + // would push past its container and get cut off by a host that hides horizontal + // overflow (iot-hub-item-detail-dialog's .dlg-body). Wrap it inside the cell instead. + // Prism sets `white-space: pre` on both the block and the code inside it, so both + // have to be relaxed for the cell to shrink. + pre, pre > code { + white-space: pre-wrap; + } + div.code-wrapper { display: inline-block; width: 100%; + // Reserve room for the absolutely positioned copy icon, plus the same gap on its + // far side, so the cell text does not run underneath it and the reservation + // follows the chip if its geometry ever changes. + padding-right: $copy-icon-width + 2 * $copy-icon-offset; button.clipboard-btn { top: -6px; @@ -275,11 +300,10 @@ $gallery-border-hover-color: #2a7dec; margin-top: 20px; margin-bottom: 20px; overflow: hidden; - table-layout: fixed; - - &.auto { - table-layout: auto; - } + // Columns are sized to their content: with fixed layout every column got the + // same width, so cells with long values (e-mails, logins, tokens) had to wrap + // mid-word while short columns kept a lot of unused space. + table-layout: auto; > thead { background-color: $table-header-background-color; From 89e2e086fb05980208b62d630e0737bce58c1263 Mon Sep 17 00:00:00 2001 From: Dmytro Pinkevych <49400214+pinkevmladchy@users.noreply.github.com> Date: Mon, 21 Sep 2026 18:39:29 +0300 Subject: [PATCH 072/159] Refresh the installed items count after an install, update or delete (#16139) * Refresh the installed items count after an install, update or delete The IoT Hub items page loaded its installed-items counter once, so installing, updating or deleting an item from the embedded browse list left the counter showing a stale number until the page was reloaded. The browse component now emits installedItemsChanged whenever it refreshes its own installed-items state, and the page reloads the counter on that event. * Refresh the installed items count from the device wizard and deep links too The device install wizard registers the install as soon as the entity steps finish, but closing it with the header X or with Cancel on a still-pending later step resolved to false, so the caller never reloaded. It now reports 'installed' once the server has the installed item, whichever way it is closed. The deep-linked item dialog is opened by the items page itself, so its outcome was discarded. It now refreshes the browse grid, which in turn announces the new count. --- .../device-install-dialog.component.ts | 9 ++++++++- .../iot-hub/iot-hub-browse.component.ts | 12 +++++++++++- .../iot-hub/iot-hub-items-page.component.html | 3 ++- .../pages/iot-hub/iot-hub-items-page.component.ts | 15 ++++++++++++--- 4 files changed, 33 insertions(+), 6 deletions(-) diff --git a/ui-ngx/src/app/modules/home/components/iot-hub/device-install-dialog/device-install-dialog.component.ts b/ui-ngx/src/app/modules/home/components/iot-hub/device-install-dialog/device-install-dialog.component.ts index 676ad706b1..7f991316ee 100644 --- a/ui-ngx/src/app/modules/home/components/iot-hub/device-install-dialog/device-install-dialog.component.ts +++ b/ui-ngx/src/app/modules/home/components/iot-hub/device-install-dialog/device-install-dialog.component.ts @@ -95,6 +95,12 @@ export class TbDeviceInstallDialogComponent extends DialogComponent = {}; @@ -357,7 +363,7 @@ export class TbDeviceInstallDialogComponent extends DialogComponent(); + /** + * Fired whenever an install, update or delete changed what this tenant has installed, so a host + * page showing its own installed-items counter can refresh it instead of waiting for a reload. + */ + @Output() installedItemsChanged = new EventEmitter(); @Input() set activeType(value: ItemType) { if (value && value !== this._activeType) { const wasInit = !!this._activeType; @@ -627,7 +632,11 @@ export class TbIotHubBrowseComponent implements OnInit, AfterViewInit, OnDestroy }); } - private reloadInstalledItems(): void { + /** + * Re-reads what is installed for the active type and announces the change. Public so a host page + * that opens the item detail dialog itself can refresh this grid through the same path. + */ + reloadInstalledItems(): void { const config = {ignoreLoading: true}; const pageLink = new PageLink(10000, 0); if (this.activeType === ItemType.WIDGET) { @@ -643,6 +652,7 @@ export class TbIotHubBrowseComponent implements OnInit, AfterViewInit, OnDestroy this.installedItemCounts = counts; }); } + this.installedItemsChanged.emit(); } private loadFilterInfo(): void { diff --git a/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-items-page.component.html b/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-items-page.component.html index 59a42eab29..5787b5ecf0 100644 --- a/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-items-page.component.html +++ b/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-items-page.component.html @@ -35,7 +35,8 @@ + [hideTabs]="true" + (installedItemsChanged)="loadInstalledCount()"> diff --git a/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-items-page.component.ts b/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-items-page.component.ts index b89448be3c..07beff5559 100644 --- a/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-items-page.component.ts +++ b/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-items-page.component.ts @@ -1,12 +1,13 @@ // SPDX-FileCopyrightText: Copyright The Thingsboard Authors // SPDX-License-Identifier: Apache-2.0 -import { Component, OnInit } from '@angular/core'; +import { Component, OnInit, ViewChild } from '@angular/core'; import { ActivatedRoute, Router } from '@angular/router'; import { map } from 'rxjs/operators'; import { Observable } from 'rxjs'; import { ItemType } from '@shared/models/iot-hub/iot-hub-item.models'; import { IotHubApiService } from '@core/http/iot-hub-api.service'; import { IotHubActionsService } from '@home/components/iot-hub/iot-hub-actions.service'; +import { TbIotHubBrowseComponent } from '@home/components/iot-hub/iot-hub-browse.component'; import { IotHubInstalledItem } from '@shared/models/iot-hub/iot-hub-installed-item.models'; import { MpItemVersionView } from '@shared/models/iot-hub/iot-hub-version.models'; import { PageLink } from '@shared/models/page/page-link'; @@ -83,6 +84,8 @@ export class TbIotHubItemsPageComponent implements OnInit { config: ItemTypePageConfig; installedItemsCount = 0; + @ViewChild(TbIotHubBrowseComponent) private browse: TbIotHubBrowseComponent; + constructor( private route: ActivatedRoute, private router: Router, @@ -109,7 +112,7 @@ export class TbIotHubItemsPageComponent implements OnInit { window.open(this.iotHubApiService.baseUrl + '/signup', '_blank'); } - private loadInstalledCount(): void { + loadInstalledCount(): void { this.iotHubApiService.getInstalledItemsCount(this.config.type, { ignoreLoading: true }).subscribe(count => { this.installedItemsCount = count; }); @@ -147,7 +150,13 @@ export class TbIotHubItemsPageComponent implements OnInit { 'default', true, openItem.preview - ).subscribe(); + ).subscribe(result => { + // The deep-linked dialog is opened by this page rather than by the grid, so its outcome + // has to be fed back in by hand — the grid then refreshes and announces the new count. + if (result === 'installed' || result === 'updated' || result === 'deleted') { + this.browse?.reloadInstalledItems(); + } + }); }); } From b02a7d0817c053f779b54f8e952a62d72e4d8772 Mon Sep 17 00:00:00 2001 From: Viacheslav Klimov Date: Tue, 22 Sep 2026 16:43:19 +0300 Subject: [PATCH 073/159] Fix license headers --- .../service/edge/rpc/EdgeGrpcServiceTest.java | 17 ++--------------- .../js/NashornJsInvokeServiceLifecycleTest.java | 17 ++--------------- 2 files changed, 4 insertions(+), 30 deletions(-) diff --git a/application/src/test/java/org/thingsboard/server/service/edge/rpc/EdgeGrpcServiceTest.java b/application/src/test/java/org/thingsboard/server/service/edge/rpc/EdgeGrpcServiceTest.java index 7b71c65c9f..80730f9f53 100644 --- a/application/src/test/java/org/thingsboard/server/service/edge/rpc/EdgeGrpcServiceTest.java +++ b/application/src/test/java/org/thingsboard/server/service/edge/rpc/EdgeGrpcServiceTest.java @@ -1,18 +1,5 @@ -/** - * Copyright © 2016-2026 The Thingsboard Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ +// SPDX-FileCopyrightText: Copyright The Thingsboard Authors +// SPDX-License-Identifier: Apache-2.0 package org.thingsboard.server.service.edge.rpc; import org.junit.jupiter.api.BeforeEach; diff --git a/common/script/script-api/src/test/java/org/thingsboard/script/api/js/NashornJsInvokeServiceLifecycleTest.java b/common/script/script-api/src/test/java/org/thingsboard/script/api/js/NashornJsInvokeServiceLifecycleTest.java index cdfd2d8e93..673e06d5a8 100644 --- a/common/script/script-api/src/test/java/org/thingsboard/script/api/js/NashornJsInvokeServiceLifecycleTest.java +++ b/common/script/script-api/src/test/java/org/thingsboard/script/api/js/NashornJsInvokeServiceLifecycleTest.java @@ -1,18 +1,5 @@ -/** - * Copyright © 2016-2026 The Thingsboard Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ +// SPDX-FileCopyrightText: Copyright The Thingsboard Authors +// SPDX-License-Identifier: Apache-2.0 package org.thingsboard.script.api.js; import delight.nashornsandbox.NashornSandbox; From e1e6bfdef3d03b8ee5dc34ded56368c5c0fb25e6 Mon Sep 17 00:00:00 2001 From: IrynaMatveieva Date: Thu, 24 Sep 2026 09:49:57 +0300 Subject: [PATCH 074/159] Apply tenant profile default storage TTL to calculated field time series output --- ...tractCalculatedFieldProcessingService.java | 10 +- ...tCalculatedFieldProcessingServiceTest.java | 99 +++++++++++++++++++ 2 files changed, 108 insertions(+), 1 deletion(-) create mode 100644 application/src/test/java/org/thingsboard/server/service/cf/DefaultCalculatedFieldProcessingServiceTest.java diff --git a/application/src/main/java/org/thingsboard/server/service/cf/AbstractCalculatedFieldProcessingService.java b/application/src/main/java/org/thingsboard/server/service/cf/AbstractCalculatedFieldProcessingService.java index e4850b9128..72f34918c8 100644 --- a/application/src/main/java/org/thingsboard/server/service/cf/AbstractCalculatedFieldProcessingService.java +++ b/application/src/main/java/org/thingsboard/server/service/cf/AbstractCalculatedFieldProcessingService.java @@ -70,6 +70,7 @@ import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.ExecutionException; +import java.util.concurrent.TimeUnit; import java.util.function.Function; import java.util.function.Predicate; import java.util.stream.Collectors; @@ -489,10 +490,17 @@ public abstract class AbstractCalculatedFieldProcessingService { callback.onFailure(new IllegalArgumentException("Only TimeSeriesImmediateOutputStrategy is supported.")); } else { TimeseriesSaveRequest.Strategy strategy = new TimeseriesSaveRequest.Strategy(tsOutputStrategy.isSaveTimeSeries(), tsOutputStrategy.isSaveLatest(), tsOutputStrategy.isSendWsUpdate(), tsOutputStrategy.isProcessCfs()); - saveTimeSeriesInternal(tenantId, entityId, jsonResult, tsOutputStrategy.getTtl(), cfIds, ts, strategy, callback); + saveTimeSeriesInternal(tenantId, entityId, jsonResult, resolveTtl(tenantId, tsOutputStrategy.getTtl()), cfIds, ts, strategy, callback); } } + private long resolveTtl(TenantId tenantId, long ttl) { + if (ttl == 0L) { + return TimeUnit.DAYS.toSeconds(apiLimitService.getLimit(tenantId, DefaultTenantProfileConfiguration::getDefaultStorageTtlDays)); + } + return ttl; + } + private void saveTimeSeriesInternal(TenantId tenantId, EntityId entityId, JsonElement jsonResult, Long ttl, List cfIds, long ts, TimeseriesSaveRequest.Strategy strategy, TbCallback callback) { Map> tsKvMap = JsonConverter.convertToTelemetry(jsonResult, ts); if (tsKvMap.isEmpty()) { diff --git a/application/src/test/java/org/thingsboard/server/service/cf/DefaultCalculatedFieldProcessingServiceTest.java b/application/src/test/java/org/thingsboard/server/service/cf/DefaultCalculatedFieldProcessingServiceTest.java new file mode 100644 index 0000000000..925eaed40a --- /dev/null +++ b/application/src/test/java/org/thingsboard/server/service/cf/DefaultCalculatedFieldProcessingServiceTest.java @@ -0,0 +1,99 @@ +// SPDX-FileCopyrightText: Copyright The Thingsboard Authors +// SPDX-License-Identifier: Apache-2.0 +package org.thingsboard.server.service.cf; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.ArgumentCaptor; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; +import org.thingsboard.common.util.JacksonUtil; +import org.thingsboard.rule.engine.api.TimeseriesSaveRequest; +import org.thingsboard.server.cluster.TbClusterService; +import org.thingsboard.server.common.data.cf.configuration.OutputType; +import org.thingsboard.server.common.data.cf.configuration.TimeSeriesImmediateOutputStrategy; +import org.thingsboard.server.common.data.id.DeviceId; +import org.thingsboard.server.common.data.id.TenantId; +import org.thingsboard.server.common.msg.queue.TbCallback; +import org.thingsboard.server.dao.attributes.AttributesService; +import org.thingsboard.server.dao.relation.RelationService; +import org.thingsboard.server.dao.timeseries.TimeseriesService; +import org.thingsboard.server.dao.usagerecord.ApiLimitService; +import org.thingsboard.server.queue.discovery.PartitionService; +import org.thingsboard.server.service.telemetry.TelemetrySubscriptionService; + +import java.util.Collections; +import java.util.UUID; +import java.util.concurrent.TimeUnit; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +@ExtendWith(MockitoExtension.class) +public class DefaultCalculatedFieldProcessingServiceTest { + + private final TenantId tenantId = TenantId.fromUUID(UUID.fromString("e7f46b23-0c7d-42f5-9b06-fc35ab17af8a")); + private final DeviceId deviceId = new DeviceId(UUID.fromString("ccd71696-0586-422d-940e-755a41ec3b0d")); + + @Mock + private AttributesService attributesService; + @Mock + private TimeseriesService timeseriesService; + @Mock + private ApiLimitService apiLimitService; + @Mock + private RelationService relationService; + @Mock + private OwnerService ownerService; + @Mock + private TbClusterService clusterService; + @Mock + private TelemetrySubscriptionService tsSubService; + @Mock + private PartitionService partitionService; + + private DefaultCalculatedFieldProcessingService service; + + @BeforeEach + public void setUp() { + service = new DefaultCalculatedFieldProcessingService(attributesService, timeseriesService, apiLimitService, + relationService, ownerService, clusterService, tsSubService, partitionService); + } + + @Test + public void givenTimeSeriesOutputWithoutTtl_whenProcessResult_thenTenantProfileDefaultStorageTtlIsUsed() { + when(apiLimitService.getLimit(eq(tenantId), any())).thenReturn(30L); + + service.processResult(tenantId, deviceId, "cf", buildTimeSeriesResult(0L), Collections.emptyList(), TbCallback.EMPTY); + + assertThat(captureSaveRequest().getTtl()).isEqualTo(TimeUnit.DAYS.toSeconds(30)); + } + + @Test + public void givenTimeSeriesOutputWithCustomTtl_whenProcessResult_thenCustomTtlIsUsed() { + service.processResult(tenantId, deviceId, "cf", buildTimeSeriesResult(3600L), Collections.emptyList(), TbCallback.EMPTY); + + assertThat(captureSaveRequest().getTtl()).isEqualTo(3600L); + verify(apiLimitService, never()).getLimit(any(), any()); + } + + private TelemetryCalculatedFieldResult buildTimeSeriesResult(long ttl) { + return TelemetryCalculatedFieldResult.builder() + .type(OutputType.TIME_SERIES) + .outputStrategy(new TimeSeriesImmediateOutputStrategy(ttl, true, true, true, true)) + .result(JacksonUtil.newObjectNode().put("result", 42)) + .build(); + } + + private TimeseriesSaveRequest captureSaveRequest() { + ArgumentCaptor captor = ArgumentCaptor.forClass(TimeseriesSaveRequest.class); + verify(tsSubService).saveTimeseries(captor.capture()); + return captor.getValue(); + } + +} From d9f5ec7b433854c1682707d4729c5298e6d9f31f Mon Sep 17 00:00:00 2001 From: Maksym Tsymbarov Date: Thu, 24 Sep 2026 11:11:59 +0200 Subject: [PATCH 075/159] Updated gateway sync branch config --- application/src/main/resources/thingsboard.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/application/src/main/resources/thingsboard.yml b/application/src/main/resources/thingsboard.yml index 2de4c21c8a..a527a4108c 100644 --- a/application/src/main/resources/thingsboard.yml +++ b/application/src/main/resources/thingsboard.yml @@ -1428,7 +1428,7 @@ transport: # URL of gateways dashboard repository repository_url: "${TB_GATEWAY_DASHBOARD_SYNC_REPOSITORY_URL:https://github.com/thingsboard/gateway-management-extensions-dist.git}" # Branch of gateways dashboard repository to work with - branch: "${TB_GATEWAY_DASHBOARD_SYNC_BRANCH:release/4.0.0}" + branch: "${TB_GATEWAY_DASHBOARD_SYNC_BRANCH:release/4.2.0}" # Fetch frequency in hours for gateways dashboard repository fetch_frequency: "${TB_GATEWAY_DASHBOARD_SYNC_FETCH_FREQUENCY:24}" ssl: From 84220d92edcf0453145a87cc34a9f2e32bc6b46b Mon Sep 17 00:00:00 2001 From: Viacheslav Klimov Date: Thu, 24 Sep 2026 15:05:10 +0300 Subject: [PATCH 076/159] Add the Community Grant enrollment flow --- .../main/data/upgrade/basic/schema_update.sql | 2 + .../upgrade/lts/4.3.1.6/schema_update.sql | 21 + .../ThingsboardSecurityConfiguration.java | 11 +- .../controller/CommunityGrantController.java | 213 +++ .../CommunityGrantTestResetController.java | 74 ++ .../install/ThingsboardInstallService.java | 3 + .../CommunityGrantBundleFormatException.java | 34 + .../CommunityGrantCheckerInput.java | 23 + ...ommunityGrantCheckerTooLargeException.java | 17 + .../CommunityGrantClusterStatus.java | 9 + .../CommunityGrantFlowStateStore.java | 122 ++ .../CommunityGrantLibpqDsn.java | 77 ++ .../CommunityGrantOfflineBundle.java | 314 +++++ .../CommunityGrantOfflineReportStore.java | 155 +++ .../CommunityGrantPlatform.java | 61 + .../community_grant/CommunityGrantPoller.java | 517 ++++++++ .../CommunityGrantPortalClient.java | 269 ++++ .../CommunityGrantPortalStatus.java | 16 + ...ommunityGrantReleaseSignatureVerifier.java | 212 +++ .../CommunityGrantReportRequest.java | 6 + .../CommunityGrantReportResponse.java | 9 + .../CommunityGrantReportRunner.java | 383 ++++++ .../CommunityGrantService.java | 35 + .../DefaultCommunityGrantService.java | 527 ++++++++ .../install/EntityDatabaseSchemaService.java | 2 + .../SqlEntityDatabaseSchemaService.java | 40 + .../install/lts/LtsMigrationService.java | 21 +- .../install/lts/V4_3_1_6Migration.java | 43 + .../service/system/SystemPatchApplier.java | 29 +- .../src/main/resources/thingsboard.yml | 18 +- .../CommunityGrantControllerTest.java | 678 ++++++++++ .../ThingsboardInstallServiceTest.java | 90 ++ .../CommunityGrantBundleFixtures.java | 126 ++ .../CommunityGrantFlowStateStoreTest.java | 305 +++++ .../CommunityGrantLibpqDsnTest.java | 64 + .../CommunityGrantOfflineBundleTest.java | 421 ++++++ .../CommunityGrantOfflineReportStoreTest.java | 216 +++ .../CommunityGrantPlatformTest.java | 59 + .../CommunityGrantPollerTest.java | 952 ++++++++++++++ .../CommunityGrantPortalClientTest.java | 552 ++++++++ ...nityGrantReleaseSignatureVerifierTest.java | 260 ++++ .../CommunityGrantReportRunnerTest.java | 529 ++++++++ .../CommunityGrantSigningFixtures.java | 50 + .../CommunityGrantStateInfoTest.java | 70 + .../CommunityGrantStateTest.java | 48 + .../CommunityGrantUploadPayloadLimitTest.java | 143 ++ ...tCommunityGrantServiceConcurrencyTest.java | 149 +++ .../DefaultCommunityGrantServiceTest.java | 1171 +++++++++++++++++ .../install/AbstractInstallPostgresTest.java | 34 + .../service/install/InstallTestSupport.java | 60 + .../SchemaUpdateSqlUpgradeOrderTest.java | 60 + ...ityDatabaseSchemaServiceClusterIdTest.java | 106 ++ .../install/TbClusterDdlDriftTest.java | 39 + .../lts/LtsMigrationIntegrationTest.java | 83 +- .../install/lts/LtsMigrationServiceTest.java | 64 +- .../server/system/SystemPatchApplierTest.java | 44 +- .../resources/community-grant/01-valid.tbicb | Bin 0 -> 575 bytes .../community-grant/02-too-short.tbicb | Bin 0 -> 90 bytes .../community-grant/03-bad-magic.tbicb | Bin 0 -> 575 bytes .../community-grant/04-unknown-version.tbicb | Bin 0 -> 575 bytes .../05-manifest-len-zero.tbicb | Bin 0 -> 575 bytes .../06-manifest-len-too-large.tbicb | Bin 0 -> 575 bytes .../community-grant/07-checker-len-zero.tbicb | Bin 0 -> 575 bytes .../08-truncated-mid-manifest.tbicb | Bin 0 -> 301 bytes .../09-truncated-mid-checker.tbicb | Bin 0 -> 543 bytes .../community-grant/10-trailing-byte.tbicb | Bin 0 -> 576 bytes .../11-manifest-not-utf8.tbicb | Bin 0 -> 575 bytes .../12-manifest-not-json.tbicb | Bin 0 -> 575 bytes .../13-manifest-missing-field.tbicb | Bin 0 -> 524 bytes .../14-expired-challenge.tbicb | Bin 0 -> 575 bytes .../15-relsig-not-tbicsig1.tbicb | Bin 0 -> 575 bytes .../resources/community-grant/vectors.json | 142 ++ .../install/pre-upgrade-schema-entities.sql | 997 ++++++++++++++ .../server/common/data/audit/ActionType.java | 14 +- .../CommunityGrantFlowState.java | 54 + .../community_grant/CommunityGrantMode.java | 13 + .../CommunityGrantOfflineRun.java | 41 + .../CommunityGrantOfflineRunStatus.java | 13 + .../CommunityGrantParkReason.java | 21 + .../community_grant/CommunityGrantState.java | 46 + .../CommunityGrantStateInfo.java | 38 + .../dao/subscription/TbClusterStore.java | 67 + .../main/resources/sql/schema-entities.sql | 11 + .../dao/subscription/TbClusterStoreTest.java | 118 ++ .../resources/sql/psql/drop-all-tables.sql | 1 + ui-ngx/package.json | 1 + ui-ngx/src/app/core/auth/auth.service.spec.ts | 14 - .../app/core/http/community-grant.service.ts | 63 + .../interceptors/global-http-interceptor.ts | 2 + .../widget/lib/home-page/ce-grant-tokens.scss | 34 + .../community-grant-dialog.component.html | 555 ++++++++ .../community-grant-dialog.component.scss | 709 ++++++++++ .../community-grant-dialog.component.ts | 492 +++++++ .../lib/home-page/home-page-widgets.module.ts | 9 +- .../lib/home-page/version-info.component.html | 126 +- .../lib/home-page/version-info.component.scss | 207 ++- .../lib/home-page/version-info.component.ts | 146 +- .../src/app/shared/models/audit-log.models.ts | 8 +- .../models/ce-grant/community-grant.models.ts | 479 +++++++ ui-ngx/src/app/shared/models/icon.models.ts | 5 +- .../src/assets/ce-grant/key-visual-apps.svg | 124 ++ .../assets/locale/locale.constant-en_US.json | 131 +- .../assets/locale/locale.constant-ro_RO.json | 2 +- ui-ngx/src/styles.scss | 1 + ui-ngx/yarn.lock | 5 + 105 files changed, 14184 insertions(+), 141 deletions(-) create mode 100644 application/src/main/data/upgrade/lts/4.3.1.6/schema_update.sql create mode 100644 application/src/main/java/org/thingsboard/server/controller/CommunityGrantController.java create mode 100644 application/src/main/java/org/thingsboard/server/controller/CommunityGrantTestResetController.java create mode 100644 application/src/main/java/org/thingsboard/server/service/community_grant/CommunityGrantBundleFormatException.java create mode 100644 application/src/main/java/org/thingsboard/server/service/community_grant/CommunityGrantCheckerInput.java create mode 100644 application/src/main/java/org/thingsboard/server/service/community_grant/CommunityGrantCheckerTooLargeException.java create mode 100644 application/src/main/java/org/thingsboard/server/service/community_grant/CommunityGrantClusterStatus.java create mode 100644 application/src/main/java/org/thingsboard/server/service/community_grant/CommunityGrantFlowStateStore.java create mode 100644 application/src/main/java/org/thingsboard/server/service/community_grant/CommunityGrantLibpqDsn.java create mode 100644 application/src/main/java/org/thingsboard/server/service/community_grant/CommunityGrantOfflineBundle.java create mode 100644 application/src/main/java/org/thingsboard/server/service/community_grant/CommunityGrantOfflineReportStore.java create mode 100644 application/src/main/java/org/thingsboard/server/service/community_grant/CommunityGrantPlatform.java create mode 100644 application/src/main/java/org/thingsboard/server/service/community_grant/CommunityGrantPoller.java create mode 100644 application/src/main/java/org/thingsboard/server/service/community_grant/CommunityGrantPortalClient.java create mode 100644 application/src/main/java/org/thingsboard/server/service/community_grant/CommunityGrantPortalStatus.java create mode 100644 application/src/main/java/org/thingsboard/server/service/community_grant/CommunityGrantReleaseSignatureVerifier.java create mode 100644 application/src/main/java/org/thingsboard/server/service/community_grant/CommunityGrantReportRequest.java create mode 100644 application/src/main/java/org/thingsboard/server/service/community_grant/CommunityGrantReportResponse.java create mode 100644 application/src/main/java/org/thingsboard/server/service/community_grant/CommunityGrantReportRunner.java create mode 100644 application/src/main/java/org/thingsboard/server/service/community_grant/CommunityGrantService.java create mode 100644 application/src/main/java/org/thingsboard/server/service/community_grant/DefaultCommunityGrantService.java create mode 100644 application/src/main/java/org/thingsboard/server/service/install/lts/V4_3_1_6Migration.java create mode 100644 application/src/test/java/org/thingsboard/server/controller/CommunityGrantControllerTest.java create mode 100644 application/src/test/java/org/thingsboard/server/install/ThingsboardInstallServiceTest.java create mode 100644 application/src/test/java/org/thingsboard/server/service/community_grant/CommunityGrantBundleFixtures.java create mode 100644 application/src/test/java/org/thingsboard/server/service/community_grant/CommunityGrantFlowStateStoreTest.java create mode 100644 application/src/test/java/org/thingsboard/server/service/community_grant/CommunityGrantLibpqDsnTest.java create mode 100644 application/src/test/java/org/thingsboard/server/service/community_grant/CommunityGrantOfflineBundleTest.java create mode 100644 application/src/test/java/org/thingsboard/server/service/community_grant/CommunityGrantOfflineReportStoreTest.java create mode 100644 application/src/test/java/org/thingsboard/server/service/community_grant/CommunityGrantPlatformTest.java create mode 100644 application/src/test/java/org/thingsboard/server/service/community_grant/CommunityGrantPollerTest.java create mode 100644 application/src/test/java/org/thingsboard/server/service/community_grant/CommunityGrantPortalClientTest.java create mode 100644 application/src/test/java/org/thingsboard/server/service/community_grant/CommunityGrantReleaseSignatureVerifierTest.java create mode 100644 application/src/test/java/org/thingsboard/server/service/community_grant/CommunityGrantReportRunnerTest.java create mode 100644 application/src/test/java/org/thingsboard/server/service/community_grant/CommunityGrantSigningFixtures.java create mode 100644 application/src/test/java/org/thingsboard/server/service/community_grant/CommunityGrantStateInfoTest.java create mode 100644 application/src/test/java/org/thingsboard/server/service/community_grant/CommunityGrantStateTest.java create mode 100644 application/src/test/java/org/thingsboard/server/service/community_grant/CommunityGrantUploadPayloadLimitTest.java create mode 100644 application/src/test/java/org/thingsboard/server/service/community_grant/DefaultCommunityGrantServiceConcurrencyTest.java create mode 100644 application/src/test/java/org/thingsboard/server/service/community_grant/DefaultCommunityGrantServiceTest.java create mode 100644 application/src/test/java/org/thingsboard/server/service/install/AbstractInstallPostgresTest.java create mode 100644 application/src/test/java/org/thingsboard/server/service/install/InstallTestSupport.java create mode 100644 application/src/test/java/org/thingsboard/server/service/install/SchemaUpdateSqlUpgradeOrderTest.java create mode 100644 application/src/test/java/org/thingsboard/server/service/install/SqlEntityDatabaseSchemaServiceClusterIdTest.java create mode 100644 application/src/test/java/org/thingsboard/server/service/install/TbClusterDdlDriftTest.java create mode 100644 application/src/test/resources/community-grant/01-valid.tbicb create mode 100644 application/src/test/resources/community-grant/02-too-short.tbicb create mode 100644 application/src/test/resources/community-grant/03-bad-magic.tbicb create mode 100644 application/src/test/resources/community-grant/04-unknown-version.tbicb create mode 100644 application/src/test/resources/community-grant/05-manifest-len-zero.tbicb create mode 100644 application/src/test/resources/community-grant/06-manifest-len-too-large.tbicb create mode 100644 application/src/test/resources/community-grant/07-checker-len-zero.tbicb create mode 100644 application/src/test/resources/community-grant/08-truncated-mid-manifest.tbicb create mode 100644 application/src/test/resources/community-grant/09-truncated-mid-checker.tbicb create mode 100644 application/src/test/resources/community-grant/10-trailing-byte.tbicb create mode 100644 application/src/test/resources/community-grant/11-manifest-not-utf8.tbicb create mode 100644 application/src/test/resources/community-grant/12-manifest-not-json.tbicb create mode 100644 application/src/test/resources/community-grant/13-manifest-missing-field.tbicb create mode 100644 application/src/test/resources/community-grant/14-expired-challenge.tbicb create mode 100644 application/src/test/resources/community-grant/15-relsig-not-tbicsig1.tbicb create mode 100644 application/src/test/resources/community-grant/vectors.json create mode 100644 application/src/test/resources/install/pre-upgrade-schema-entities.sql create mode 100644 common/data/src/main/java/org/thingsboard/server/common/data/community_grant/CommunityGrantFlowState.java create mode 100644 common/data/src/main/java/org/thingsboard/server/common/data/community_grant/CommunityGrantMode.java create mode 100644 common/data/src/main/java/org/thingsboard/server/common/data/community_grant/CommunityGrantOfflineRun.java create mode 100644 common/data/src/main/java/org/thingsboard/server/common/data/community_grant/CommunityGrantOfflineRunStatus.java create mode 100644 common/data/src/main/java/org/thingsboard/server/common/data/community_grant/CommunityGrantParkReason.java create mode 100644 common/data/src/main/java/org/thingsboard/server/common/data/community_grant/CommunityGrantState.java create mode 100644 common/data/src/main/java/org/thingsboard/server/common/data/community_grant/CommunityGrantStateInfo.java create mode 100644 dao/src/main/java/org/thingsboard/server/dao/subscription/TbClusterStore.java create mode 100644 dao/src/test/java/org/thingsboard/server/dao/subscription/TbClusterStoreTest.java delete mode 100644 ui-ngx/src/app/core/auth/auth.service.spec.ts create mode 100644 ui-ngx/src/app/core/http/community-grant.service.ts create mode 100644 ui-ngx/src/app/modules/home/components/widget/lib/home-page/ce-grant-tokens.scss create mode 100644 ui-ngx/src/app/modules/home/components/widget/lib/home-page/community-grant-dialog.component.html create mode 100644 ui-ngx/src/app/modules/home/components/widget/lib/home-page/community-grant-dialog.component.scss create mode 100644 ui-ngx/src/app/modules/home/components/widget/lib/home-page/community-grant-dialog.component.ts create mode 100644 ui-ngx/src/app/shared/models/ce-grant/community-grant.models.ts create mode 100644 ui-ngx/src/assets/ce-grant/key-visual-apps.svg diff --git a/application/src/main/data/upgrade/basic/schema_update.sql b/application/src/main/data/upgrade/basic/schema_update.sql index 20a3528e9a..c7ac2598a0 100644 --- a/application/src/main/data/upgrade/basic/schema_update.sql +++ b/application/src/main/data/upgrade/basic/schema_update.sql @@ -3,6 +3,8 @@ -- SPDX-License-Identifier: Apache-2.0 -- +-- Runs before schema-entities.sql and the LTS schema migrations: reference only tables a released version already has. + -- UPDATE TENANT PROFILE CONFIGURATION START UPDATE tenant_profile diff --git a/application/src/main/data/upgrade/lts/4.3.1.6/schema_update.sql b/application/src/main/data/upgrade/lts/4.3.1.6/schema_update.sql new file mode 100644 index 0000000000..e984d996f5 --- /dev/null +++ b/application/src/main/data/upgrade/lts/4.3.1.6/schema_update.sql @@ -0,0 +1,21 @@ +-- +-- SPDX-FileCopyrightText: Copyright The Thingsboard Authors +-- SPDX-License-Identifier: Apache-2.0 +-- + +-- TB_CLUSTER START + +-- The patch path never runs schema-entities.sql, so tb_cluster is created here too. +-- Keep this block identical to the one in schema-entities.sql. + +CREATE TABLE IF NOT EXISTS tb_cluster ( + cluster_id uuid NOT NULL, + license_claim_token varchar, + CONSTRAINT tb_cluster_pkey PRIMARY KEY (cluster_id) +); + +-- Backstop against two concurrent install jobs both minting an id: a unique index on a constant +-- expression allows at most one row in the table, no matter how many rows race to insert. +CREATE UNIQUE INDEX IF NOT EXISTS tb_cluster_single_row ON tb_cluster ((true)); + +-- TB_CLUSTER END diff --git a/application/src/main/java/org/thingsboard/server/config/ThingsboardSecurityConfiguration.java b/application/src/main/java/org/thingsboard/server/config/ThingsboardSecurityConfiguration.java index 0eeb602c1d..9e638d271b 100644 --- a/application/src/main/java/org/thingsboard/server/config/ThingsboardSecurityConfiguration.java +++ b/application/src/main/java/org/thingsboard/server/config/ThingsboardSecurityConfiguration.java @@ -75,8 +75,11 @@ public class ThingsboardSecurityConfiguration { public static final String WS_ENTRY_POINT = "/api/ws/**"; public static final String MAIL_OAUTH2_PROCESSING_ENTRY_POINT = "/api/admin/mail/oauth2/code"; public static final String DEVICE_CONNECTIVITY_CERTIFICATE_DOWNLOAD_ENTRY_POINT = "/api/device-connectivity/*/certificate/download"; + public static final String COMMUNITY_GRANT_OFFLINE_RUN_ENTRY_POINT = "/api/communityGrant/offline/run"; + public static final String COMMUNITY_GRANT_OFFLINE_RUN_PAYLOAD_LIMIT = COMMUNITY_GRANT_OFFLINE_RUN_ENTRY_POINT + "=35651584"; - @Value("${server.http.max_payload_size:/api/image*/**=52428800;/api/resource/**=52428800;/api/**=16777216}") + // First match wins, so the community grant entry must stay ahead of /api/**. + @Value("${server.http.max_payload_size:/api/communityGrant/offline/run=35651584;/api/image*/**=52428800;/api/resource/**=52428800;/api/**=16777216}") private String maxPayloadSizeConfig; @Autowired @@ -133,9 +136,13 @@ public class ThingsboardSecurityConfiguration { @Autowired private HttpSecurityHeadersCustomizer httpSecurityHeadersCustomizer; + // An override replaces the whole list, so the offline upload's entry is re-added unless it names that path. @Bean protected PayloadSizeFilter payloadSizeFilter() { - return new PayloadSizeFilter(maxPayloadSizeConfig); + String config = maxPayloadSizeConfig.contains(COMMUNITY_GRANT_OFFLINE_RUN_ENTRY_POINT + "=") + ? maxPayloadSizeConfig + : COMMUNITY_GRANT_OFFLINE_RUN_PAYLOAD_LIMIT + ";" + maxPayloadSizeConfig; + return new PayloadSizeFilter(config); } @Bean diff --git a/application/src/main/java/org/thingsboard/server/controller/CommunityGrantController.java b/application/src/main/java/org/thingsboard/server/controller/CommunityGrantController.java new file mode 100644 index 0000000000..8df6f400ac --- /dev/null +++ b/application/src/main/java/org/thingsboard/server/controller/CommunityGrantController.java @@ -0,0 +1,213 @@ +// SPDX-FileCopyrightText: Copyright The Thingsboard Authors +// SPDX-License-Identifier: Apache-2.0 +package org.thingsboard.server.controller; + +import io.swagger.v3.oas.annotations.Hidden; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.core.io.ByteArrayResource; +import org.springframework.core.io.Resource; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; +import org.springframework.security.access.prepost.PreAuthorize; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestPart; +import org.springframework.web.bind.annotation.ResponseBody; +import org.springframework.web.bind.annotation.RestController; +import org.springframework.web.multipart.MultipartFile; +import org.thingsboard.server.common.data.audit.ActionType; +import org.thingsboard.server.common.data.community_grant.CommunityGrantStateInfo; +import org.thingsboard.server.common.data.exception.ThingsboardErrorCode; +import org.thingsboard.server.common.data.exception.ThingsboardException; +import org.thingsboard.server.dao.subscription.TbClusterStore; +import org.thingsboard.server.queue.util.TbCoreComponent; +import org.thingsboard.server.service.community_grant.CommunityGrantOfflineBundle; +import org.thingsboard.server.service.community_grant.CommunityGrantPlatform; +import org.thingsboard.server.service.community_grant.CommunityGrantService; +import org.thingsboard.server.service.security.model.SecurityUser; + +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.time.Instant; +import java.util.Optional; +import java.util.UUID; + +@Hidden +@RestController +@TbCoreComponent +@RequestMapping("/api/communityGrant") +@RequiredArgsConstructor +@Slf4j +public class CommunityGrantController extends BaseController { + + private static final String REPORT_FILE_NAME = "tb-instance-check-report.txt"; + + @Value("${community-grant.max-checker-size-bytes:33554432}") + private long maxCheckerSizeBytes; + + private final CommunityGrantService communityGrantService; + private final TbClusterStore tbClusterStore; + + @PreAuthorize("hasAuthority('SYS_ADMIN')") + @GetMapping("/state") + @ResponseBody + public CommunityGrantStateInfo getState() { + return communityGrantService.getStateInfo(); + } + + /** Every failure is audited as a refusal, hence the catch on {@code Exception}. */ + @PreAuthorize("hasAuthority('SYS_ADMIN')") + @PostMapping("/start") + @ResponseBody + public CommunityGrantStateInfo start() throws ThingsboardException { + SecurityUser user = getCurrentUser(); + CommunityGrantStateInfo stateInfo; + try { + stateInfo = communityGrantService.start(); + } catch (Exception e) { + auditLogService.logEntityAction(user.getTenantId(), user.getCustomerId(), user.getId(), user.getName(), + user.getId(), user, ActionType.COMMUNITY_GRANT_ENROLLMENT, e); + throw e; + } + auditLogService.logEntityAction(user.getTenantId(), user.getCustomerId(), user.getId(), user.getName(), + user.getId(), user, ActionType.COMMUNITY_GRANT_ENROLLMENT, null); + return stateInfo; + } + + /** + * Answers {@code 202} once the run has started on this node; a refusal is audited here, and the run + * audits its own ending. + */ + @PreAuthorize("hasAuthority('SYS_ADMIN')") + @PostMapping(value = "/offline/run", consumes = MediaType.MULTIPART_FORM_DATA_VALUE) + public ResponseEntity runOfflineChecker(@RequestPart("bundle") MultipartFile bundle) + throws ThingsboardException { + SecurityUser user = getCurrentUser(); + CommunityGrantStateInfo stateInfo; + try { + stateInfo = runOfflineChecker(bundle, user); + } catch (Exception e) { + auditOfflineRun(user, e); + throw e; + } + return ResponseEntity.status(HttpStatus.ACCEPTED).body(stateInfo); + } + + private void auditOfflineRun(SecurityUser user, Exception failure) { + auditLogService.logEntityAction(user.getTenantId(), user.getCustomerId(), user.getId(), user.getName(), + user.getId(), user, ActionType.COMMUNITY_GRANT_OFFLINE_CHECKER_RUN, failure); + } + + private CommunityGrantStateInfo runOfflineChecker(MultipartFile bundle, SecurityUser user) + throws ThingsboardException { + long maxBundleSize = maxCheckerSizeBytes + CommunityGrantOfflineBundle.MAX_OVERHEAD_BYTES; + if (bundle.getSize() > maxBundleSize) { + throw new ThingsboardException("The uploaded enrollment bundle is larger than the configured limit of " + + maxBundleSize + " bytes", ThingsboardErrorCode.BAD_REQUEST_PARAMS); + } + byte[] bundleData; + try { + bundleData = bundle.getBytes(); + } catch (IOException e) { + throw new ThingsboardException("Failed to read the uploaded file", ThingsboardErrorCode.BAD_REQUEST_PARAMS); + } + CommunityGrantOfflineBundle parsed; + try { + parsed = CommunityGrantOfflineBundle.parse(bundleData); + } catch (IllegalArgumentException e) { + throw new ThingsboardException(e.getMessage(), ThingsboardErrorCode.BAD_REQUEST_PARAMS); + } + refuseBundleForAnotherInstallation(parsed); + refuseBundleForAnotherPlatform(parsed); + warnIfChallengeExpired(parsed, user); + return communityGrantService.runOfflineChecker(parsed.checker(), parsed.signature(), + parsed.checkerFileName(), parsed.checkerInput(), failure -> auditOfflineRun(user, failure)); + } + + /** Skipped when this deployment has no cluster id at all. */ + private void refuseBundleForAnotherInstallation(CommunityGrantOfflineBundle parsed) throws ThingsboardException { + Optional clusterId = tbClusterStore.getClusterId(); + if (clusterId.isPresent() && !clusterId.get().equals(parsed.clusterId())) { + throw new ThingsboardException("This enrollment bundle was issued for a different installation. " + + "Download a bundle for this installation from the License Portal and upload that one.", + ThingsboardErrorCode.BAD_REQUEST_PARAMS); + } + } + + private void refuseBundleForAnotherPlatform(CommunityGrantOfflineBundle parsed) throws ThingsboardException { + CommunityGrantPlatform platform; + try { + platform = CommunityGrantPlatform.current(); + } catch (RuntimeException e) { + log.debug("Refusing an enrollment bundle: this server's platform has no instance checker build", e); + throw new ThingsboardException("This server's operating system and CPU architecture have no " + + "instance checker build, so an enrollment bundle cannot be run here.", + ThingsboardErrorCode.BAD_REQUEST_PARAMS); + } + if (!platform.os().equals(parsed.os()) || !platform.arch().equals(parsed.arch())) { + throw new ThingsboardException("This enrollment bundle is for " + parsed.os() + "/" + parsed.arch() + + ", and this server is " + platform.os() + "/" + platform.arch() + + ". Download the bundle for this server's platform.", ThingsboardErrorCode.BAD_REQUEST_PARAMS); + } + } + + /** Warns, never blocks: the portal is the authoritative clock, and an air-gapped host may have drifted. */ + private void warnIfChallengeExpired(CommunityGrantOfflineBundle parsed, SecurityUser user) { + if (parsed.isChallengeExpired(System.currentTimeMillis())) { + log.warn("Running an instance checker from an enrollment bundle whose challenge expired at {} " + + "(requested by user {}). The portal will refuse the report it produces; a fresh " + + "bundle is the remedy.", + Instant.ofEpochMilli(parsed.challengeExpiresAt()), user.getId()); + } + } + + @PreAuthorize("hasAuthority('SYS_ADMIN')") + @PostMapping("/requestAccess") + public void requestAccess() throws ThingsboardException { + SecurityUser user = getCurrentUser(); + try { + communityGrantService.requestAccess(); + } catch (Exception e) { + auditLogService.logEntityAction(user.getTenantId(), user.getCustomerId(), user.getId(), user.getName(), + user.getId(), user, ActionType.COMMUNITY_GRANT_REQUEST_ACCESS, e); + throw e; + } + auditLogService.logEntityAction(user.getTenantId(), user.getCustomerId(), user.getId(), user.getName(), + user.getId(), user, ActionType.COMMUNITY_GRANT_REQUEST_ACCESS, null); + } + + @PreAuthorize("hasAuthority('SYS_ADMIN')") + @PostMapping("/offline/handoff") + @ResponseBody + public CommunityGrantStateInfo confirmOfflineHandoff() throws ThingsboardException { + SecurityUser user = getCurrentUser(); + CommunityGrantStateInfo stateInfo; + try { + stateInfo = communityGrantService.confirmOfflineHandoff(); + } catch (Exception e) { + auditLogService.logEntityAction(user.getTenantId(), user.getCustomerId(), user.getId(), user.getName(), + user.getId(), user, ActionType.COMMUNITY_GRANT_ENROLLMENT, e); + throw e; + } + auditLogService.logEntityAction(user.getTenantId(), user.getCustomerId(), user.getId(), user.getName(), + user.getId(), user, ActionType.COMMUNITY_GRANT_ENROLLMENT, null); + return stateInfo; + } + + @PreAuthorize("hasAuthority('SYS_ADMIN')") + @GetMapping("/offline/report") + public ResponseEntity downloadOfflineReport() throws ThingsboardException { + byte[] report = communityGrantService.getOfflineReport().getBytes(StandardCharsets.UTF_8); + return ResponseEntity.ok() + .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + REPORT_FILE_NAME + "\"") + .contentType(MediaType.TEXT_PLAIN) + .contentLength(report.length) + .body(new ByteArrayResource(report)); + } + +} diff --git a/application/src/main/java/org/thingsboard/server/controller/CommunityGrantTestResetController.java b/application/src/main/java/org/thingsboard/server/controller/CommunityGrantTestResetController.java new file mode 100644 index 0000000000..65a1f61362 --- /dev/null +++ b/application/src/main/java/org/thingsboard/server/controller/CommunityGrantTestResetController.java @@ -0,0 +1,74 @@ +// SPDX-FileCopyrightText: Copyright The Thingsboard Authors +// SPDX-License-Identifier: Apache-2.0 +package org.thingsboard.server.controller; + +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.security.access.prepost.PreAuthorize; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.ResponseBody; +import org.springframework.web.bind.annotation.RestController; +import org.thingsboard.server.common.data.community_grant.CommunityGrantStateInfo; +import org.thingsboard.server.common.data.id.TenantId; +import org.thingsboard.server.config.annotations.ApiOperation; +import org.thingsboard.server.dao.settings.AdminSettingsService; +import org.thingsboard.server.dao.subscription.TbClusterStore; +import org.thingsboard.server.queue.util.TbCoreComponent; +import org.thingsboard.server.service.community_grant.CommunityGrantFlowStateStore; +import org.thingsboard.server.service.community_grant.CommunityGrantOfflineReportStore; +import org.thingsboard.server.service.community_grant.CommunityGrantPoller; +import org.thingsboard.server.service.community_grant.CommunityGrantService; + +import java.util.UUID; + +/** FIXME: delete this whole class before merge. Test-only reset that makes the enrollment flow re-runnable. */ +@RestController +@TbCoreComponent +@RequestMapping("/api/communityGrant/test") +@RequiredArgsConstructor +@Slf4j +public class CommunityGrantTestResetController extends BaseController { + + private final JdbcTemplate jdbcTemplate; + private final TbClusterStore tbClusterStore; + private final AdminSettingsService adminSettingsService; + private final CommunityGrantOfflineReportStore offlineReportStore; + private final CommunityGrantPoller poller; + private final CommunityGrantService communityGrantService; + + // The poller is stopped first, so a tick in flight cannot write the enrollment back after the reset. + @ApiOperation(value = "Reset the community grant enrollment (testing only)", + notes = "Discards this deployment's claim token, its persisted community grant flow and the last " + + "offline report, and mints a new cluster id so the portal sees an installation it has " + + "never registered. Available for users with 'SYS_ADMIN' authority.") + @PreAuthorize("hasAuthority('SYS_ADMIN')") + @PostMapping("/reset") + @ResponseBody + public CommunityGrantTestResetResult reset(@RequestParam(defaultValue = "true") boolean newClusterId) { + poller.disarm(); + tbClusterStore.forceClearLicenseClaimToken(); + offlineReportStore.clear(); + adminSettingsService.deleteAdminSettingsByTenantIdAndKey(TenantId.SYS_TENANT_ID, + CommunityGrantFlowStateStore.SETTINGS_KEY); + adminSettingsService.deleteAdminSettingsByTenantIdAndKey(TenantId.SYS_TENANT_ID, + CommunityGrantOfflineReportStore.SETTINGS_KEY); + UUID clusterId = newClusterId ? mintClusterId() : tbClusterStore.getClusterId().orElse(null); + log.warn("Community grant enrollment reset by the test endpoint. Cluster id is now {}", clusterId); + return new CommunityGrantTestResetResult(clusterId, communityGrantService.getStateInfo()); + } + + private UUID mintClusterId() { + UUID clusterId = UUID.randomUUID(); + if (jdbcTemplate.update("UPDATE tb_cluster SET cluster_id = ?::uuid", clusterId.toString()) == 0) { + jdbcTemplate.update("INSERT INTO tb_cluster (cluster_id) VALUES (?::uuid)", clusterId.toString()); + } + return clusterId; + } + + public record CommunityGrantTestResetResult(UUID clusterId, CommunityGrantStateInfo state) { + } + +} diff --git a/application/src/main/java/org/thingsboard/server/install/ThingsboardInstallService.java b/application/src/main/java/org/thingsboard/server/install/ThingsboardInstallService.java index 0f2c37a8dc..508edc321b 100644 --- a/application/src/main/java/org/thingsboard/server/install/ThingsboardInstallService.java +++ b/application/src/main/java/org/thingsboard/server/install/ThingsboardInstallService.java @@ -112,6 +112,7 @@ public class ThingsboardInstallService { systemDataLoaderService.loadSystemWidgets(); installScripts.loadSystemLwm2mResources(); installScripts.loadSystemImagesAndResources(); + entityDatabaseSchemaService.generateClusterIdIfNotExist(); databaseSchemaVersionService.updateSchemaVersion(); } log.info("Upgrade finished successfully!"); @@ -158,6 +159,8 @@ public class ThingsboardInstallService { installScripts.loadSystemLwm2mResources(); installScripts.loadSystemImagesAndResources(); + entityDatabaseSchemaService.generateClusterIdIfNotExist(); + if (loadDemo) { log.info("Loading demo data..."); systemDataLoaderService.loadDemoData(); diff --git a/application/src/main/java/org/thingsboard/server/service/community_grant/CommunityGrantBundleFormatException.java b/application/src/main/java/org/thingsboard/server/service/community_grant/CommunityGrantBundleFormatException.java new file mode 100644 index 0000000000..66fa1e6197 --- /dev/null +++ b/application/src/main/java/org/thingsboard/server/service/community_grant/CommunityGrantBundleFormatException.java @@ -0,0 +1,34 @@ +// SPDX-FileCopyrightText: Copyright The Thingsboard Authors +// SPDX-License-Identifier: Apache-2.0 +package org.thingsboard.server.service.community_grant; + +import lombok.Getter; + +/** + * Why {@link CommunityGrantOfflineBundle#parse} refused a {@code TBICBDL1} file. The message is shown to the + * uploader and stored in an audit row, so it must never carry secrets or the uploaded bytes. + */ +@Getter +public class CommunityGrantBundleFormatException extends IllegalArgumentException { + + /** In the order the checks are made. */ + public enum Reason { + TOO_SHORT, + BAD_MAGIC, + UNSUPPORTED_VERSION, + MANIFEST_LEN_RANGE, + CHECKER_LEN_RANGE, + LENGTH_MISMATCH, + MANIFEST_NOT_UTF8, + MANIFEST_NOT_JSON, + MANIFEST_FIELD + } + + private final Reason reason; + + public CommunityGrantBundleFormatException(Reason reason, String message) { + super(message); + this.reason = reason; + } + +} diff --git a/application/src/main/java/org/thingsboard/server/service/community_grant/CommunityGrantCheckerInput.java b/application/src/main/java/org/thingsboard/server/service/community_grant/CommunityGrantCheckerInput.java new file mode 100644 index 0000000000..775ed7b090 --- /dev/null +++ b/application/src/main/java/org/thingsboard/server/service/community_grant/CommunityGrantCheckerInput.java @@ -0,0 +1,23 @@ +// SPDX-FileCopyrightText: Copyright The Thingsboard Authors +// SPDX-License-Identifier: Apache-2.0 +package org.thingsboard.server.service.community_grant; + +import com.fasterxml.jackson.databind.JsonNode; +import org.thingsboard.common.util.JacksonUtil; + +import java.util.Optional; + +/** + * The portal-decided input for the instance checker, passed through to its {@code TB_IC_INPUT} unread. + */ +public record CommunityGrantCheckerInput(String json) { + + /** Empty unless {@code input} is a non-empty JSON object. */ + public static Optional from(JsonNode input) { + if (input == null || !input.isObject() || input.isEmpty()) { + return Optional.empty(); + } + return Optional.of(new CommunityGrantCheckerInput(JacksonUtil.toString(input))); + } + +} diff --git a/application/src/main/java/org/thingsboard/server/service/community_grant/CommunityGrantCheckerTooLargeException.java b/application/src/main/java/org/thingsboard/server/service/community_grant/CommunityGrantCheckerTooLargeException.java new file mode 100644 index 0000000000..b26e39fbcf --- /dev/null +++ b/application/src/main/java/org/thingsboard/server/service/community_grant/CommunityGrantCheckerTooLargeException.java @@ -0,0 +1,17 @@ +// SPDX-FileCopyrightText: Copyright The Thingsboard Authors +// SPDX-License-Identifier: Apache-2.0 +package org.thingsboard.server.service.community_grant; + +import org.springframework.web.client.RestClientException; + +/** + * Thrown by {@link CommunityGrantPortalClient#downloadChecker} when the checker exceeds the configured size + * cap, whether advertised by Content-Length or discovered mid-stream. + */ +public class CommunityGrantCheckerTooLargeException extends RestClientException { + + public CommunityGrantCheckerTooLargeException(String message) { + super(message); + } + +} diff --git a/application/src/main/java/org/thingsboard/server/service/community_grant/CommunityGrantClusterStatus.java b/application/src/main/java/org/thingsboard/server/service/community_grant/CommunityGrantClusterStatus.java new file mode 100644 index 0000000000..f40cd9d2de --- /dev/null +++ b/application/src/main/java/org/thingsboard/server/service/community_grant/CommunityGrantClusterStatus.java @@ -0,0 +1,9 @@ +// SPDX-FileCopyrightText: Copyright The Thingsboard Authors +// SPDX-License-Identifier: Apache-2.0 +package org.thingsboard.server.service.community_grant; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; + +@JsonIgnoreProperties(ignoreUnknown = true) +public record CommunityGrantClusterStatus(boolean alreadyRegistered) { +} diff --git a/application/src/main/java/org/thingsboard/server/service/community_grant/CommunityGrantFlowStateStore.java b/application/src/main/java/org/thingsboard/server/service/community_grant/CommunityGrantFlowStateStore.java new file mode 100644 index 0000000000..a0be2548f7 --- /dev/null +++ b/application/src/main/java/org/thingsboard/server/service/community_grant/CommunityGrantFlowStateStore.java @@ -0,0 +1,122 @@ +// SPDX-FileCopyrightText: Copyright The Thingsboard Authors +// SPDX-License-Identifier: Apache-2.0 +package org.thingsboard.server.service.community_grant; + +import com.fasterxml.jackson.databind.JsonNode; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.stereotype.Component; +import org.thingsboard.common.util.JacksonUtil; +import org.thingsboard.server.common.data.AdminSettings; +import org.thingsboard.server.common.data.community_grant.CommunityGrantFlowState; +import org.thingsboard.server.common.data.community_grant.CommunityGrantMode; +import org.thingsboard.server.common.data.id.TenantId; +import org.thingsboard.server.dao.settings.AdminSettingsService; +import org.thingsboard.server.exception.DataValidationException; +import org.thingsboard.server.queue.util.TbCoreComponent; + +import java.util.concurrent.locks.ReentrantLock; +import java.util.function.UnaryOperator; + +/** + * Every write goes through {@link #update}, which re-reads under a per-node lock. {@code admin_settings} has no + * unique index on {@code (tenant_id, key)}, so two creates that both commit leave duplicate rows, and every + * later read throws until one is deleted by hand. + */ +@Component +@TbCoreComponent +@RequiredArgsConstructor +@Slf4j +public class CommunityGrantFlowStateStore { + + public static final String SETTINGS_KEY = "communityGrant"; + + private final AdminSettingsService adminSettingsService; + + private final ReentrantLock updateLock = new ReentrantLock(); + + public CommunityGrantFlowState get() { + try { + return readOrThrow(); + } catch (IllegalStateException e) { + // Read-only fallback; a store failure still propagates. + log.warn("Failed to parse the stored community grant flow state, falling back to the initial state", e); + return CommunityGrantFlowState.initial(); + } + } + + /** + * The updater runs a second time against the winner's document when a create race is lost, so it must be + * deterministic: read the clock before the call, not inside it. + */ + public CommunityGrantFlowState update(UnaryOperator updater) { + updateLock.lock(); + try { + AdminSettings settings = adminSettingsService.findAdminSettingsByKey(TenantId.SYS_TENANT_ID, SETTINGS_KEY); + JsonNode stored = settings != null ? settings.getJsonValue() : null; + CommunityGrantFlowState updated = updater.apply(parseOrThrow(settings)); + JsonNode serialized = JacksonUtil.valueToTree(updated); + // Every poll runs an updater; an unchanged document is not written back. + if (serialized.equals(stored)) { + return updated; + } + if (settings == null) { + settings = new AdminSettings(); + settings.setTenantId(TenantId.SYS_TENANT_ID); + settings.setKey(SETTINGS_KEY); + } + settings.setJsonValue(serialized); + try { + adminSettingsService.saveAdminSettings(TenantId.SYS_TENANT_ID, settings); + return updated; + } catch (DataValidationException e) { + if (settings.getId() != null) { + throw e; + } + // Lost a create race to another node: re-apply the change to the winner's row. + AdminSettings winner = adminSettingsService.findAdminSettingsByKey(TenantId.SYS_TENANT_ID, SETTINGS_KEY); + if (winner == null) { + throw e; + } + CommunityGrantFlowState reapplied; + try { + reapplied = updater.apply(parseOrThrow(winner)); + } catch (RuntimeException retryFailure) { + retryFailure.addSuppressed(e); + throw retryFailure; + } + winner.setJsonValue(JacksonUtil.valueToTree(reapplied)); + adminSettingsService.saveAdminSettings(TenantId.SYS_TENANT_ID, winner); + return reapplied; + } + } finally { + updateLock.unlock(); + } + } + + private CommunityGrantFlowState readOrThrow() { + return parseOrThrow(adminSettingsService.findAdminSettingsByKey(TenantId.SYS_TENANT_ID, SETTINGS_KEY)); + } + + private CommunityGrantFlowState parseOrThrow(AdminSettings settings) { + if (settings == null || settings.getJsonValue() == null || settings.getJsonValue().isNull()) { + return CommunityGrantFlowState.initial(); + } + CommunityGrantFlowState flowState; + try { + flowState = JacksonUtil.treeToValue(settings.getJsonValue(), CommunityGrantFlowState.class); + } catch (Exception e) { + // The cause is dropped: it carries the whole stored document, claim token included. + throw new IllegalStateException("Stored community grant flow state at admin_settings[" + SETTINGS_KEY + + "] could not be parsed: " + e.getClass().getSimpleName()); + } + if (flowState == null || flowState.getState() == null) { + return CommunityGrantFlowState.initial(); + } + if (flowState.getMode() == null) { + flowState.setMode(CommunityGrantMode.ONLINE); + } + return flowState; + } + +} diff --git a/application/src/main/java/org/thingsboard/server/service/community_grant/CommunityGrantLibpqDsn.java b/application/src/main/java/org/thingsboard/server/service/community_grant/CommunityGrantLibpqDsn.java new file mode 100644 index 0000000000..608adff2dc --- /dev/null +++ b/application/src/main/java/org/thingsboard/server/service/community_grant/CommunityGrantLibpqDsn.java @@ -0,0 +1,77 @@ +// SPDX-FileCopyrightText: Copyright The Thingsboard Authors +// SPDX-License-Identifier: Apache-2.0 +package org.thingsboard.server.service.community_grant; + +import java.net.URI; +import java.net.URISyntaxException; +import java.nio.charset.StandardCharsets; + +/** + * Rewrites this deployment's JDBC url as the libpq connection string the instance checker's driver + * understands. + */ +final class CommunityGrantLibpqDsn { + + private static final String JDBC_PREFIX = "jdbc:"; + private static final String JDBC_POSTGRESQL_PREFIX = "jdbc:postgresql:"; + private static final String POSTGRES_SCHEME = "postgres://"; + + private CommunityGrantLibpqDsn() { + } + + /** + * The JDBC query string is dropped: its parameters are the JDBC driver's, not libpq's. + * + * @throws IllegalStateException if the url is not a PostgreSQL JDBC url naming a single host and a + * database, or the username is blank + */ + static String from(String jdbcUrl, String username, String password) { + if (jdbcUrl == null || !jdbcUrl.startsWith(JDBC_POSTGRESQL_PREFIX)) { + throw new IllegalStateException("The datasource url is not a PostgreSQL JDBC url"); + } + URI jdbc; + try { + jdbc = new URI(jdbcUrl.substring(JDBC_PREFIX.length())); + } catch (URISyntaxException e) { + // The cause is dropped: its message quotes the url, which may carry the database password. + throw new IllegalStateException("The datasource url is not a valid PostgreSQL JDBC url"); + } + if (jdbc.getHost() == null) { + throw new IllegalStateException("The datasource url does not name a single host"); + } + String path = jdbc.getPath(); + if (path == null || path.length() <= 1) { + throw new IllegalStateException("The datasource url does not name a database"); + } + if (username == null || username.isBlank()) { + throw new IllegalStateException("The datasource has no configured username"); + } + String userInfo = percentEncodeUserInfoComponent(username) + ":" + + percentEncodeUserInfoComponent(password == null ? "" : password); + try { + // Spliced in rather than passed to the URI constructor, which would escape every '%' above again. + String withoutUserInfo = new URI("postgres", null, jdbc.getHost(), jdbc.getPort(), path, null, null) + .toASCIIString(); + return POSTGRES_SCHEME + userInfo + "@" + withoutUserInfo.substring(POSTGRES_SCHEME.length()); + } catch (URISyntaxException e) { + // The cause is dropped for the same reason as above. + throw new IllegalStateException("Failed to build the instance check connection string"); + } + } + + /** Escapes everything outside the RFC 3986 unreserved set, ':' and '%' included. */ + private static String percentEncodeUserInfoComponent(String value) { + StringBuilder encoded = new StringBuilder(); + for (byte b : value.getBytes(StandardCharsets.UTF_8)) { + int c = b & 0xFF; + if ((c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || (c >= '0' && c <= '9') + || c == '-' || c == '.' || c == '_' || c == '~') { + encoded.append((char) c); + } else { + encoded.append('%').append(String.format("%02X", c)); + } + } + return encoded.toString(); + } + +} diff --git a/application/src/main/java/org/thingsboard/server/service/community_grant/CommunityGrantOfflineBundle.java b/application/src/main/java/org/thingsboard/server/service/community_grant/CommunityGrantOfflineBundle.java new file mode 100644 index 0000000000..09d261e7ae --- /dev/null +++ b/application/src/main/java/org/thingsboard/server/service/community_grant/CommunityGrantOfflineBundle.java @@ -0,0 +1,314 @@ +// SPDX-FileCopyrightText: Copyright The Thingsboard Authors +// SPDX-License-Identifier: Apache-2.0 +package org.thingsboard.server.service.community_grant; + +import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonParser; +import com.fasterxml.jackson.core.JsonToken; +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.json.JsonMapper; +import org.thingsboard.server.service.community_grant.CommunityGrantBundleFormatException.Reason; + +import java.io.IOException; +import java.nio.ByteBuffer; +import java.nio.CharBuffer; +import java.nio.charset.CharacterCodingException; +import java.nio.charset.CharsetDecoder; +import java.nio.charset.CodingErrorAction; +import java.nio.charset.StandardCharsets; +import java.util.ArrayDeque; +import java.util.Arrays; +import java.util.Deque; +import java.util.HashSet; +import java.util.List; +import java.util.Set; +import java.util.UUID; +import java.util.regex.Pattern; + +/** + * The {@code TBICBDL1} offline enrollment bundle. + *
    + * offset  width  field         value / constraint
    + * 0       8      MAGIC         "TBICBDL1"
    + * 8       1      VERSION       0x01
    + * 9       4      MANIFEST_LEN  uint32 big-endian, 1..8192
    + * 13      4      CHECKER_LEN   uint32 big-endian, >= 1
    + * 17      74     RELSIG        a complete TBICSIG1 file, verbatim
    + * 91      M      MANIFEST      UTF-8 JSON
    + * 91+M    C      CHECKER       the executable image
    + * 
    + * {@code RELSIG} is not inspected here; {@link CommunityGrantReleaseSignatureVerifier} does that. + */ +public record CommunityGrantOfflineBundle(String os, String arch, UUID clusterId, String checkerFileName, + long issuedAt, long challengeExpiresAt, + CommunityGrantCheckerInput checkerInput, byte[] signature, byte[] checker) { + + public static final int HEADER_LEN = 91; + public static final int MIN_MANIFEST_LEN = 1; + public static final int MAX_MANIFEST_LEN = 8192; + + public static final int MAX_OVERHEAD_BYTES = HEADER_LEN + MAX_MANIFEST_LEN; + + private static final byte[] MAGIC = {'T', 'B', 'I', 'C', 'B', 'D', 'L', '1'}; + private static final byte VERSION_V1 = 0x01; + private static final int RELSIG_OFFSET = 17; + private static final int RELSIG_LEN = 74; + private static final long MIN_CHECKER_LEN = 1; + + private static final int MANIFEST_LEN_OFFSET = 9; + private static final int CHECKER_LEN_OFFSET = 13; + + private static final int MAX_CHECKER_FILE_NAME_LEN = 255; + private static final int MAX_QUOTED_KEY_LEN = 64; + + private static final List KNOWN_OS = List.of("linux", "darwin", "windows"); + private static final List KNOWN_ARCH = List.of("amd64", "arm64"); + + /** {@link UUID#fromString} alone is far too lenient. */ + private static final Pattern CANONICAL_UUID = + Pattern.compile("[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}"); + + /** Duplicate keys and trailing content are rejected: parsers disagree on which duplicate wins. */ + private static final ObjectMapper MANIFEST_MAPPER = JsonMapper.builder() + .enable(DeserializationFeature.FAIL_ON_READING_DUP_TREE_KEY) + .enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS) + .build(); + + /** + * @throws CommunityGrantBundleFormatException with a message safe to show the uploader and to store in + * an audit row. + */ + public static CommunityGrantOfflineBundle parse(byte[] data) { + int total = data == null ? 0 : data.length; + if (total < HEADER_LEN) { + throw new CommunityGrantBundleFormatException(Reason.TOO_SHORT, "The uploaded file is " + total + + " bytes, shorter than the " + HEADER_LEN + "-byte enrollment bundle header, so it is not" + + " a ThingsBoard enrollment bundle."); + } + if (!Arrays.equals(data, 0, MAGIC.length, MAGIC, 0, MAGIC.length)) { + throw new CommunityGrantBundleFormatException(Reason.BAD_MAGIC, "The uploaded file is not a" + + " ThingsBoard enrollment bundle: it does not carry the marker every bundle begins with."); + } + if (data[MAGIC.length] != VERSION_V1) { + throw new CommunityGrantBundleFormatException(Reason.UNSUPPORTED_VERSION, "The enrollment bundle" + + " declares format version " + (data[MAGIC.length] & 0xFF) + ", and this deployment" + + " supports version " + VERSION_V1 + " only."); + } + // Unsigned: read into a long so 0xFFFFFFFF cannot wrap the length arithmetic. + long manifestLen = readUnsignedInt(data, MANIFEST_LEN_OFFSET); + long checkerLen = readUnsignedInt(data, CHECKER_LEN_OFFSET); + if (manifestLen < MIN_MANIFEST_LEN || manifestLen > MAX_MANIFEST_LEN) { + throw new CommunityGrantBundleFormatException(Reason.MANIFEST_LEN_RANGE, "The enrollment bundle" + + " declares a manifest of " + manifestLen + " bytes, outside the permitted range of " + + MIN_MANIFEST_LEN + " to " + MAX_MANIFEST_LEN + " bytes, so the file is damaged."); + } + if (checkerLen < MIN_CHECKER_LEN) { + throw new CommunityGrantBundleFormatException(Reason.CHECKER_LEN_RANGE, "The enrollment bundle" + + " declares a checker of " + checkerLen + " bytes, so the file is damaged."); + } + long expectedTotal = HEADER_LEN + manifestLen + checkerLen; + if (expectedTotal != total) { + throw new CommunityGrantBundleFormatException(Reason.LENGTH_MISMATCH, "The enrollment bundle is" + + " damaged or truncated: its declared " + manifestLen + "-byte manifest and " + + checkerLen + "-byte checker need a file of " + expectedTotal + " bytes, but the" + + " uploaded file is " + total + " bytes. Download the bundle again."); + } + JsonNode manifest = readManifest(data, (int) manifestLen); + return new CommunityGrantOfflineBundle( + readEnum(manifest, "os", KNOWN_OS), + readEnum(manifest, "arch", KNOWN_ARCH), + readClusterId(manifest), + readCheckerFileName(manifest), + readIssuedAt(manifest), + readTimestamp(manifest, "challengeExpiresAt"), + readCheckerInput(manifest), + Arrays.copyOfRange(data, RELSIG_OFFSET, RELSIG_OFFSET + RELSIG_LEN), + Arrays.copyOfRange(data, HEADER_LEN + (int) manifestLen, total)); + } + + /** Strictly later: the portal still accepts the deadline instant itself. */ + public boolean isChallengeExpired(long now) { + return now > challengeExpiresAt; + } + + private static long readUnsignedInt(byte[] data, int offset) { + return ((long) (data[offset] & 0xFF) << 24) + | ((long) (data[offset + 1] & 0xFF) << 16) + | ((long) (data[offset + 2] & 0xFF) << 8) + | (data[offset + 3] & 0xFF); + } + + /** A strict decoder: a substituting one would report binary garbage as bad JSON rather than bad text. */ + private static JsonNode readManifest(byte[] data, int manifestLen) { + CharsetDecoder decoder = StandardCharsets.UTF_8.newDecoder() + .onMalformedInput(CodingErrorAction.REPORT) + .onUnmappableCharacter(CodingErrorAction.REPORT); + CharBuffer text; + try { + text = decoder.decode(ByteBuffer.wrap(data, HEADER_LEN, manifestLen)); + } catch (CharacterCodingException e) { + throw new CommunityGrantBundleFormatException(Reason.MANIFEST_NOT_UTF8, "The enrollment bundle's" + + " manifest is not readable text, so the file is damaged. Download the bundle again."); + } + String manifestJson = text.toString(); + JsonNode manifest; + try { + manifest = MANIFEST_MAPPER.readTree(manifestJson); + } catch (JsonParseException e) { + throw notAJsonObject(); + } catch (IOException e) { + // Not a syntax error, so the duplicate-key refusal; Jackson's message does not name the key reliably. + String duplicate = findDuplicateKey(manifestJson); + if (duplicate == null) { + throw notAJsonObject(); + } + throw fieldError(quoteKey(duplicate), "appears more than once"); + } + if (manifest == null || !manifest.isObject()) { + throw notAJsonObject(); + } + int declaredVersion = readInt(manifest, "bundleVersion"); + if (declaredVersion != VERSION_V1) { + throw fieldError("bundleVersion", "must be " + VERSION_V1); + } + return manifest; + } + + /** Scans the root value only, so trailing junk is not blamed for a duplicate key. */ + private static String findDuplicateKey(String manifestJson) { + Deque> seenPerObject = new ArrayDeque<>(); + try (JsonParser parser = MANIFEST_MAPPER.createParser(manifestJson)) { + for (JsonToken token = parser.nextToken(); token != null; token = parser.nextToken()) { + if (token == JsonToken.START_OBJECT) { + seenPerObject.push(new HashSet<>()); + } else if (token == JsonToken.END_OBJECT) { + seenPerObject.pop(); + if (seenPerObject.isEmpty()) { + break; + } + } else if (token == JsonToken.FIELD_NAME && !seenPerObject.peek().add(parser.currentName())) { + return parser.currentName(); + } + } + } catch (IOException e) { + return null; + } + return null; + } + + private static CommunityGrantBundleFormatException notAJsonObject() { + return new CommunityGrantBundleFormatException(Reason.MANIFEST_NOT_JSON, "The enrollment bundle's" + + " manifest is not a JSON object, so the file is damaged. Download the bundle again."); + } + + /** Never quotes the offending value: the message is shown to the uploader and audited. */ + private static CommunityGrantBundleFormatException fieldError(String key, String problem) { + return new CommunityGrantBundleFormatException(Reason.MANIFEST_FIELD, "The enrollment bundle's" + + " manifest is not usable: \"" + key + "\" " + problem + ". Download the bundle again."); + } + + /** The one uploaded string a refusal quotes, so it is bounded and stripped of control characters. */ + private static String quoteKey(String key) { + String quoted = key; + if (quoted.length() > MAX_QUOTED_KEY_LEN) { + // Never cut between the halves of a surrogate pair. + int end = Character.isHighSurrogate(quoted.charAt(MAX_QUOTED_KEY_LEN - 1)) + ? MAX_QUOTED_KEY_LEN - 1 : MAX_QUOTED_KEY_LEN; + quoted = quoted.substring(0, end) + "..."; + } + return quoted.replaceAll("\\p{Cntrl}", "?"); + } + + private static JsonNode required(JsonNode manifest, String key) { + JsonNode value = manifest.get(key); + if (value == null || value.isNull()) { + throw fieldError(key, "is missing"); + } + return value; + } + + private static String readString(JsonNode manifest, String key) { + JsonNode value = required(manifest, key); + if (!value.isTextual()) { + throw fieldError(key, "must be a string"); + } + return value.textValue(); + } + + private static int readInt(JsonNode manifest, String key) { + JsonNode value = required(manifest, key); + if (!value.isIntegralNumber() || !value.canConvertToInt()) { + throw fieldError(key, "must be a whole number"); + } + return value.intValue(); + } + + private static long readTimestamp(JsonNode manifest, String key) { + JsonNode value = required(manifest, key); + if (!value.isIntegralNumber() || !value.canConvertToLong()) { + throw fieldError(key, "must be a whole number of milliseconds"); + } + long millis = value.longValue(); + if (millis <= 0) { + throw fieldError(key, "must be a positive number of milliseconds"); + } + return millis; + } + + private static String readEnum(JsonNode manifest, String key, List permitted) { + String value = readString(manifest, key); + if (!permitted.contains(value)) { + throw fieldError(key, "must be one of " + String.join(", ", permitted)); + } + return value; + } + + private static UUID readClusterId(JsonNode manifest) { + String value = readString(manifest, "clusterId"); + if (!CANONICAL_UUID.matcher(value).matches()) { + throw fieldError("clusterId", "must be a canonical lowercase UUID"); + } + return UUID.fromString(value); + } + + private static String readCheckerFileName(JsonNode manifest) { + String value = readString(manifest, "checkerFileName"); + if (value.isEmpty() || value.length() > MAX_CHECKER_FILE_NAME_LEN) { + throw fieldError("checkerFileName", "must be between 1 and " + MAX_CHECKER_FILE_NAME_LEN + + " characters"); + } + // Logged verbatim, so control characters could forge log lines. + if (value.indexOf('/') >= 0 || value.indexOf('\\') >= 0 || value.contains("..") + || containsControlCharacter(value)) { + throw fieldError("checkerFileName", + "must not contain a path separator, \"..\" or a control character"); + } + return value; + } + + private static boolean containsControlCharacter(String value) { + for (int i = 0; i < value.length(); i++) { + char c = value.charAt(i); + if (c < 0x20 || c == 0x7F) { + return true; + } + } + return false; + } + + private static long readIssuedAt(JsonNode manifest) { + long issuedAt = readTimestamp(manifest, "issuedAt"); + if (issuedAt > readTimestamp(manifest, "challengeExpiresAt")) { + throw fieldError("issuedAt", "must not be later than the challenge's expiry"); + } + return issuedAt; + } + + private static CommunityGrantCheckerInput readCheckerInput(JsonNode manifest) { + return CommunityGrantCheckerInput.from(manifest.get("checkerInput")) + .orElseThrow(() -> fieldError("checkerInput", "must be a non-empty object")); + } + +} diff --git a/application/src/main/java/org/thingsboard/server/service/community_grant/CommunityGrantOfflineReportStore.java b/application/src/main/java/org/thingsboard/server/service/community_grant/CommunityGrantOfflineReportStore.java new file mode 100644 index 0000000000..3909e60c21 --- /dev/null +++ b/application/src/main/java/org/thingsboard/server/service/community_grant/CommunityGrantOfflineReportStore.java @@ -0,0 +1,155 @@ +// SPDX-FileCopyrightText: Copyright The Thingsboard Authors +// SPDX-License-Identifier: Apache-2.0 +package org.thingsboard.server.service.community_grant; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.node.ObjectNode; +import lombok.AccessLevel; +import lombok.RequiredArgsConstructor; +import lombok.Setter; +import lombok.extern.slf4j.Slf4j; +import org.springframework.stereotype.Component; +import org.thingsboard.common.util.JacksonUtil; +import org.thingsboard.server.common.data.AdminSettings; +import org.thingsboard.server.common.data.StringUtils; +import org.thingsboard.server.common.data.id.TenantId; +import org.thingsboard.server.dao.settings.AdminSettingsService; +import org.thingsboard.server.queue.util.TbCoreComponent; + +import java.util.Optional; +import java.util.concurrent.atomic.AtomicReference; +import java.util.function.LongSupplier; + +/** + * The last offline report: a durable row plus a node-local copy that outranks it until a newer write lands, so + * a node whose durable write failed still serves what it produced. Ordering relies on wall clocks across + * nodes. {@link #clear()} writes a tombstone so "cleared" differs from "never stored". + */ +@Component +@TbCoreComponent +@RequiredArgsConstructor +@Slf4j +public class CommunityGrantOfflineReportStore { + + public static final String SETTINGS_KEY = "communityGrantReport"; + private static final String REPORT_FIELD = "report"; + private static final String UPDATED_AT_FIELD = "updatedAt"; + + private final AdminSettingsService adminSettingsService; + + private final AtomicReference nodeLocalReport = new AtomicReference<>(); + + @Setter(AccessLevel.PACKAGE) + private LongSupplier clock = System::currentTimeMillis; + + /** + * The last report, or empty when there is none. A failed read propagates unless this node has a copy of + * its own to answer with: a read that did not reach the database is no evidence of absence. + */ + public Optional get() { + LocalReport localReport = nodeLocalReport.get(); + Optional local = Optional.ofNullable(localReport) + .map(LocalReport::report) + .filter(StringUtils::isNotEmpty); + StoredReport stored; + try { + stored = readStored(); + } catch (RuntimeException e) { + if (localReport == null) { + throw e; + } + log.warn("Failed to read the stored community grant offline report; " + + "serving what this node last did itself", e); + return local; + } + if (stored == null) { + return local; + } + if (localReport != null && !localReport.durable() + && stored.updatedAt() <= localReport.writtenAt()) { + return local; + } + if (stored.report() == null) { + nodeLocalReport.compareAndSet(localReport, null); + return Optional.empty(); + } + if (localReport != null && !localReport.durable()) { + // Dropped so a later write carrying an earlier instant cannot revive it. + nodeLocalReport.compareAndSet(localReport, null); + } + return Optional.of(stored.report()); + } + + public void put(String report) { + long writtenAt = clock.getAsLong(); + LocalReport pending = new LocalReport(report, false, writtenAt); + nodeLocalReport.set(pending); + if (writeStored(report, writtenAt)) { + nodeLocalReport.compareAndSet(pending, new LocalReport(report, true, writtenAt)); + } + } + + /** + * Retires the report along with the enrollment it belonged to. Until the durable write lands, the local + * copy answers empty on this node. + */ + public void clear() { + long writtenAt = clock.getAsLong(); + LocalReport pending = new LocalReport(null, false, writtenAt); + nodeLocalReport.set(pending); + if (writeStored(null, writtenAt)) { + nodeLocalReport.compareAndSet(pending, null); + } + } + + /** {@code null} for no usable row; a {@link StoredReport} with a {@code null} report for the tombstone. */ + private StoredReport readStored() { + AdminSettings settings = adminSettingsService.findAdminSettingsByKey(TenantId.SYS_TENANT_ID, SETTINGS_KEY); + if (settings == null || settings.getJsonValue() == null) { + return null; + } + JsonNode value = settings.getJsonValue(); + JsonNode report = value.get(REPORT_FIELD); + if (report == null) { + return null; + } + long updatedAt = value.path(UPDATED_AT_FIELD).asLong(); + if (report.isNull()) { + return new StoredReport(null, updatedAt); + } + return report.isTextual() && !report.asText().isEmpty() + ? new StoredReport(report.asText(), updatedAt) + : null; + } + + /** A null report writes the tombstone. Returns whether the write reached the database. */ + private boolean writeStored(String report, long updatedAt) { + try { + AdminSettings settings = adminSettingsService.findAdminSettingsByKey(TenantId.SYS_TENANT_ID, SETTINGS_KEY); + if (settings == null) { + settings = new AdminSettings(); + settings.setTenantId(TenantId.SYS_TENANT_ID); + settings.setKey(SETTINGS_KEY); + } + ObjectNode value = JacksonUtil.newObjectNode(); + if (report == null) { + value.putNull(REPORT_FIELD); + } else { + value.put(REPORT_FIELD, report); + } + value.put(UPDATED_AT_FIELD, updatedAt); + settings.setJsonValue(value); + adminSettingsService.saveAdminSettings(TenantId.SYS_TENANT_ID, settings); + return true; + } catch (RuntimeException e) { + log.warn("Failed to store the community grant offline report", e); + return false; + } + } + + /** A {@code null} report stands for a {@link #clear()}. */ + private record LocalReport(String report, boolean durable, long writtenAt) {} + + private record StoredReport(String report, long updatedAt) {} + +} diff --git a/application/src/main/java/org/thingsboard/server/service/community_grant/CommunityGrantPlatform.java b/application/src/main/java/org/thingsboard/server/service/community_grant/CommunityGrantPlatform.java new file mode 100644 index 0000000000..7858638b8c --- /dev/null +++ b/application/src/main/java/org/thingsboard/server/service/community_grant/CommunityGrantPlatform.java @@ -0,0 +1,61 @@ +// SPDX-FileCopyrightText: Copyright The Thingsboard Authors +// SPDX-License-Identifier: Apache-2.0 +package org.thingsboard.server.service.community_grant; + +import org.thingsboard.server.common.data.StringUtils; + +import java.util.List; +import java.util.Locale; + +/** + * The host platform in the vocabulary the portal's {@code /checker} endpoint expects. + */ +public record CommunityGrantPlatform(String os, String arch) { + + private static final List KNOWN_OS = List.of("darwin", "windows", "linux"); + private static final List KNOWN_ARCH = List.of("amd64", "arm64"); + + public static CommunityGrantPlatform current() { + return of(System.getProperty("os.name", ""), System.getProperty("os.arch", "")); + } + + static CommunityGrantPlatform of(String rawOsName, String rawOsArch) { + String osName = rawOsName.toLowerCase(Locale.ROOT); + String osArch = rawOsArch.toLowerCase(Locale.ROOT); + String os; + if (osName.contains("mac") || osName.contains("darwin")) { + os = "darwin"; + } else if (osName.contains("win")) { + os = "windows"; + } else { + os = "linux"; + } + String arch; + if (osArch.contains("aarch64") || osArch.contains("arm64")) { + arch = "arm64"; + } else if (osArch.contains("amd64") || osArch.contains("x86_64") || osArch.contains("x64")) { + arch = "amd64"; + } else { + throw new IllegalStateException("Unsupported architecture for the instance checker: " + osArch); + } + return new CommunityGrantPlatform(os, arch); + } + + public String checkerFileName() { + return "windows".equals(os) ? "tb-instance-check.exe" : "tb-instance-check"; + } + + /** A legibility check, not a security one: true only for a name that spells out another os or arch. */ + public boolean namesAnotherPlatform(String fileName) { + if (StringUtils.isEmpty(fileName)) { + return false; + } + String normalized = fileName.toLowerCase(Locale.ROOT); + return namesAnother(normalized, KNOWN_OS, os) || namesAnother(normalized, KNOWN_ARCH, arch); + } + + private static boolean namesAnother(String fileName, List known, String mine) { + return known.stream().anyMatch(token -> !token.equals(mine) && fileName.contains(token)); + } + +} diff --git a/application/src/main/java/org/thingsboard/server/service/community_grant/CommunityGrantPoller.java b/application/src/main/java/org/thingsboard/server/service/community_grant/CommunityGrantPoller.java new file mode 100644 index 0000000000..0b192ad224 --- /dev/null +++ b/application/src/main/java/org/thingsboard/server/service/community_grant/CommunityGrantPoller.java @@ -0,0 +1,517 @@ +// SPDX-FileCopyrightText: Copyright The Thingsboard Authors +// SPDX-License-Identifier: Apache-2.0 +package org.thingsboard.server.service.community_grant; + +import jakarta.annotation.PreDestroy; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.stereotype.Component; +import org.thingsboard.common.util.ThingsBoardExecutors; +import org.thingsboard.server.common.data.StringUtils; +import org.thingsboard.server.common.data.community_grant.CommunityGrantFlowState; +import org.thingsboard.server.common.data.community_grant.CommunityGrantMode; +import org.thingsboard.server.common.data.community_grant.CommunityGrantParkReason; +import org.thingsboard.server.common.data.community_grant.CommunityGrantState; +import org.thingsboard.server.common.data.id.TenantId; +import org.thingsboard.server.common.msg.queue.ServiceType; +import org.thingsboard.server.dao.subscription.TbClusterStore; +import org.thingsboard.server.queue.discovery.PartitionService; +import org.thingsboard.server.queue.discovery.TbApplicationEventListener; +import org.thingsboard.server.queue.discovery.event.PartitionChangeEvent; +import org.thingsboard.server.queue.util.AfterStartUp; +import org.thingsboard.server.queue.util.TbCoreComponent; + +import java.util.Optional; +import java.util.UUID; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.ScheduledFuture; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicLong; +import java.util.concurrent.locks.ReentrantLock; +import java.util.function.UnaryOperator; + +/** + * Polls the portal about this deployment's claim and projects the answer onto the local state. Only the node + * owning the system tenant's TB_CORE partition runs the loop; it supervises for flows other nodes began. + * On the offline rail it never calls out, and only enforces the sign-up deadline. + */ +@Component +@TbCoreComponent +@RequiredArgsConstructor +@Slf4j +public class CommunityGrantPoller extends TbApplicationEventListener { + + static final long MIN_POLL_INTERVAL_MS = 2000; + static final int MAX_RETRY_AFTER_SEC = 3600; + static final long MAX_FAILURE_BACKOFF_MS = TimeUnit.MINUTES.toMillis(10); + static final int CONSECUTIVE_FAILURE_WARN_THRESHOLD = 5; + + static final int MAX_POLL_FAILURES = 200; + + /** Several of these failures are permanent, and every retry re-downloads the whole checker. */ + static final int MAX_VERIFICATION_FAILURES = 5; + + @Value("${community-grant.enabled:true}") + private boolean enabled; + + @Value("${community-grant.fast-poll-interval-ms:3000}") + private long fastPollIntervalMs; + + @Value("${community-grant.fast-poll-window-ms:120000}") + private long fastPollWindowMs; + + @Value("${community-grant.slow-poll-interval-ms:30000}") + private long slowPollIntervalMs; + + /** Matched to the portal's claim-token lifetime (24h). */ + @Value("${community-grant.sign-up-deadline-ms:86400000}") + private long signUpDeadlineMs; + + @Value("${community-grant.supervise-interval-ms:30000}") + private long superviseIntervalMs; + + private final PartitionService partitionService; + private final TbClusterStore tbClusterStore; + private final CommunityGrantFlowStateStore flowStateStore; + private final CommunityGrantPortalClient portalClient; + private final CommunityGrantReportRunner reportRunner; + + private final ScheduledExecutorService scheduler = + ThingsBoardExecutors.newSingleThreadScheduledExecutor("tb-community-grant-poller"); + private final AtomicBoolean armed = new AtomicBoolean(false); + private final ReentrantLock pollLock = new ReentrantLock(); + private final AtomicInteger consecutiveFailures = new AtomicInteger(0); + private final AtomicInteger verificationFailures = new AtomicInteger(0); + + /** Stops a poll still running across a disarm and re-arm from rescheduling beside the new chain. */ + private final AtomicLong generation = new AtomicLong(); + + private volatile ScheduledFuture pendingPoll; + private volatile ScheduledFuture supervisor; + private volatile long pollingSince; + private volatile long lastPollTs; + + /** The claim token the current budgets and fast window belong to. */ + private volatile String pollingToken; + + @AfterStartUp(order = AfterStartUp.REGULAR_SERVICE) + public void init() { + if (enabled && isSystemTenantPartitionMine()) { + startSupervising(); + armIfPollable(); + } + } + + @Override + protected void onTbApplicationEvent(PartitionChangeEvent event) { + if (!enabled) { + return; + } + if (isSystemTenantPartitionMine()) { + startSupervising(); + armIfPollable(); + } else { + stopSupervising(); + disarm(); + } + } + + @Override + protected boolean filterTbApplicationEvent(PartitionChangeEvent event) { + return ServiceType.TB_CORE == event.getServiceType(); + } + + /** A no-op off the partition owner, whose supervisor picks the flow up instead. Arms offline flows too. */ + public void arm() { + if (!enabled) { + return; + } + if (!isSystemTenantPartitionMine()) { + log.debug("Not arming the community grant poller: this node does not own the system tenant's " + + "TB_CORE partition"); + return; + } + if (armed.compareAndSet(false, true)) { + pollingSince = System.currentTimeMillis(); + verificationFailures.set(0); + consecutiveFailures.set(0); + cancelPendingPoll(); + schedule(fastPollIntervalMs, generation.incrementAndGet()); + } + } + + public void disarm() { + armed.set(false); + cancelPendingPoll(); + } + + boolean isArmed() { + return armed.get(); + } + + @PreDestroy + public void stop() { + stopSupervising(); + disarm(); + scheduler.shutdownNow(); + } + + private synchronized void startSupervising() { + if (supervisor != null) { + return; + } + try { + supervisor = scheduler.scheduleWithFixedDelay(this::supervise, + superviseIntervalMs, superviseIntervalMs, TimeUnit.MILLISECONDS); + } catch (Exception e) { + log.warn("Failed to schedule the community grant supervisor", e); + } + } + + private synchronized void stopSupervising() { + ScheduledFuture pending = supervisor; + if (pending != null) { + pending.cancel(false); + supervisor = null; + } + } + + void supervise() { + try { + if (!armed.get()) { + armIfPollable(); + } + } catch (Throwable e) { + // A fixed-delay task that throws is never run again. + log.debug("The community grant supervisor tick failed", e); + } + } + + private boolean isSystemTenantPartitionMine() { + try { + return partitionService.resolve(ServiceType.TB_CORE, TenantId.SYS_TENANT_ID, TenantId.SYS_TENANT_ID).isMyPartition(); + } catch (Exception e) { + log.debug("Failed to resolve the system tenant partition", e); + return false; + } + } + + /** Offline, nothing ever answers past the sign-up form, so there is no work left once it is done. */ + private static boolean hasWorkLeft(CommunityGrantFlowState state) { + return state.getMode() != CommunityGrantMode.OFFLINE + || state.getState() == CommunityGrantState.AWAITING_SIGNUP; + } + + private void armIfPollable() { + boolean pollable; + try { + CommunityGrantFlowState stored = flowStateStore.get(); + pollable = stored.getState().isPollable() && hasWorkLeft(stored); + } catch (Exception e) { + log.warn("Failed to read the stored community grant state, not arming the community grant poller", e); + return; + } + if (pollable) { + arm(); + } + } + + private void schedule(long delayMs, long gen) { + if (!armed.get() || gen != generation.get()) { + return; + } + try { + pendingPoll = scheduler.schedule(() -> pollAndReschedule(gen), delayMs, TimeUnit.MILLISECONDS); + } catch (Exception e) { + // Cleared so arm() can start a new chain. + armed.set(false); + log.warn("Failed to schedule the next community grant poll", e); + } + } + + private void cancelPendingPoll() { + ScheduledFuture pending = pendingPoll; + if (pending != null) { + pending.cancel(false); + pendingPoll = null; + } + } + + void pollAndReschedule() { + pollAndReschedule(generation.get()); + } + + private void pollAndReschedule(long gen) { + if (gen != generation.get()) { + return; + } + long nextDelay; + try { + nextDelay = nextDelay(poll()); + } catch (Throwable e) { + // Throwable, so an Error cannot cancel the scheduled task. + int failures = consecutiveFailures.incrementAndGet(); + if (failures >= CONSECUTIVE_FAILURE_WARN_THRESHOLD) { + log.warn("Failed to poll the license portal ({} consecutive failures)", failures, e); + } else { + log.debug("Failed to poll the license portal", e); + } + onPollFailure(failures); + nextDelay = failureDelay(failures); + } + schedule(nextDelay, gen); + } + + /** An unreachable portal never answers, so its endings are enforced locally. */ + private void onPollFailure(int failures) { + try { + String token = tbClusterStore.getLicenseClaimToken().orElse(null); + if (StringUtils.isEmpty(token)) { + return; + } + long now = System.currentTimeMillis(); + if (parkIfSignUpAbandoned(token, flowStateStore.get(), now)) { + return; + } + if (failures >= MAX_POLL_FAILURES) { + log.warn("Parking the community grant flow after {} consecutive poll failures", failures); + park(token, now, CommunityGrantParkReason.PORTAL_UNREACHABLE); + } + } catch (Exception e) { + log.debug("Failed to park the community grant flow after a poll failure", e); + } + } + + /** + * @return the portal's own pacing instruction, or {@code null} when this tick did not reach it. + */ + Integer poll() { + if (!armed.get()) { + return null; + } + String token = tbClusterStore.getLicenseClaimToken().orElse(null); + if (StringUtils.isEmpty(token)) { + disarm(); + return null; + } + if (!token.equals(pollingToken)) { + // A new token is a new enrollment. Re-based here: on another node, the owner never sees start(). + if (pollingToken != null) { + pollingSince = System.currentTimeMillis(); + verificationFailures.set(0); + consecutiveFailures.set(0); + } + pollingToken = token; + } + CommunityGrantFlowState current = flowStateStore.get(); + if (current.getMode() == CommunityGrantMode.OFFLINE) { + if (!hasWorkLeft(current)) { + disarm(); + return null; + } + parkIfSignUpAbandoned(token, current, System.currentTimeMillis()); + return null; + } + UUID clusterId = tbClusterStore.getClusterId().orElse(null); + if (clusterId == null) { + disarm(); + return null; + } + if (System.currentTimeMillis() - lastPollTs < MIN_POLL_INTERVAL_MS || !pollLock.tryLock()) { + return null; + } + try { + lastPollTs = System.currentTimeMillis(); + CommunityGrantPortalStatus status = portalClient.getStatus(token, clusterId); + // Reset only once the portal has actually answered. + consecutiveFailures.set(0); + if (status == null) { + return null; + } + apply(token, status); + return status.retryAfterSec(); + } finally { + pollLock.unlock(); + } + } + + /** The portal's {@code retryAfterSec}, when positive, wins over the local cadence. */ + long nextDelay(Integer retryAfterSec) { + if (retryAfterSec != null && retryAfterSec > 0) { + return TimeUnit.SECONDS.toMillis(Math.min(retryAfterSec, MAX_RETRY_AFTER_SEC)); + } + return System.currentTimeMillis() - pollingSince < fastPollWindowMs ? fastPollIntervalMs : slowPollIntervalMs; + } + + long failureDelay(int failures) { + return Math.min(nextDelay(null) << Math.min(failures - 1, 10), MAX_FAILURE_BACKOFF_MS); + } + + void apply(String token, CommunityGrantPortalStatus status) { + long now = System.currentTimeMillis(); + String statusValue = status.status(); + if (statusValue == null) { + // An empty or partial 200 body. + log.debug("Ignoring a portal status response with no status value"); + return; + } + CommunityGrantState terminalState = terminalStateFor(statusValue); + if (terminalState != null) { + retire(token, terminalState, now, null); + return; + } + switch (statusValue) { + case "AWAITING_SIGNUP" -> onAwaitingSignup(token, now); + case "VERIFICATION_REQUIRED" -> onVerificationRequired(token, status, now); + case "UNDER_REVIEW" -> onUnderReview(token, now); + case "EXPIRED" -> park(token, now, CommunityGrantParkReason.LINK_EXPIRED); + default -> log.debug("Ignoring an unrecognized portal status"); + } + } + + /** @return the state the flow ends in, or {@code null} if the status is not a terminal one. */ + private static CommunityGrantState terminalStateFor(String status) { + return switch (status) { + case "DONE" -> CommunityGrantState.REGISTERED; + case "WRONG_INSTALLATION" -> CommunityGrantState.WRONG_INSTALLATION; + default -> null; + }; + } + + /** The portal cannot tell an unfinished sign-up from an abandoned one, so the deadline is enforced here. */ + private void onAwaitingSignup(String token, long now) { + if (parkIfSignUpAbandoned(token, flowStateStore.get(), now)) { + return; + } + applyIfCurrent(token, state -> { + state.setState(CommunityGrantState.AWAITING_SIGNUP); + state.setLastPolledAt(now); + return state; + }); + } + + /** @return whether the flow was parked. */ + private boolean parkIfSignUpAbandoned(String token, CommunityGrantFlowState current, long now) { + Long startedAt = current.getStartedAt(); + if (current.getState() != CommunityGrantState.AWAITING_SIGNUP + || startedAt == null || now - startedAt <= signUpDeadlineMs) { + return false; + } + park(token, now, CommunityGrantParkReason.SIGNUP_ABANDONED); + return true; + } + + private void onVerificationRequired(String token, CommunityGrantPortalStatus status, long now) { + CommunityGrantFlowState updated = applyIfCurrent(token, state -> { + // The portal asks for verification until a by-hand report lands; that state must not be overwritten. + if (state.getState() != CommunityGrantState.VALIDATING + && state.getState() != CommunityGrantState.REPORT_HANDED_OVER) { + state.setState(CommunityGrantState.COLLECTING); + } + state.setLastPolledAt(now); + return state; + }); + if (updated == null) { + return; + } + if (updated.getMode() == CommunityGrantMode.OFFLINE) { + return; + } + if (updated.getState() == CommunityGrantState.VALIDATING) { + // A by-hand report is already in flight. + return; + } + Optional checkerInput = CommunityGrantCheckerInput.from(status.checkerInput()); + if (checkerInput.isEmpty()) { + log.warn("The portal asked for verification without the input needed to produce it"); + return; + } + String uploadedStatus; + try { + uploadedStatus = reportRunner.runAndUpload(token, checkerInput.get()); + } catch (Exception e) { + int failures = verificationFailures.incrementAndGet(); + if (failures < MAX_VERIFICATION_FAILURES) { + log.warn("Failed to produce and upload the instance check", e); + } else if (updated.getState() == CommunityGrantState.REPORT_HANDED_OVER) { + // Parking would retire the token the handed-over report is bound to. + log.warn("The instance check keeps failing ({} attempts), but the report has been handed over " + + "by hand, so the flow is left waiting on the portal", failures, e); + } else { + log.warn("Parking the community grant flow after {} failed instance checks", failures, e); + park(token, now, CommunityGrantParkReason.CHECK_FAILED); + } + return; + } + verificationFailures.set(0); + if (uploadedStatus == null) { + return; + } + CommunityGrantState terminalState = terminalStateFor(uploadedStatus); + if (terminalState != null) { + retire(token, terminalState, now, null); + } else if ("UNDER_REVIEW".equals(uploadedStatus)) { + onUnderReview(token, now); + } else { + log.debug("Ignoring an unrecognized portal status after the upload"); + } + } + + /** A wait, not an ending: the token is kept for the poll that brings the reviewer's decision. */ + private void onUnderReview(String token, long now) { + applyIfCurrent(token, state -> { + state.setState(CommunityGrantState.UNDER_REVIEW); + state.setLastPolledAt(now); + return state; + }); + } + + /** @return the state as written, or {@code null} if the claim token had been replaced. */ + private CommunityGrantFlowState applyIfCurrent(String token, UnaryOperator updater) { + AtomicBoolean applied = new AtomicBoolean(); + CommunityGrantFlowState updated = flowStateStore.update(state -> { + // Checked under the store's lock, so a start() on this node cannot replace the token mid-write. + applied.set(token.equals(tbClusterStore.getLicenseClaimToken().orElse(null))); + return applied.get() ? updater.apply(state) : state; + }); + if (!applied.get()) { + log.debug("Ignoring a portal answer for a claim token that has since been replaced"); + return null; + } + return updated; + } + + private void park(String token, long now, CommunityGrantParkReason reason) { + retire(token, CommunityGrantState.RESUME, now, reason); + } + + /** The state is written before the token is cleared, so a failed write leaves the next poll to retry. */ + private void retire(String token, CommunityGrantState newState, long now, CommunityGrantParkReason reason) { + AtomicBoolean applied = new AtomicBoolean(); + flowStateStore.update(state -> { + // Checked under the store's lock, so a start() on this node cannot replace the token mid-write. + applied.set(token.equals(tbClusterStore.getLicenseClaimToken().orElse(null))); + if (!applied.get()) { + return state; + } + // The portal still serves a finished grant's page on this link. + String registrationLink = newState == CommunityGrantState.REGISTERED ? state.getSignUpUrl() : null; + state.setState(newState); + state.setParkReason(reason); + state.clearClaim(); + state.setSignUpUrl(registrationLink); + state.setLastPolledAt(now); + return state; + }); + if (!applied.get()) { + log.debug("Ignoring a portal answer for a claim token that has since been replaced"); + return; + } + tbClusterStore.clearLicenseClaimToken(token); + disarm(); + } + +} diff --git a/application/src/main/java/org/thingsboard/server/service/community_grant/CommunityGrantPortalClient.java b/application/src/main/java/org/thingsboard/server/service/community_grant/CommunityGrantPortalClient.java new file mode 100644 index 0000000000..d176a29f58 --- /dev/null +++ b/application/src/main/java/org/thingsboard/server/service/community_grant/CommunityGrantPortalClient.java @@ -0,0 +1,269 @@ +// SPDX-FileCopyrightText: Copyright The Thingsboard Authors +// SPDX-License-Identifier: Apache-2.0 +package org.thingsboard.server.service.community_grant; + +import jakarta.annotation.PostConstruct; +import lombok.extern.slf4j.Slf4j; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.boot.web.client.RestTemplateBuilder; +import org.springframework.http.HttpEntity; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpMethod; +import org.springframework.http.client.ClientHttpRequest; +import org.springframework.http.client.ClientHttpResponse; +import org.springframework.stereotype.Component; +import org.springframework.web.client.DefaultResponseErrorHandler; +import org.springframework.web.client.HttpStatusCodeException; +import org.springframework.web.client.ResourceAccessException; +import org.springframework.web.client.RestClientException; +import org.springframework.web.client.RestTemplate; +import org.springframework.web.util.UriComponentsBuilder; +import org.thingsboard.server.common.data.community_grant.CommunityGrantMode; +import org.thingsboard.server.queue.util.TbCoreComponent; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.net.URI; +import java.net.URISyntaxException; +import java.time.Duration; +import java.util.UUID; + +/** + * The only outbound path to the license portal. Calls that carry grant state are authenticated by the claim + * token, never by the cluster id, which is not a secret. + */ +@Component +@TbCoreComponent +@Slf4j +public class CommunityGrantPortalClient { + + private static final String BASE_PATH = "/api/noauth/communityGrant"; + private static final String CLUSTER_STATUS_PATH = BASE_PATH + "/clusterStatus?clusterId={clusterId}"; + + /** A header rather than a query parameter, which would be written to access and proxy logs. */ + private static final String CLAIM_TOKEN_HEADER = "X-TB-Claim-Token"; + + private static final UUID REACHABILITY_PROBE_CLUSTER_ID = new UUID(0L, 0L); + + private static final int REACHABILITY_PROBE_MAX_BODY_BYTES = 4096; + + private static final int ERROR_BODY_MAX_BYTES = 4096; + + @Value("${community-grant.enabled:true}") + private boolean enabled; + + @Value("${community-grant.base-url:https://license.thingsboard.io}") + private String baseUrl; + + @Value("${community-grant.connect-timeout-sec:5}") + private int connectTimeoutSec; + + @Value("${community-grant.read-timeout-sec:10}") + private int readTimeoutSec; + + @Value("${community-grant.max-checker-size-bytes:33554432}") + private long maxCheckerSizeBytes; + + private RestTemplate restTemplate; + + @PostConstruct + public void initRestClient() { + // Validation failure stops the node, so a disabled feature does not validate its URL. + if (enabled) { + baseUrl = normalizeBaseUrl(baseUrl); + } + restTemplate = new RestTemplateBuilder() + .connectTimeout(Duration.ofSeconds(connectTimeoutSec)) + .readTimeout(Duration.ofSeconds(readTimeoutSec)) + .errorHandler(new BoundedBodyErrorHandler()) + .build(); + } + + /** Spring's default handler buffers an error body in full. */ + private static class BoundedBodyErrorHandler extends DefaultResponseErrorHandler { + + @Override + protected byte[] getResponseBody(ClientHttpResponse response) { + try (InputStream in = response.getBody()) { + ByteArrayOutputStream out = new ByteArrayOutputStream(); + byte[] buffer = new byte[1024]; + int read; + while (out.size() < ERROR_BODY_MAX_BYTES && (read = in.read(buffer)) != -1) { + out.write(buffer, 0, read); + } + return out.toByteArray(); + } catch (IOException e) { + return new byte[0]; + } + } + } + + /** A trailing slash would 404 every route, and the reachability probe counts a 404 as reachable. */ + private static String normalizeBaseUrl(String configured) { + String normalized = configured == null ? "" : configured.trim().replaceAll("/+$", ""); + URI uri; + try { + uri = new URI(normalized); + } catch (URISyntaxException e) { + throw new IllegalStateException("community-grant.base-url is not a valid URL: " + configured, e); + } + if (uri.getHost() == null || !("http".equals(uri.getScheme()) || "https".equals(uri.getScheme()))) { + throw new IllegalStateException("community-grant.base-url must be an absolute http(s) URL: " + configured); + } + return normalized; + } + + public String getPortalUrl() { + return baseUrl; + } + + /** + * The platform rides along on every link, not only an offline one: the portal needs it to build a checker + * bundle if the enrollment later moves to the by-hand route. + * + * @throws IllegalArgumentException if {@code community-grant.base-url} cannot be parsed + */ + public String buildSignUpUrl(UUID clusterId, String token, CommunityGrantMode mode) { + UriComponentsBuilder builder = UriComponentsBuilder.fromUriString(baseUrl) + .path("/communityGrant") + .queryParam("clusterId", clusterId) + .queryParam("claimToken", token); + if (mode == CommunityGrantMode.OFFLINE) { + builder.queryParam("offline", true); + } + appendPlatform(builder); + return builder.build().toUriString(); + } + + /** Omitted on an architecture with no checker build rather than failing the enrollment. */ + private static void appendPlatform(UriComponentsBuilder builder) { + CommunityGrantPlatform platform; + try { + platform = CommunityGrantPlatform.current(); + } catch (RuntimeException e) { + log.debug("Leaving the platform out of the community grant sign-up link", e); + return; + } + builder.queryParam("os", platform.os()).queryParam("arch", platform.arch()); + } + + /** Only a transport failure counts as unreachable; any HTTP status means reachable. */ + public boolean isPortalReachable() { + String url = baseUrl + CLUSTER_STATUS_PATH; + try { + restTemplate.execute(url, HttpMethod.GET, null, response -> { + try (InputStream in = response.getBody()) { + byte[] buffer = new byte[1024]; + int total = 0; + int read; + while (total < REACHABILITY_PROBE_MAX_BODY_BYTES && (read = in.read(buffer)) != -1) { + total += read; + } + } + return null; + }, REACHABILITY_PROBE_CLUSTER_ID); + return true; + } catch (HttpStatusCodeException e) { + return true; + } catch (RestClientException e) { + log.info("The license portal is not reachable from this server: {}", e.getMessage()); + return false; + } + } + + public boolean isAlreadyRegistered(UUID clusterId) { + String url = baseUrl + CLUSTER_STATUS_PATH; + CommunityGrantClusterStatus response = restTemplate.getForObject(url, CommunityGrantClusterStatus.class, clusterId); + return response != null && response.alreadyRegistered(); + } + + /** The portal always answers a bare 200, so a registration is never confirmed to the caller. */ + public void requestAccess(UUID clusterId) { + String url = baseUrl + BASE_PATH + "/requestAccess?clusterId={clusterId}"; + restTemplate.postForObject(url, null, Void.class, clusterId); + } + + /** + * The cluster id goes with every poll: the token resolves to an account whose grant may belong to a + * different installation. + * + * @return the portal's parsed answer, or {@code null} if the portal answered with an empty body + */ + public CommunityGrantPortalStatus getStatus(String token, UUID clusterId) { + String url = baseUrl + BASE_PATH + "/status?clusterId={clusterId}"; + HttpHeaders headers = new HttpHeaders(); + headers.set(CLAIM_TOKEN_HEADER, token); + return restTemplate.exchange(url, HttpMethod.GET, new HttpEntity<>(headers), + CommunityGrantPortalStatus.class, clusterId).getBody(); + } + + /** + * @return the portal's status after it accepted the report, or {@code null} if the portal answered with + * an empty body. + */ + public String uploadReport(String token, String report) { + String url = baseUrl + BASE_PATH + "/report"; + CommunityGrantReportResponse response = restTemplate.postForObject(url, + new CommunityGrantReportRequest(token, report), CommunityGrantReportResponse.class); + return response == null ? null : response.status(); + } + + /** + * @throws CommunityGrantCheckerTooLargeException if the checker exceeds {@code maxCheckerSizeBytes} + * @throws ResourceAccessException if reading the stream fails + */ + public byte[] downloadChecker(String token, String os, String arch) { + return download(BASE_PATH + "/checker?os={os}&arch={arch}", "instance checker", token, os, arch); + } + + /** + * @throws HttpStatusCodeException if the portal has no signature staged for this platform + */ + public byte[] downloadCheckerSignature(String token, String os, String arch) { + return download(BASE_PATH + "/checkerSignature?os={os}&arch={arch}", + "instance checker's release signature", token, os, arch); + } + + private byte[] download(String path, String what, String token, String os, String arch) { + String url = baseUrl + path; + final long limit = maxCheckerSizeBytes; + return restTemplate.execute(url, HttpMethod.GET, request -> setClaimToken(request, token), response -> { + long contentLength = response.getHeaders().getContentLength(); + if (contentLength > limit) { + throw new CommunityGrantCheckerTooLargeException("The " + what + " size " + contentLength + + " bytes exceeds the configured limit of " + limit + " bytes"); + } + int initialCapacity = contentLength > 0 && contentLength <= Integer.MAX_VALUE + ? (int) contentLength : 8192; + ByteArrayOutputStream out = new ByteArrayOutputStream(initialCapacity); + boolean complete = false; + try (InputStream in = response.getBody()) { + byte[] buffer = new byte[8192]; + long total = 0; + int read; + while ((read = in.read(buffer)) != -1) { + total += read; + if (total > limit) { + throw new CommunityGrantCheckerTooLargeException("The " + what + + " stream exceeded the configured limit of " + limit + " bytes"); + } + out.write(buffer, 0, read); + } + complete = true; + } catch (IOException e) { + if (!complete) { + throw new ResourceAccessException("Failed to read the " + what + " (GET " + url + ")", e); + } + // Only close() failed after a complete read; the download is kept. + log.debug("Failed to close the {} response stream after a complete read", what, e); + } + return out.toByteArray(); + }, os, arch); + } + + private static void setClaimToken(ClientHttpRequest request, String token) { + request.getHeaders().set(CLAIM_TOKEN_HEADER, token); + } + +} diff --git a/application/src/main/java/org/thingsboard/server/service/community_grant/CommunityGrantPortalStatus.java b/application/src/main/java/org/thingsboard/server/service/community_grant/CommunityGrantPortalStatus.java new file mode 100644 index 0000000000..755ee5a322 --- /dev/null +++ b/application/src/main/java/org/thingsboard/server/service/community_grant/CommunityGrantPortalStatus.java @@ -0,0 +1,16 @@ +// SPDX-FileCopyrightText: Copyright The Thingsboard Authors +// SPDX-License-Identifier: Apache-2.0 +package org.thingsboard.server.service.community_grant; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.databind.JsonNode; + +/** + * The portal's answer to a poll. {@code status} is a raw string so an unknown value leaves the flow where it + * is rather than failing deserialization. + */ +@JsonIgnoreProperties(ignoreUnknown = true) +public record CommunityGrantPortalStatus(String status, + JsonNode checkerInput, + Integer retryAfterSec) { +} diff --git a/application/src/main/java/org/thingsboard/server/service/community_grant/CommunityGrantReleaseSignatureVerifier.java b/application/src/main/java/org/thingsboard/server/service/community_grant/CommunityGrantReleaseSignatureVerifier.java new file mode 100644 index 0000000000..309efb6565 --- /dev/null +++ b/application/src/main/java/org/thingsboard/server/service/community_grant/CommunityGrantReleaseSignatureVerifier.java @@ -0,0 +1,212 @@ +// SPDX-FileCopyrightText: Copyright The Thingsboard Authors +// SPDX-License-Identifier: Apache-2.0 +package org.thingsboard.server.service.community_grant; + +import jakarta.annotation.PostConstruct; +import lombok.extern.slf4j.Slf4j; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.stereotype.Component; +import org.thingsboard.server.queue.util.TbCoreComponent; + +import java.security.GeneralSecurityException; +import java.security.KeyFactory; +import java.security.PublicKey; +import java.security.Signature; +import java.security.spec.X509EncodedKeySpec; +import java.util.Arrays; +import java.util.Base64; +import java.util.LinkedHashMap; +import java.util.Map; + +/** + * Verifies the instance checker's detached release signature against the configured release-signing keys. + * Fails closed: with no trusted key, every checker is refused. + */ +@Component +@TbCoreComponent +@Slf4j +public class CommunityGrantReleaseSignatureVerifier { + + static final String PUBLIC_KEYS_PROPERTY = "community-grant.checker-release-public-keys"; + + /** The whole signature file: {@code MAGIC(8) ‖ VERSION(1) ‖ KEYID(1) ‖ SIG(64)}, and nothing after it. */ + static final int SIGNATURE_FILE_LENGTH = 74; + + private static final byte[] MAGIC = {'T', 'B', 'I', 'C', 'S', 'I', 'G', '1'}; + private static final int VERSION_OFFSET = 8; + private static final byte SUPPORTED_VERSION = 0x01; + private static final int KEY_ID_OFFSET = 9; + private static final int SIGNATURE_OFFSET = 10; + + private static final int ED25519_PUBLIC_KEY_LENGTH = 32; + + /** RFC 8410 SubjectPublicKeyInfo prefix for a raw 32-byte Ed25519 key; KeyFactory takes no raw spec. */ + private static final byte[] ED25519_SPKI_PREFIX = { + 0x30, 0x2a, 0x30, 0x05, 0x06, 0x03, 0x2b, 0x65, 0x70, 0x03, 0x21, 0x00 + }; + + @Value("${" + PUBLIC_KEYS_PROPERTY + ":}") + private String checkerReleasePublicKeys; + + /** Empty when nothing is configured and when the configured value could not be parsed. */ + private Map trustStore = Map.of(); + + private String trustStoreError; + + @PostConstruct + void init() { + try { + trustStore = parsePublicKeys(checkerReleasePublicKeys); + trustStoreError = null; + } catch (IllegalArgumentException e) { + trustStore = Map.of(); + trustStoreError = e.getMessage(); + log.error("{} could not be parsed, so no release-signing key is trusted and every " + + "instance checker will be refused: {}", PUBLIC_KEYS_PROPERTY, e.getMessage()); + } + } + + public boolean hasTrustedKeys() { + return !trustStore.isEmpty(); + } + + /** + * Throws {@link IllegalArgumentException} unless {@code signatureData} is a valid release signature over + * exactly {@code checkerData} under a trusted key. Messages are safe to show the uploader and to audit. + */ + public void verify(byte[] checkerData, byte[] signatureData) { + if (checkerData == null || checkerData.length == 0) { + throw new IllegalArgumentException("The uploaded instance checker is empty, so there is nothing " + + "to verify. It was not run."); + } + if (signatureData == null || signatureData.length == 0) { + throw new IllegalArgumentException("The enrollment bundle carries no release signature for the " + + "instance checker, so it could not be verified and was not run. Download the enrollment " + + "bundle for this platform again from the License Portal."); + } + if (signatureData.length != SIGNATURE_FILE_LENGTH) { + throw new IllegalArgumentException("The release signature is " + signatureData.length + + " bytes; a ThingsBoard release signature is exactly " + SIGNATURE_FILE_LENGTH + + " bytes. The uploaded instance checker was not run. Download the enrollment bundle again " + + "from the License Portal and upload it unmodified."); + } + if (!Arrays.equals(signatureData, 0, MAGIC.length, MAGIC, 0, MAGIC.length)) { + throw new IllegalArgumentException("The release signature is not a ThingsBoard release " + + "signature. The uploaded instance checker was not run. Download the enrollment bundle again " + + "from the License Portal and upload it unmodified."); + } + byte version = signatureData[VERSION_OFFSET]; + if (version != SUPPORTED_VERSION) { + throw new IllegalArgumentException("The release signature declares signature format " + + "version " + (version & 0xFF) + "; this deployment only understands version " + + SUPPORTED_VERSION + ". The uploaded instance checker was not run. Upgrade ThingsBoard, or " + + "use a checker release this version can verify."); + } + int keyId = signatureData[KEY_ID_OFFSET] & 0xFF; + if (keyId == 0) { + throw new IllegalArgumentException("The release signature names key id 0, which is " + + "reserved and never valid. The uploaded instance checker was not run."); + } + if (trustStore.isEmpty()) { + if (trustStoreError != null) { + throw new IllegalArgumentException("The configured " + PUBLIC_KEYS_PROPERTY + " could not be " + + "parsed (" + trustStoreError + "), so no uploaded instance checker can be verified. " + + "It was not run. Fix the configured value."); + } + throw new IllegalArgumentException("This deployment is not configured to verify an uploaded " + + "instance checker, so it refuses to run one. Set " + PUBLIC_KEYS_PROPERTY + " to the " + + "release-signing public key ThingsBoard publishes, as a comma-separated list of " + + "keyId:base64PublicKey entries."); + } + PublicKey publicKey = trustStore.get(keyId); + if (publicKey == null) { + throw new IllegalArgumentException("The uploaded instance checker is signed under release-signing " + + "key id " + keyId + ", which this deployment does not trust. It was not run. Add that " + + "key id and its public key to " + PUBLIC_KEYS_PROPERTY + " if ThingsBoard published " + + "this release under it."); + } + byte[] signature = Arrays.copyOfRange(signatureData, SIGNATURE_OFFSET, SIGNATURE_FILE_LENGTH); + boolean verified; + try { + Signature ed25519 = Signature.getInstance("Ed25519"); + ed25519.initVerify(publicKey); + ed25519.update(checkerData); + verified = ed25519.verify(signature); + } catch (GeneralSecurityException e) { + // The JDK throws, rather than returning false, for some invalid encodings. + log.debug("An uploaded instance checker's release signature could not be evaluated", e); + verified = false; + } + if (!verified) { + throw new IllegalArgumentException("The uploaded instance checker does not match its release " + + "signature, so it was not run. Download the enrollment bundle again from the License Portal " + + "and upload it unmodified."); + } + } + + /** + * Parses {@code keyId:base64PublicKey[,keyId:base64PublicKey...]}. Every malformed entry throws rather + * than being skipped. + */ + static Map parsePublicKeys(String configured) { + Map keys = new LinkedHashMap<>(); + if (configured == null || configured.isBlank()) { + return Map.copyOf(keys); + } + for (String entry : configured.split(",", -1)) { + String trimmed = entry.trim(); + if (trimmed.isEmpty()) { + throw new IllegalArgumentException("it has an empty entry; every entry must be " + + "keyId:base64PublicKey"); + } + int separator = trimmed.indexOf(':'); + if (separator < 0) { + throw new IllegalArgumentException("an entry is not in the keyId:base64PublicKey form"); + } + int keyId; + try { + keyId = Integer.parseInt(trimmed.substring(0, separator).trim()); + } catch (NumberFormatException e) { + throw new IllegalArgumentException("an entry's key id is not a number"); + } + if (keyId < 1 || keyId > 255) { + throw new IllegalArgumentException("an entry's key id is " + keyId + "; it must be 1-255 " + + "(0 is reserved and never valid)"); + } + byte[] raw; + try { + raw = Base64.getDecoder().decode(trimmed.substring(separator + 1).trim()); + } catch (IllegalArgumentException e) { + throw new IllegalArgumentException("the public key for key id " + keyId + + " is not valid standard base64"); + } + if (raw.length != ED25519_PUBLIC_KEY_LENGTH) { + throw new IllegalArgumentException("the public key for key id " + keyId + " decodes to " + + raw.length + " bytes; a raw Ed25519 public key is " + ED25519_PUBLIC_KEY_LENGTH + + " bytes (it must not be X.509 SubjectPublicKeyInfo-wrapped)"); + } + if (keys.containsKey(keyId)) { + throw new IllegalArgumentException("key id " + keyId + " is configured more than once"); + } + keys.put(keyId, ed25519PublicKey(keyId, raw)); + } + return Map.copyOf(keys); + } + + /** Probes initVerify here: KeyFactory accepts some off-curve values and only initVerify rejects them. */ + private static PublicKey ed25519PublicKey(int keyId, byte[] raw) { + byte[] encoded = new byte[ED25519_SPKI_PREFIX.length + raw.length]; + System.arraycopy(ED25519_SPKI_PREFIX, 0, encoded, 0, ED25519_SPKI_PREFIX.length); + System.arraycopy(raw, 0, encoded, ED25519_SPKI_PREFIX.length, raw.length); + try { + PublicKey publicKey = KeyFactory.getInstance("Ed25519") + .generatePublic(new X509EncodedKeySpec(encoded)); + Signature.getInstance("Ed25519").initVerify(publicKey); + return publicKey; + } catch (GeneralSecurityException e) { + throw new IllegalArgumentException("the public key for key id " + keyId + + " is not a usable Ed25519 public key"); + } + } + +} diff --git a/application/src/main/java/org/thingsboard/server/service/community_grant/CommunityGrantReportRequest.java b/application/src/main/java/org/thingsboard/server/service/community_grant/CommunityGrantReportRequest.java new file mode 100644 index 0000000000..1c825a6d59 --- /dev/null +++ b/application/src/main/java/org/thingsboard/server/service/community_grant/CommunityGrantReportRequest.java @@ -0,0 +1,6 @@ +// SPDX-FileCopyrightText: Copyright The Thingsboard Authors +// SPDX-License-Identifier: Apache-2.0 +package org.thingsboard.server.service.community_grant; + +public record CommunityGrantReportRequest(String token, String report) { +} diff --git a/application/src/main/java/org/thingsboard/server/service/community_grant/CommunityGrantReportResponse.java b/application/src/main/java/org/thingsboard/server/service/community_grant/CommunityGrantReportResponse.java new file mode 100644 index 0000000000..221528aa31 --- /dev/null +++ b/application/src/main/java/org/thingsboard/server/service/community_grant/CommunityGrantReportResponse.java @@ -0,0 +1,9 @@ +// SPDX-FileCopyrightText: Copyright The Thingsboard Authors +// SPDX-License-Identifier: Apache-2.0 +package org.thingsboard.server.service.community_grant; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; + +@JsonIgnoreProperties(ignoreUnknown = true) +public record CommunityGrantReportResponse(String status) { +} diff --git a/application/src/main/java/org/thingsboard/server/service/community_grant/CommunityGrantReportRunner.java b/application/src/main/java/org/thingsboard/server/service/community_grant/CommunityGrantReportRunner.java new file mode 100644 index 0000000000..a5a3c23ec8 --- /dev/null +++ b/application/src/main/java/org/thingsboard/server/service/community_grant/CommunityGrantReportRunner.java @@ -0,0 +1,383 @@ +// SPDX-FileCopyrightText: Copyright The Thingsboard Authors +// SPDX-License-Identifier: Apache-2.0 +package org.thingsboard.server.service.community_grant; + +import lombok.Getter; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.apache.commons.io.FileUtils; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.boot.info.BuildProperties; +import org.springframework.stereotype.Component; +import org.springframework.web.client.HttpStatusCodeException; +import org.thingsboard.server.queue.util.TbCoreComponent; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.UncheckedIOException; +import java.nio.charset.StandardCharsets; +import java.nio.file.FileSystems; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.attribute.PosixFilePermissions; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.ArrayList; +import java.util.HexFormat; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicBoolean; + +/** + * Fetches or accepts the instance checker, verifies its release signature and runs it against this instance's + * own database. + */ +@Component +@TbCoreComponent +@RequiredArgsConstructor +@Slf4j +public class CommunityGrantReportRunner { + + static final String REPORT_HEADER = "-----BEGIN TB INSTANCE CHECK-----"; + static final String REPORT_FOOTER = "-----END TB INSTANCE CHECK-----"; + + private static final int TERMINATION_GRACE_SEC = 5; + + private static final int MAX_STDERR_CAPTURE_BYTES = 8192; + + @Value("${spring.datasource.url}") + private String dbUrl; + + @Value("${spring.datasource.username}") + private String dbUserName; + + @Value("${spring.datasource.password}") + private String dbPassword; + + @Getter + @Value("${community-grant.checker-timeout-sec:600}") + private int checkerTimeoutSec; + + @Value("${community-grant.max-report-size-bytes:1048576}") + private int maxReportSizeBytes; + + @Value("${community-grant.max-checker-size-bytes:33554432}") + private long maxCheckerSizeBytes; + + @Autowired(required = false) + private BuildProperties buildProperties; + + private final CommunityGrantPortalClient portalClient; + private final CommunityGrantReleaseSignatureVerifier releaseSignatureVerifier; + + /** + * @return the portal's status after it accepted the report, or {@code null} if the portal answered with + * an empty body. + */ + public String runAndUpload(String token, CommunityGrantCheckerInput checkerInput) { + Path checker; + try { + checker = fetchChecker(token); + } catch (IOException e) { + throw new UncheckedIOException("Failed to obtain the instance checker", e); + } + return portalClient.uploadReport(token, runCheckerAndCleanUp(checker, checkerInput)); + } + + /** + * The checks {@link #runUploadedChecker} runs before anything is executed, callable on their own so a + * refusal can answer the upload request while the run itself happens later. + * + * @throws IllegalArgumentException on every refusal + */ + public void verifyUploadedChecker(byte[] checkerData, byte[] signatureData, String fileName) { + if (checkerData == null || checkerData.length == 0) { + throw new IllegalArgumentException("The uploaded file is empty"); + } + if (checkerData.length > maxCheckerSizeBytes) { + throw new IllegalArgumentException("The uploaded file is larger than the configured limit of " + + maxCheckerSizeBytes + " bytes"); + } + CommunityGrantPlatform platform = CommunityGrantPlatform.current(); + if (platform.namesAnotherPlatform(fileName)) { + throw new IllegalArgumentException("The uploaded file does not match this server's platform (" + + platform.os() + "/" + platform.arch() + ")"); + } + verifyOfflineCheckerSignature(checkerData, signatureData); + } + + /** Repeats {@link #verifyUploadedChecker} so nothing unverified reaches disk however this is called. */ + public String runUploadedChecker(byte[] checkerData, byte[] signatureData, String fileName, + CommunityGrantCheckerInput checkerInput) { + verifyUploadedChecker(checkerData, signatureData, fileName); + CommunityGrantPlatform platform = CommunityGrantPlatform.current(); + log.info("Running an uploaded instance checker (uploaded file name {}, SHA-256 {})", + fileName, HexFormat.of().formatHex(sha256(checkerData))); + Path checker; + try { + checker = writeChecker(checkerData, platform.checkerFileName()); + } catch (IOException e) { + throw new UncheckedIOException("Failed to store the uploaded file", e); + } + return runCheckerAndCleanUp(checker, checkerInput); + } + + private String runCheckerAndCleanUp(Path checker, CommunityGrantCheckerInput checkerInput) { + try { + return runChecker(checker, checkerInput); + } finally { + deleteQuietly(checker); + } + } + + private void verifyOfflineCheckerSignature(byte[] checkerData, byte[] signatureData) { + try { + releaseSignatureVerifier.verify(checkerData, signatureData); + } catch (IllegalArgumentException e) { + log.warn("Refused to run an uploaded instance checker (uploaded file SHA-256 {}): {}", + HexFormat.of().formatHex(sha256(checkerData)), e.getMessage()); + throw e; + } + } + + private static byte[] sha256(byte[] data) { + try { + return MessageDigest.getInstance("SHA-256").digest(data); + } catch (NoSuchAlgorithmException e) { + throw new IllegalStateException("SHA-256 is not available", e); + } + } + + Path fetchChecker(String token) throws IOException { + if (!releaseSignatureVerifier.hasTrustedKeys()) { + throw new IllegalStateException("No trusted release-signing key is configured in " + + CommunityGrantReleaseSignatureVerifier.PUBLIC_KEYS_PROPERTY + + ", so the instance checker could not be verified and was not run"); + } + CommunityGrantPlatform platform = CommunityGrantPlatform.current(); + byte[] checkerData = portalClient.downloadChecker(token, platform.os(), platform.arch()); + verifyDownloadedCheckerSignature(token, platform, checkerData); + return writeChecker(checkerData, platform.checkerFileName()); + } + + private void verifyDownloadedCheckerSignature(String token, CommunityGrantPlatform platform, byte[] checkerData) { + byte[] signatureData; + try { + signatureData = portalClient.downloadCheckerSignature(token, platform.os(), platform.arch()); + } catch (HttpStatusCodeException e) { + throw new IllegalStateException("The portal served no release signature for the instance checker (" + + e.getStatusCode() + "), so it could not be verified and was not run", e); + } + try { + releaseSignatureVerifier.verify(checkerData, signatureData); + } catch (IllegalArgumentException e) { + // The verifier's messages name an uploaded checker. + throw new IllegalStateException("The instance checker downloaded from the portal does not match " + + "the release signature published for it, so it was not run", e); + } + } + + Path writeChecker(byte[] checkerData, String fileName) throws IOException { + boolean posix = FileSystems.getDefault().supportedFileAttributeViews().contains("posix"); + Path dir = posix + ? Files.createTempDirectory("tb-instance-check", + PosixFilePermissions.asFileAttribute(PosixFilePermissions.fromString("rwx------"))) + : Files.createTempDirectory("tb-instance-check"); + try { + Path checker = dir.resolve(fileName); + Files.write(checker, checkerData); + if (posix) { + Files.setPosixFilePermissions(checker, PosixFilePermissions.fromString("r-x------")); + } else if (!checker.toFile().setExecutable(true, true)) { + throw new IOException("Failed to make the instance checker executable"); + } + return checker; + } catch (IOException | RuntimeException e) { + deleteRecursivelyQuietly(dir); + throw e; + } + } + + /** + * Secrets travel in the environment, never on the command line, where {@code ps} shows them to every + * local user. + */ + String runChecker(Path checker, CommunityGrantCheckerInput checkerInput) { + ProcessBuilder processBuilder = new ProcessBuilder(buildCommand(checker)); + processBuilder.directory(checker.getParent().toFile()); + prepareCheckerEnvironment(processBuilder.environment(), + CommunityGrantLibpqDsn.from(dbUrl, dbUserName, dbPassword), checkerInput); + + Process process; + try { + process = processBuilder.start(); + } catch (IOException e) { + throw new UncheckedIOException("Failed to start the instance check", e); + } + ByteArrayOutputStream stdout = new ByteArrayOutputStream(); + ByteArrayOutputStream stderr = new ByteArrayOutputStream(); + AtomicBoolean overflow = new AtomicBoolean(false); + Thread stdoutDrain = drainCappedAsync(process.getInputStream(), stdout, overflow, process); + Thread stderrDrain = drainBoundedAsync(process.getErrorStream(), stderr); + try { + process.getOutputStream().close(); + } catch (IOException e) { + log.debug("Failed to close the instance check input stream", e); + } + boolean exited; + try { + exited = process.waitFor(checkerTimeoutSec, TimeUnit.SECONDS); + if (!exited) { + killTree(process); + awaitTermination(process); + } + stdoutDrain.join(TimeUnit.SECONDS.toMillis(TERMINATION_GRACE_SEC)); + stderrDrain.join(TimeUnit.SECONDS.toMillis(TERMINATION_GRACE_SEC)); + // Ahead of the timeout: the overflow branch kills the process too. + if (overflow.get()) { + String ending = "produced more output than the configured limit of " + maxReportSizeBytes + " bytes"; + logCheckerDiagnostics(stderr, ending); + throw new IllegalStateException("The instance check " + ending); + } + if (!exited) { + String ending = "did not finish within " + checkerTimeoutSec + " seconds"; + logCheckerDiagnostics(stderr, ending); + throw new IllegalStateException("The instance check " + ending); + } + if (stdoutDrain.isAlive()) { + // Reading a buffer the drain is still filling could upload a truncated report. stderr is not + // checked: a grandchild holding that pipe open would keep its drain alive indefinitely. + String ending = "output could not be read back in time"; + logCheckerDiagnostics(stderr, ending); + throw new IllegalStateException("The instance check " + ending); + } + } catch (InterruptedException e) { + killTree(process); + Thread.currentThread().interrupt(); + throw new IllegalStateException("Interrupted while running the instance check", e); + } + int exitCode = process.exitValue(); + if (exitCode != 0) { + String ending = "failed with exit code " + exitCode; + logCheckerDiagnostics(stderr, ending); + throw new IllegalStateException("The instance check " + ending); + } + return readReport(stdout); + } + + /** Logged, never put in the exception: it is untrusted child output and the message is shown to the user. */ + private void logCheckerDiagnostics(ByteArrayOutputStream stderr, String ending) { + String diagnostics = stderr.toString(StandardCharsets.UTF_8).trim(); + if (!diagnostics.isEmpty()) { + log.warn("The instance check {}. It wrote to standard error: {}", ending, diagnostics); + } + } + + private List buildCommand(Path checker) { + List command = new ArrayList<>(List.of(checker.toAbsolutePath().toString())); + if (buildProperties != null) { + command.add("--tb-version"); + command.add(buildProperties.getVersion()); + } + return command; + } + + private static String readReport(ByteArrayOutputStream stdout) { + String report = stdout.toString(StandardCharsets.UTF_8).trim(); + if (!report.startsWith(REPORT_HEADER) || !report.endsWith(REPORT_FOOTER)) { + throw new IllegalStateException("The instance check produced unexpected output"); + } + return report; + } + + /** Descendants are collected first: once the parent dies they are reparented and no longer found. */ + private static void killTree(Process process) { + List descendants = process.descendants().toList(); + process.destroyForcibly(); + descendants.forEach(ProcessHandle::destroyForcibly); + } + + /** + * Drops the inherited {@code PG*} variables, which could change how the DSN's connection is made. + * Case-insensitive because {@link ProcessBuilder#environment()} is on Windows. + */ + static void prepareCheckerEnvironment(Map environment, String dsn, + CommunityGrantCheckerInput checkerInput) { + environment.keySet().removeIf(name -> name.toUpperCase(Locale.ROOT).startsWith("PG")); + environment.put("TB_IC_DSN", dsn); + environment.put("TB_IC_INPUT", checkerInput.json()); + } + + /** On Windows, deleting the binary of a still-exiting process fails. */ + private void awaitTermination(Process process) { + try { + if (!process.waitFor(TERMINATION_GRACE_SEC, TimeUnit.SECONDS)) { + log.debug("The instance check process did not terminate within {} seconds of being killed", + TERMINATION_GRACE_SEC); + } + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } + } + + private Thread drainCappedAsync(InputStream in, ByteArrayOutputStream sink, AtomicBoolean overflow, + Process process) { + return startDaemon("tb-instance-check-stdout", () -> { + try (InputStream stream = in) { + byte[] buffer = new byte[8192]; + int read; + while ((read = stream.read(buffer)) != -1) { + if (sink.size() + read > maxReportSizeBytes) { + overflow.set(true); + killTree(process); + awaitTermination(process); + return; + } + sink.write(buffer, 0, read); + } + } catch (IOException e) { + log.debug("Failed to read the instance check output", e); + } + }); + } + + /** Keeps reading past the cap so a chatty checker cannot deadlock on the pipe. */ + private Thread drainBoundedAsync(InputStream in, ByteArrayOutputStream sink) { + return startDaemon("tb-instance-check-stderr", () -> { + try (InputStream stream = in) { + byte[] buffer = new byte[8192]; + int read; + while ((read = stream.read(buffer)) != -1) { + int room = MAX_STDERR_CAPTURE_BYTES - sink.size(); + if (room > 0) { + sink.write(buffer, 0, Math.min(read, room)); + } + } + } catch (IOException e) { + log.debug("Failed to read the instance check diagnostics", e); + } + }); + } + + private static Thread startDaemon(String name, Runnable body) { + Thread thread = new Thread(body, name); + thread.setDaemon(true); + thread.start(); + return thread; + } + + private void deleteQuietly(Path checker) { + deleteRecursivelyQuietly(checker.getParent()); + } + + private void deleteRecursivelyQuietly(Path dir) { + if (!FileUtils.deleteQuietly(dir.toFile())) { + log.debug("Failed to clean up the instance check directory {}", dir); + } + } + +} diff --git a/application/src/main/java/org/thingsboard/server/service/community_grant/CommunityGrantService.java b/application/src/main/java/org/thingsboard/server/service/community_grant/CommunityGrantService.java new file mode 100644 index 0000000000..5bb7a84d87 --- /dev/null +++ b/application/src/main/java/org/thingsboard/server/service/community_grant/CommunityGrantService.java @@ -0,0 +1,35 @@ +// SPDX-FileCopyrightText: Copyright The Thingsboard Authors +// SPDX-License-Identifier: Apache-2.0 +package org.thingsboard.server.service.community_grant; + +import org.thingsboard.server.common.data.community_grant.CommunityGrantStateInfo; +import org.thingsboard.server.common.data.exception.ThingsboardException; + +import java.util.function.Consumer; + +public interface CommunityGrantService { + + CommunityGrantStateInfo getStateInfo(); + + /** Starts or restarts the flow; a restart supersedes the previous claim token. */ + CommunityGrantStateInfo start() throws ThingsboardException; + + /** + * Starts an uploaded instance checker in the background on this node. The signature must verify before + * this returns; a refusal throws here, and the run's own outcome reaches {@link #getStateInfo()}. + * + * @param completionListener told how the run ended, on the run's own thread: {@code null} on success + */ + CommunityGrantStateInfo runOfflineChecker(byte[] checkerData, byte[] signatureData, String fileName, + CommunityGrantCheckerInput checkerInput, + Consumer completionListener) throws ThingsboardException; + + String getOfflineReport() throws ThingsboardException; + + /** Records that the operator handed the report to the portal by hand; the flow keeps waiting. */ + CommunityGrantStateInfo confirmOfflineHandoff() throws ThingsboardException; + + /** Asks the portal to notify this cluster's registered owner. Throttled by a cooldown. */ + void requestAccess() throws ThingsboardException; + +} diff --git a/application/src/main/java/org/thingsboard/server/service/community_grant/DefaultCommunityGrantService.java b/application/src/main/java/org/thingsboard/server/service/community_grant/DefaultCommunityGrantService.java new file mode 100644 index 0000000000..df4f44ac23 --- /dev/null +++ b/application/src/main/java/org/thingsboard/server/service/community_grant/DefaultCommunityGrantService.java @@ -0,0 +1,527 @@ +// SPDX-FileCopyrightText: Copyright The Thingsboard Authors +// SPDX-License-Identifier: Apache-2.0 +package org.thingsboard.server.service.community_grant; + +import jakarta.annotation.PreDestroy; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.stereotype.Service; +import org.thingsboard.common.util.ThingsBoardThreadFactory; +import org.thingsboard.server.common.data.community_grant.CommunityGrantFlowState; +import org.thingsboard.server.common.data.community_grant.CommunityGrantMode; +import org.thingsboard.server.common.data.community_grant.CommunityGrantOfflineRun; +import org.thingsboard.server.common.data.community_grant.CommunityGrantOfflineRunStatus; +import org.thingsboard.server.common.data.community_grant.CommunityGrantState; +import org.thingsboard.server.common.data.community_grant.CommunityGrantStateInfo; +import org.thingsboard.server.common.data.exception.ThingsboardErrorCode; +import org.thingsboard.server.common.data.exception.ThingsboardException; +import org.thingsboard.server.dao.subscription.TbClusterStore; +import org.thingsboard.server.queue.util.TbCoreComponent; + +import java.security.SecureRandom; +import java.util.Base64; +import java.util.UUID; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.RejectedExecutionException; +import java.util.concurrent.Semaphore; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.locks.ReentrantLock; +import java.util.function.Consumer; + +@Service +@TbCoreComponent +@RequiredArgsConstructor +@Slf4j +public class DefaultCommunityGrantService implements CommunityGrantService { + + static final int CLAIM_TOKEN_BYTES = 32; + + static final long REQUEST_ACCESS_COOLDOWN_MS = TimeUnit.MINUTES.toMillis(5); + + static final String NOT_AVAILABLE_MESSAGE = "This action is not available on this deployment."; + static final String NO_CLUSTER_ID_MESSAGE = + "This deployment is not fully installed yet. Restart the platform and try again."; + private static final String START_FAILED_MESSAGE = + "Failed to start. Please check that the database is reachable and try again."; + private static final String ALREADY_FINISHED_MESSAGE = "This deployment has already completed this process."; + static final String UNDER_REVIEW_MESSAGE = + "This deployment's registration is with a reviewer. There is nothing to send again while it is."; + static final String REPORT_HANDED_OVER_MESSAGE = + "This deployment's check result has already been handed over. Starting again would abandon it."; + static final String NOTHING_TO_HAND_OVER_MESSAGE = + "This deployment is not waiting for a check result to be handed over."; + static final String HANDOFF_FAILED_MESSAGE = + "Failed to record the hand-over. Please check that the database is reachable and try again."; + private static final String PORTAL_MISCONFIGURED_MESSAGE = + "This deployment's connection to the license portal is misconfigured. Contact your administrator."; + static final String NO_OFFLINE_REPORT_MESSAGE = "No result is available. Run the check first."; + static final String OFFLINE_RUN_IN_PROGRESS_MESSAGE = + "A check is already running on this deployment. Wait for it to finish and try again."; + static final String OFFLINE_STATE_NOT_PERSISTED_MESSAGE = + "The check completed, but this deployment could not record it. The result is still available for download."; + static final String OFFLINE_RUN_START_FAILED_MESSAGE = + "Failed to start the check. Please check that the database is reachable and try again."; + static final String OFFLINE_RUN_NOT_SCHEDULED_MESSAGE = + "Failed to start the check: this server is shutting down. Please try again."; + static final String OFFLINE_RUN_INTERRUPTED_MESSAGE = + "The check was interrupted before it finished. Please run it again."; + static final String OFFLINE_RESULT_NOT_RECORDED_MESSAGE = + "The check completed, but this deployment could not record its result. Please check that the database " + + "is reachable and run the check again."; + static final String OFFLINE_RUN_SUPERSEDED_MESSAGE = + "The check finished after a newer check or enrollment replaced it, so its result was discarded."; + private static final String RUN_FAILED_PREFIX = "Failed to run the check. "; + + /** Past the checker's own timeout: room for writing the binary and recording the result. */ + static final long OFFLINE_RUN_GRACE_MS = TimeUnit.MINUTES.toMillis(2); + static final String NOT_ALREADY_REGISTERED_MESSAGE = + "This action is only available once this deployment is confirmed as already registered under another account."; + static final String REQUEST_ACCESS_RATE_LIMITED_MESSAGE = + "Please wait a few minutes before requesting access again."; + static final String REQUEST_ACCESS_STORE_FAILED_MESSAGE = + "Failed to process the request. Please check that the database is reachable and try again."; + static final String REQUEST_ACCESS_FAILED_MESSAGE = + "Failed to reach the license portal. Please try again later."; + + @Value("${community-grant.enabled:true}") + private boolean enabled; + + private final TbClusterStore tbClusterStore; + private final CommunityGrantFlowStateStore flowStateStore; + private final CommunityGrantPortalClient portalClient; + private final CommunityGrantPoller poller; + private final CommunityGrantReportRunner reportRunner; + private final CommunityGrantOfflineReportStore offlineReportStore; + + private final SecureRandom secureRandom = new SecureRandom(); + private final ReentrantLock startLock = new ReentrantLock(); + + /** A permit, not a lock: the request thread takes it and the executor thread gives it back. */ + private final Semaphore offlineRunPermit = new Semaphore(1); + + private ExecutorService offlineRunExecutor = + Executors.newSingleThreadExecutor(ThingsBoardThreadFactory.forName("tb-community-grant-offline-run")); + + /** A failure to read the report drops it from the answer rather than failing the whole read. */ + @Override + public CommunityGrantStateInfo getStateInfo() { + CommunityGrantFlowState flowState = flowStateStore.get(); + String portalUrl = portalClient.getPortalUrl(); + CommunityGrantOfflineRun run = flowState.getOfflineRun(); + boolean runInProgress = isOfflineRunInProgress(run, System.currentTimeMillis(), offlineRunStaleAfterMs()); + String runError = offlineRunError(run, runInProgress); + String report = null; + if (CommunityGrantStateInfo.carriesOfflineReport(flowState)) { + try { + report = offlineReportStore.get().orElse(null); + } catch (Exception e) { + log.warn("Failed to read the stored community grant offline report", e); + } + } + return CommunityGrantStateInfo.of(flowState, portalUrl, report, runInProgress, runError); + } + + @Override + public CommunityGrantStateInfo start() throws ThingsboardException { + if (!enabled) { + throw new ThingsboardException(NOT_AVAILABLE_MESSAGE, ThingsboardErrorCode.ITEM_NOT_FOUND); + } + startLock.lock(); + try { + CommunityGrantFlowState currentState = flowStateStore.get(); + CommunityGrantState current = currentState.getState(); + if (current.isTerminal()) { + throw new ThingsboardException(ALREADY_FINISHED_MESSAGE, ThingsboardErrorCode.BAD_REQUEST_PARAMS); + } + if (current == CommunityGrantState.UNDER_REVIEW) { + // Re-minting would replace the token the reviewer's decision is delivered against. + throw new ThingsboardException(UNDER_REVIEW_MESSAGE, ThingsboardErrorCode.BAD_REQUEST_PARAMS); + } + if (current == CommunityGrantState.REPORT_HANDED_OVER) { + // Re-minting would abandon the submission and clear the report a failed paste comes back for. + throw new ThingsboardException(REPORT_HANDED_OVER_MESSAGE, ThingsboardErrorCode.BAD_REQUEST_PARAMS); + } + UUID clusterId = tbClusterStore.getClusterId() + .orElseThrow(() -> new ThingsboardException(NO_CLUSTER_ID_MESSAGE, ThingsboardErrorCode.GENERAL)); + + // Probed even when OFFLINE: the only way back to ONLINE. + CommunityGrantMode mode; + try { + mode = portalClient.isPortalReachable() ? CommunityGrantMode.ONLINE : CommunityGrantMode.OFFLINE; + } catch (IllegalArgumentException e) { + // Only a malformed base URL; unreachability is a plain false. + log.warn("Failed to reach the license portal: the configured base URL is not valid", e); + throw new ThingsboardException(PORTAL_MISCONFIGURED_MESSAGE, ThingsboardErrorCode.GENERAL); + } + + // Only from NOT_STARTED: on a flow this deployment began, its own pending registration answers + // true, and the terminal ALREADY_REGISTERED would dead-end the operator's own enrollment. + if (mode == CommunityGrantMode.ONLINE && current == CommunityGrantState.NOT_STARTED + && isAlreadyRegistered(clusterId)) { + return enrollAsAlreadyRegistered(); + } + + String token = mintToken(); + // Built before the token is stored, so a bad base URL leaves nothing to retire. + String signUpUrl; + try { + signUpUrl = portalClient.buildSignUpUrl(clusterId, token, mode); + } catch (Exception e) { + log.warn("Failed to build the sign-up URL: the configured base URL is not valid", e); + throw new ThingsboardException(PORTAL_MISCONFIGURED_MESSAGE, ThingsboardErrorCode.GENERAL); + } + try { + tbClusterStore.saveLicenseClaimToken(token); + } catch (Exception e) { + log.warn("Failed to store the community grant claim token", e); + throw new ThingsboardException(START_FAILED_MESSAGE, ThingsboardErrorCode.GENERAL); + } + + CommunityGrantFlowState updated; + try { + long now = System.currentTimeMillis(); + updated = flowStateStore.update(state -> { + state.setMode(mode); + state.setState(CommunityGrantState.AWAITING_SIGNUP); + state.setSignUpUrl(signUpUrl); + state.setStartedAt(now); + state.setLastPolledAt(null); + state.setParkReason(null); + state.setLastOfflineCheckAt(null); + state.setOfflineRun(null); + return state; + }); + } catch (Exception e) { + tbClusterStore.clearLicenseClaimToken(token); + log.warn("Failed to persist the community grant flow state after minting a token", e); + throw new ThingsboardException(START_FAILED_MESSAGE, ThingsboardErrorCode.GENERAL); + } + // After the write, so a failed start keeps the previous report. + offlineReportStore.clear(); + // After the write: the loop reads the persisted mode. + poller.arm(); + return CommunityGrantStateInfo.of(updated, portalClient.getPortalUrl()); + } finally { + startLock.unlock(); + } + } + + /** + * Refusals answer the upload request; the run itself goes to {@link #offlineRunExecutor} on this node. + * One run at a time: per node by {@link #offlineRunPermit}, cluster-wide by the run record on the flow + * state. Two nodes starting in the same instant can both pass; the run written last keeps its result. + */ + @Override + public CommunityGrantStateInfo runOfflineChecker(byte[] checkerData, byte[] signatureData, String fileName, + CommunityGrantCheckerInput checkerInput, + Consumer completionListener) + throws ThingsboardException { + if (!enabled) { + throw new ThingsboardException(NOT_AVAILABLE_MESSAGE, ThingsboardErrorCode.ITEM_NOT_FOUND); + } + if (!offlineRunPermit.tryAcquire()) { + throw new ThingsboardException(OFFLINE_RUN_IN_PROGRESS_MESSAGE, ThingsboardErrorCode.TOO_MANY_REQUESTS); + } + boolean handedToExecutor = false; + try { + try { + reportRunner.verifyUploadedChecker(checkerData, signatureData, fileName); + } catch (IllegalArgumentException e) { + throw new ThingsboardException(e.getMessage(), ThingsboardErrorCode.BAD_REQUEST_PARAMS); + } catch (Exception e) { + log.warn("Failed to verify the uploaded instance check", e); + throw new ThingsboardException(RUN_FAILED_PREFIX + e.getMessage(), ThingsboardErrorCode.GENERAL); + } + UUID runId = UUID.randomUUID(); + long startedAt = System.currentTimeMillis(); + CommunityGrantStateInfo answer = CommunityGrantStateInfo.of(recordOfflineRunStarted(runId, startedAt), + portalClient.getPortalUrl(), null, true, null); + try { + offlineRunExecutor.execute(() -> + completeOfflineRun(runId, checkerData, signatureData, fileName, checkerInput, + completionListener)); + } catch (RejectedExecutionException e) { + log.warn("Failed to schedule the uploaded instance check", e); + recordOfflineRunFailed(runId, OFFLINE_RUN_NOT_SCHEDULED_MESSAGE); + throw new ThingsboardException(OFFLINE_RUN_NOT_SCHEDULED_MESSAGE, ThingsboardErrorCode.GENERAL); + } + handedToExecutor = true; + return answer; + } finally { + if (!handedToExecutor) { + offlineRunPermit.release(); + } + } + } + + private CommunityGrantFlowState recordOfflineRunStarted(UUID runId, long startedAt) throws ThingsboardException { + long staleAfterMs = offlineRunStaleAfterMs(); + try { + return flowStateStore.update(state -> { + if (isOfflineRunInProgress(state.getOfflineRun(), startedAt, staleAfterMs)) { + throw new UpdateRefusal(OFFLINE_RUN_IN_PROGRESS_MESSAGE, ThingsboardErrorCode.TOO_MANY_REQUESTS); + } + state.setOfflineRun(CommunityGrantOfflineRun.running(runId, startedAt)); + return state; + }); + } catch (UpdateRefusal e) { + throw new ThingsboardException(e.getMessage(), e.errorCode); + } catch (Exception e) { + // No cause: the audit log stores the full stack trace. + log.warn("Failed to record the start of a community grant offline check", e); + throw new ThingsboardException(OFFLINE_RUN_START_FAILED_MESSAGE, ThingsboardErrorCode.GENERAL); + } + } + + private void completeOfflineRun(UUID runId, byte[] checkerData, byte[] signatureData, String fileName, + CommunityGrantCheckerInput checkerInput, Consumer completionListener) { + try { + ThingsboardException failure = null; + try { + runAndRecordOfflineCheck(runId, checkerData, signatureData, fileName, checkerInput); + } catch (ThingsboardException e) { + failure = e; + } catch (Exception e) { + log.warn("Failed to complete the uploaded instance check", e); + failure = new ThingsboardException(RUN_FAILED_PREFIX + e.getMessage(), ThingsboardErrorCode.GENERAL); + } + if (failure != null) { + recordOfflineRunFailed(runId, failure.getMessage()); + } + try { + completionListener.accept(failure); + } catch (Exception e) { + log.warn("Failed to report the end of a community grant offline check", e); + } + } finally { + offlineRunPermit.release(); + } + } + + private void runAndRecordOfflineCheck(UUID runId, byte[] checkerData, byte[] signatureData, String fileName, + CommunityGrantCheckerInput checkerInput) throws ThingsboardException { + String report; + try { + report = reportRunner.runUploadedChecker(checkerData, signatureData, fileName, checkerInput); + } catch (IllegalArgumentException e) { + throw new ThingsboardException(e.getMessage(), ThingsboardErrorCode.BAD_REQUEST_PARAMS); + } catch (Exception e) { + log.warn("Failed to run the uploaded instance check", e); + throw new ThingsboardException(RUN_FAILED_PREFIX + e.getMessage(), ThingsboardErrorCode.GENERAL); + } + CommunityGrantOfflineRun current; + try { + current = flowStateStore.get().getOfflineRun(); + } catch (Exception e) { + log.warn("Failed to read the community grant flow state after an offline check", e); + throw new ThingsboardException(OFFLINE_RESULT_NOT_RECORDED_MESSAGE, ThingsboardErrorCode.GENERAL); + } + if (current == null || !current.isOwnedBy(runId)) { + throw supersededOfflineRun(); + } + // Before and apart from the state write: OFFLINE_STATE_NOT_PERSISTED_MESSAGE promises the download. + offlineReportStore.put(report); + long lastOfflineCheckAt = System.currentTimeMillis(); + AtomicBoolean owned = new AtomicBoolean(); + try { + flowStateStore.update(state -> { + owned.set(state.getOfflineRun() != null && state.getOfflineRun().isOwnedBy(runId)); + if (!owned.get()) { + return state; + } + if (state.getMode() != CommunityGrantMode.ONLINE) { + state.setMode(CommunityGrantMode.OFFLINE); + } + if (!state.getState().isAwaitingOrPastDecision()) { + state.setState(CommunityGrantState.VALIDATING); + state.setParkReason(null); + } + state.setLastOfflineCheckAt(lastOfflineCheckAt); + state.setOfflineRun(null); + return state; + }); + } catch (Exception e) { + log.warn("Failed to persist the community grant flow state after a successful offline check", e); + throw new ThingsboardException(OFFLINE_STATE_NOT_PERSISTED_MESSAGE, ThingsboardErrorCode.GENERAL); + } + if (!owned.get()) { + // The report stays: deleting it could delete a newer run's. + throw supersededOfflineRun(); + } + } + + private static ThingsboardException supersededOfflineRun() { + return new ThingsboardException(OFFLINE_RUN_SUPERSEDED_MESSAGE, ThingsboardErrorCode.GENERAL); + } + + /** Best effort: a run left {@code RUNNING} is reported as interrupted once it goes stale. */ + private void recordOfflineRunFailed(UUID runId, String error) { + try { + flowStateStore.update(state -> { + CommunityGrantOfflineRun run = state.getOfflineRun(); + if (run != null && run.isOwnedBy(runId)) { + run.setStatus(CommunityGrantOfflineRunStatus.FAILED); + run.setError(error); + } + return state; + }); + } catch (Exception e) { + log.warn("Failed to record a failed community grant offline check", e); + } + } + + private long offlineRunStaleAfterMs() { + return TimeUnit.SECONDS.toMillis(reportRunner.getCheckerTimeoutSec()) + OFFLINE_RUN_GRACE_MS; + } + + private static boolean isOfflineRunInProgress(CommunityGrantOfflineRun run, long now, long staleAfterMs) { + return run != null && run.getStatus() == CommunityGrantOfflineRunStatus.RUNNING + && run.getStartedAt() != null && now - run.getStartedAt() <= staleAfterMs; + } + + private static String offlineRunError(CommunityGrantOfflineRun run, boolean inProgress) { + if (run == null || inProgress) { + return null; + } + return run.getStatus() == CommunityGrantOfflineRunStatus.FAILED + ? run.getError() + : OFFLINE_RUN_INTERRUPTED_MESSAGE; + } + + @PreDestroy + public void stop() { + offlineRunExecutor.shutdownNow(); + } + + @Override + public String getOfflineReport() throws ThingsboardException { + return offlineReportStore.get() + .orElseThrow(() -> new ThingsboardException(NO_OFFLINE_REPORT_MESSAGE, + ThingsboardErrorCode.ITEM_NOT_FOUND)); + } + + /** Under {@link #startLock}, so a concurrent start() is not relabelled as handed over. */ + @Override + public CommunityGrantStateInfo confirmOfflineHandoff() throws ThingsboardException { + if (!enabled) { + throw new ThingsboardException(NOT_AVAILABLE_MESSAGE, ThingsboardErrorCode.ITEM_NOT_FOUND); + } + startLock.lock(); + try { + CommunityGrantState current = flowStateStore.get().getState(); + if (current == CommunityGrantState.REPORT_HANDED_OVER) { + return getStateInfo(); + } + if (current != CommunityGrantState.VALIDATING) { + throw new ThingsboardException(NOTHING_TO_HAND_OVER_MESSAGE, ThingsboardErrorCode.BAD_REQUEST_PARAMS); + } + try { + flowStateStore.update(state -> { + // Re-tested: a poll may have retired the flow since the read above. + if (state.getState() == CommunityGrantState.VALIDATING) { + state.setState(CommunityGrantState.REPORT_HANDED_OVER); + } + return state; + }); + } catch (Exception e) { + log.warn("Failed to persist the community grant offline hand-off", e); + throw new ThingsboardException(HANDOFF_FAILED_MESSAGE, ThingsboardErrorCode.GENERAL); + } + return getStateInfo(); + } finally { + startLock.unlock(); + } + } + + @Override + public void requestAccess() throws ThingsboardException { + if (!enabled) { + throw new ThingsboardException(NOT_AVAILABLE_MESSAGE, ThingsboardErrorCode.ITEM_NOT_FOUND); + } + UUID clusterId; + long now = System.currentTimeMillis(); + try { + clusterId = tbClusterStore.getClusterId().orElse(null); + // The cooldown lives on the shared flow state; only the lock is per node. + flowStateStore.update(state -> { + // Not WRONG_INSTALLATION: there is no registration on this cluster id to notify. + if (state.getState() != CommunityGrantState.ALREADY_REGISTERED) { + throw new UpdateRefusal(NOT_ALREADY_REGISTERED_MESSAGE, ThingsboardErrorCode.BAD_REQUEST_PARAMS); + } + Long lastRequestAccessAt = state.getLastRequestAccessAt(); + if (lastRequestAccessAt != null && now - lastRequestAccessAt < REQUEST_ACCESS_COOLDOWN_MS) { + throw new UpdateRefusal(REQUEST_ACCESS_RATE_LIMITED_MESSAGE, ThingsboardErrorCode.TOO_MANY_REQUESTS); + } + if (clusterId == null) { + throw new UpdateRefusal(NO_CLUSTER_ID_MESSAGE, ThingsboardErrorCode.GENERAL); + } + // Recorded whatever the portal call below does. + state.setLastRequestAccessAt(now); + return state; + }); + } catch (UpdateRefusal e) { + throw new ThingsboardException(e.getMessage(), e.errorCode); + } catch (Exception e) { + log.warn("Failed to read or persist the community grant request-access state", e); + throw new ThingsboardException(REQUEST_ACCESS_STORE_FAILED_MESSAGE, ThingsboardErrorCode.GENERAL); + } + try { + portalClient.requestAccess(clusterId); + } catch (Exception e) { + log.warn("Failed to ask the license portal to notify the registered owner", e); + throw new ThingsboardException(REQUEST_ACCESS_FAILED_MESSAGE, ThingsboardErrorCode.GENERAL); + } + } + + /** Unchecked so it can leave an updater; translated back to {@link ThingsboardException} by the caller. */ + private static final class UpdateRefusal extends RuntimeException { + private final ThingsboardErrorCode errorCode; + + private UpdateRefusal(String message, ThingsboardErrorCode errorCode) { + super(message); + this.errorCode = errorCode; + } + } + + /** The token is retired before the terminal state is written, since nothing retires it afterwards. */ + private CommunityGrantStateInfo enrollAsAlreadyRegistered() throws ThingsboardException { + poller.disarm(); + tbClusterStore.forceClearLicenseClaimToken(); + try { + CommunityGrantFlowState updated = flowStateStore.update(state -> { + state.setMode(CommunityGrantMode.ONLINE); + state.setState(CommunityGrantState.ALREADY_REGISTERED); + state.clearClaim(); + state.setLastPolledAt(null); + state.setParkReason(null); + state.setOfflineRun(null); + return state; + }); + offlineReportStore.clear(); + return CommunityGrantStateInfo.of(updated, portalClient.getPortalUrl()); + } catch (Exception e) { + log.warn("Failed to persist the community grant flow state for an already-registered deployment", e); + throw new ThingsboardException(START_FAILED_MESSAGE, ThingsboardErrorCode.GENERAL); + } + } + + /** Best effort: a failure here reads as not registered, and the poll reaches the same answer later. */ + private boolean isAlreadyRegistered(UUID clusterId) { + try { + return portalClient.isAlreadyRegistered(clusterId); + } catch (Exception e) { + log.debug("Failed to read the cluster status from the portal", e); + return false; + } + } + + private String mintToken() { + byte[] tokenBytes = new byte[CLAIM_TOKEN_BYTES]; + secureRandom.nextBytes(tokenBytes); + return Base64.getUrlEncoder().withoutPadding().encodeToString(tokenBytes); + } + +} diff --git a/application/src/main/java/org/thingsboard/server/service/install/EntityDatabaseSchemaService.java b/application/src/main/java/org/thingsboard/server/service/install/EntityDatabaseSchemaService.java index 24bdadd2d5..b3a46fd60f 100644 --- a/application/src/main/java/org/thingsboard/server/service/install/EntityDatabaseSchemaService.java +++ b/application/src/main/java/org/thingsboard/server/service/install/EntityDatabaseSchemaService.java @@ -8,4 +8,6 @@ public interface EntityDatabaseSchemaService extends DatabaseSchemaService { void createOrUpdateViewsAndFunctions() throws Exception; + void generateClusterIdIfNotExist(); + } diff --git a/application/src/main/java/org/thingsboard/server/service/install/SqlEntityDatabaseSchemaService.java b/application/src/main/java/org/thingsboard/server/service/install/SqlEntityDatabaseSchemaService.java index 8ed65c390f..e90df5e1ea 100644 --- a/application/src/main/java/org/thingsboard/server/service/install/SqlEntityDatabaseSchemaService.java +++ b/application/src/main/java/org/thingsboard/server/service/install/SqlEntityDatabaseSchemaService.java @@ -6,6 +6,14 @@ import lombok.extern.slf4j.Slf4j; import org.springframework.context.annotation.Profile; import org.springframework.stereotype.Service; +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; +import java.util.UUID; + @Service @Profile("install") @Slf4j @@ -43,4 +51,36 @@ public class SqlEntityDatabaseSchemaService extends SqlAbstractDatabaseSchemaSer executeQueryFromFile(SCHEMA_FUNCTIONS_SQL); } + @Override + public void generateClusterIdIfNotExist() { + var clusterId = UUID.randomUUID(); + try (Connection conn = DriverManager.getConnection(dbUrl, dbUserName, dbPassword); + PreparedStatement statement = conn.prepareStatement( + "INSERT INTO tb_cluster (cluster_id) SELECT ?::uuid WHERE NOT EXISTS (SELECT 1 FROM tb_cluster) ON CONFLICT DO NOTHING")) { + statement.setString(1, clusterId.toString()); + int insertedRows = statement.executeUpdate(); + UUID storedClusterId = insertedRows > 0 ? clusterId : readClusterId(conn); + if (storedClusterId != null) { + logClusterId(storedClusterId); + } + } catch (SQLException e) { + log.error("Failed to generate Cluster id", e); + throw new RuntimeException("Failed to generate Cluster id", e); + } + } + + private UUID readClusterId(Connection conn) throws SQLException { + try (Statement statement = conn.createStatement(); + ResultSet rs = statement.executeQuery("SELECT cluster_id FROM tb_cluster")) { + return rs.next() ? rs.getObject(1, UUID.class) : null; + } + } + + private void logClusterId(UUID clusterId) { + String line = ":: Cluster Id: " + clusterId + " ::"; + String border = "=".repeat(line.length()); + // Logged at JVM shutdown so it follows the rest of the install output. + Runtime.getRuntime().addShutdownHook(new Thread(() -> log.info("\n{}\n{}\n{}\n", border, line, border))); + } + } diff --git a/application/src/main/java/org/thingsboard/server/service/install/lts/LtsMigrationService.java b/application/src/main/java/org/thingsboard/server/service/install/lts/LtsMigrationService.java index 9f6e22b2b3..d333814171 100644 --- a/application/src/main/java/org/thingsboard/server/service/install/lts/LtsMigrationService.java +++ b/application/src/main/java/org/thingsboard/server/service/install/lts/LtsMigrationService.java @@ -67,18 +67,29 @@ public class LtsMigrationService { .toList(); } - /** No-downtime path: per migration in (from, to] run SQL, then apply(), then record the version. */ - public void applyMigrations(String fromVersion, String toVersion) { - for (VersionedMigration vm : select(fromVersion, toVersion)) { - LtsMigration migration = vm.migration(); + /** + * No version in (from, to] is recorded until every migration and {@code afterSchemaPhase} succeed, so a + * failure re-runs them all: each {@link LtsMigration} and its SQL must be idempotent. + */ + public void applyMigrations(String fromVersion, String toVersion, Runnable afterSchemaPhase) { + List selected = select(fromVersion, toVersion); + for (VersionedMigration versionedMigration : selected) { + LtsMigration migration = versionedMigration.migration(); String version = migration.getVersion(); transactionTemplate.executeWithoutResult(status -> { runSchemaUpdate(version); migration.apply(); - schemaSettingsService.updateSchemaVersion(version); }); log.info("Applied LTS migration {}", version); } + + afterSchemaPhase.run(); + + for (VersionedMigration versionedMigration : selected) { + String version = versionedMigration.migration().getVersion(); + schemaSettingsService.updateSchemaVersion(version); + log.info("Recorded LTS migration version {}", version); + } } /** Offline major-upgrade schema phase: per migration in (from, to] run SQL only. No version record. */ diff --git a/application/src/main/java/org/thingsboard/server/service/install/lts/V4_3_1_6Migration.java b/application/src/main/java/org/thingsboard/server/service/install/lts/V4_3_1_6Migration.java new file mode 100644 index 0000000000..2a28cce7af --- /dev/null +++ b/application/src/main/java/org/thingsboard/server/service/install/lts/V4_3_1_6Migration.java @@ -0,0 +1,43 @@ +// SPDX-FileCopyrightText: Copyright The Thingsboard Authors +// SPDX-License-Identifier: Apache-2.0 +package org.thingsboard.server.service.install.lts; + +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.stereotype.Component; +import org.thingsboard.server.queue.util.TbCoreComponent; + +import java.util.UUID; + +/** + * Creates {@code tb_cluster} and mints the cluster id on the no-downtime patch path, which runs neither + * {@code schema-entities.sql} nor {@code generateClusterIdIfNotExist()}. Both steps are idempotent. + */ +@Slf4j +@Component +@TbCoreComponent +@RequiredArgsConstructor +public class V4_3_1_6Migration implements LtsMigration { + + private final JdbcTemplate jdbcTemplate; + + @Override + public String getVersion() { + return "4.3.1.6"; + } + + // Must run in the migration transaction: tb_cluster is created there and is not yet visible to other connections. + @Override + public void apply() { + UUID clusterId = UUID.randomUUID(); + int insertedRows = jdbcTemplate.update( + "INSERT INTO tb_cluster (cluster_id) SELECT ?::uuid WHERE NOT EXISTS (SELECT 1 FROM tb_cluster) ON CONFLICT DO NOTHING", + clusterId.toString()); + if (insertedRows > 0) { + log.info("Generated Cluster Id: {}", clusterId); + } else { + log.info("Cluster Id already exists, keeping it"); + } + } +} diff --git a/application/src/main/java/org/thingsboard/server/service/system/SystemPatchApplier.java b/application/src/main/java/org/thingsboard/server/service/system/SystemPatchApplier.java index d97d2c5ddf..c1391f111b 100644 --- a/application/src/main/java/org/thingsboard/server/service/system/SystemPatchApplier.java +++ b/application/src/main/java/org/thingsboard/server/service/system/SystemPatchApplier.java @@ -93,19 +93,7 @@ public class SystemPatchApplier { try { String dbVersion = schemaSettingsService.getDbSchemaVersion(); String packageVersion = schemaSettingsService.getPackageSchemaVersion(); - ltsMigrationService.applyMigrations(dbVersion, packageVersion); - - updateSqlViews(); - log.info("Updated sql database views"); - - WidgetTypeStats widgetStats = updateWidgetTypes(); - log.info("System widget types: {} created, {} updated", widgetStats.created(), widgetStats.updated()); - - int updatedBundles = updateWidgetBundles(); - log.info("System widget bundles: {} updated", updatedBundles); - - int createdImages = createMissingSystemImages(); - log.info("Created {} new system images", createdImages); + ltsMigrationService.applyMigrations(dbVersion, packageVersion, this::syncSystemData); schemaSettingsService.updateSchemaVersion(); log.info("System data patch update completed successfully"); @@ -115,6 +103,21 @@ public class SystemPatchApplier { } } + // Views are rebuilt with SELECT * over tables the migrations may have altered, so this must run after them. + private void syncSystemData() { + updateSqlViews(); + log.info("Updated sql database views"); + + WidgetTypeStats widgetStats = updateWidgetTypes(); + log.info("System widget types: {} created, {} updated", widgetStats.created(), widgetStats.updated()); + + int updatedBundles = updateWidgetBundles(); + log.info("System widget bundles: {} updated", updatedBundles); + + int createdImages = createMissingSystemImages(); + log.info("Created {} new system images", createdImages); + } + private boolean isVersionChanged() { String packageVersion = schemaSettingsService.getPackageSchemaVersion(); String dbVersion = schemaSettingsService.getDbSchemaVersion(); diff --git a/application/src/main/resources/thingsboard.yml b/application/src/main/resources/thingsboard.yml index fe454447c5..d0fa7565f9 100644 --- a/application/src/main/resources/thingsboard.yml +++ b/application/src/main/resources/thingsboard.yml @@ -43,7 +43,8 @@ server: # HTTP settings http: # Semi-colon-separated list of urlPattern=maxPayloadSize pairs that define max http request size for specified url pattern. After first match all other will be skipped - max_payload_size: "${HTTP_MAX_PAYLOAD_SIZE_LIMIT_CONFIGURATION:/api/image*/**=52428800;/api/resource/**=52428800;/api/**=16777216}" + # The /api/communityGrant/offline/run entry must precede /api/** to allow instance checker uploads; it is prepended automatically if missing + max_payload_size: "${HTTP_MAX_PAYLOAD_SIZE_LIMIT_CONFIGURATION:/api/communityGrant/offline/run=35651584;/api/image*/**=52428800;/api/resource/**=52428800;/api/**=16777216}" # HTTP/2 support (takes effect only if server SSL is enabled) http2: # Enable/disable HTTP/2 support @@ -2237,3 +2238,18 @@ iot-hub: max-uncompressed-entry-bytes: "${IOT_HUB_MAX_UNCOMPRESSED_ENTRY_BYTES:52428800}" # maximum uncompressed size in bytes for any single entry inside a solution template archive. max-archive-entry-count: "${IOT_HUB_MAX_ARCHIVE_ENTRY_COUNT:10000}" # maximum number of entries allowed inside a solution template archive. max-install-timeout-ms: "${IOT_HUB_MAX_INSTALL_TIMEOUT_MS:60000}" # upper clamp in milliseconds for the post-install wait declared in a solution template's solution.json. Prevents a malicious or misconfigured template from pinning an HTTP worker thread. + +community-grant: + enabled: "${COMMUNITY_GRANT_ENABLED:true}" # enables the community grant enrollment flow; when disabled, no flow can be started and no outbound calls are made. + base-url: "${COMMUNITY_GRANT_BASE_URL:https://license.thingsboard.io}" # base URL of the license portal. + connect-timeout-sec: "${COMMUNITY_GRANT_CONNECT_TIMEOUT_SEC:5}" # timeout in seconds to connect to the license portal. + read-timeout-sec: "${COMMUNITY_GRANT_READ_TIMEOUT_SEC:10}" # timeout in seconds to read from the license portal. + fast-poll-interval-ms: "${COMMUNITY_GRANT_FAST_POLL_INTERVAL_MS:3000}" # interval in milliseconds between portal polls during the initial polling window; a node never polls more often than every 2000 ms. + fast-poll-window-ms: "${COMMUNITY_GRANT_FAST_POLL_WINDOW_MS:120000}" # duration in milliseconds of the initial polling window, after which the slow interval is used. + slow-poll-interval-ms: "${COMMUNITY_GRANT_SLOW_POLL_INTERVAL_MS:30000}" # interval in milliseconds between portal polls after the initial polling window. + supervise-interval-ms: "${COMMUNITY_GRANT_SUPERVISE_INTERVAL_MS:30000}" # interval in milliseconds at which the node owning the system tenant partition picks up enrollment flows started on other nodes. + sign-up-deadline-ms: "${COMMUNITY_GRANT_SIGN_UP_DEADLINE_MS:86400000}" # how long in milliseconds to poll for an uncompleted sign-up before the flow is stopped and can be restarted. + max-checker-size-bytes: "${COMMUNITY_GRANT_MAX_CHECKER_SIZE_BYTES:33554432}" # maximum size in bytes of the instance checker, downloaded or uploaded; keep below the /api/communityGrant/offline/run limit in server.http.max_payload_size. + checker-timeout-sec: "${COMMUNITY_GRANT_CHECKER_TIMEOUT_SEC:600}" # maximum time in seconds the instance checker may run before it is terminated; an offline run still unfinished 2 minutes later is reported as interrupted. + max-report-size-bytes: "${COMMUNITY_GRANT_MAX_REPORT_SIZE_BYTES:1048576}" # maximum size in bytes of the output accepted from the instance checker. + checker-release-public-keys: "${COMMUNITY_GRANT_CHECKER_RELEASE_PUBLIC_KEYS:1:Xwg49dWb+Ofzx4FzIvxqYMS9EV9hqzlTGmphtTYZtw4=}" # comma-separated keyId:base64Key list (keyId 1-255, raw 32-byte Ed25519 key) trusted to sign the instance checker; if empty or unparseable, no instance checker is run. diff --git a/application/src/test/java/org/thingsboard/server/controller/CommunityGrantControllerTest.java b/application/src/test/java/org/thingsboard/server/controller/CommunityGrantControllerTest.java new file mode 100644 index 0000000000..8d34f8a7ba --- /dev/null +++ b/application/src/test/java/org/thingsboard/server/controller/CommunityGrantControllerTest.java @@ -0,0 +1,678 @@ +// SPDX-FileCopyrightText: Copyright The Thingsboard Authors +// SPDX-License-Identifier: Apache-2.0 +package org.thingsboard.server.controller; + +import com.fasterxml.jackson.core.type.TypeReference; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.node.ObjectNode; +import org.hamcrest.Matchers; +import org.junit.Test; +import org.mockito.ArgumentCaptor; +import org.mockito.Mockito; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.HttpHeaders; +import org.springframework.http.MediaType; +import org.springframework.mock.web.MockMultipartFile; +import org.springframework.test.context.bean.override.mockito.MockitoSpyBean; +import org.springframework.test.util.AopTestUtils; +import org.springframework.test.util.ReflectionTestUtils; +import org.springframework.test.web.servlet.ResultActions; +import org.springframework.test.web.servlet.request.MockMultipartHttpServletRequestBuilder; +import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; +import org.thingsboard.common.util.JacksonUtil; +import org.thingsboard.server.common.data.User; +import org.thingsboard.server.common.data.audit.ActionStatus; +import org.thingsboard.server.common.data.audit.ActionType; +import org.thingsboard.server.common.data.audit.AuditLog; +import org.thingsboard.server.common.data.community_grant.CommunityGrantFlowState; +import org.thingsboard.server.common.data.community_grant.CommunityGrantMode; +import org.thingsboard.server.common.data.community_grant.CommunityGrantOfflineRun; +import org.thingsboard.server.common.data.community_grant.CommunityGrantState; +import org.thingsboard.server.common.data.page.PageLink; +import org.thingsboard.server.common.data.page.SortOrder; +import org.thingsboard.server.common.data.page.TimePageLink; +import org.thingsboard.server.dao.audit.AuditLogService; +import org.thingsboard.server.dao.service.DaoSqlTest; +import org.thingsboard.server.service.community_grant.CommunityGrantBundleFixtures; +import org.thingsboard.server.service.community_grant.CommunityGrantCheckerInput; +import org.thingsboard.server.service.community_grant.CommunityGrantFlowStateStore; +import org.thingsboard.server.service.community_grant.CommunityGrantOfflineReportStore; +import org.thingsboard.server.service.community_grant.CommunityGrantPlatform; +import org.thingsboard.server.service.community_grant.CommunityGrantPoller; +import org.thingsboard.server.service.community_grant.CommunityGrantPortalClient; +import org.thingsboard.server.service.community_grant.CommunityGrantPortalStatus; +import org.thingsboard.server.service.community_grant.CommunityGrantReportRunner; +import org.thingsboard.server.service.community_grant.CommunityGrantService; + +import java.nio.charset.StandardCharsets; +import java.util.List; +import java.util.UUID; +import java.util.concurrent.Semaphore; +import java.util.concurrent.TimeUnit; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.awaitility.Awaitility.await; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.never; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.header; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +@DaoSqlTest +public class CommunityGrantControllerTest extends AbstractControllerTest { + + private static final List ALLOWED_FIELDS = + List.of("mode", "state", "signUpUrl", "lastPolledAt", "parkReason", "portalUrl", "offlineReport", + "offlineRunInProgress", "offlineRunError"); + private static final String REPORT = "-----BEGIN TB INSTANCE CHECK-----\nbody"; + private static final String BUNDLE_FILE_NAME = "tb-instance-check-bundle_" + + CommunityGrantPlatform.current().os() + "_" + CommunityGrantPlatform.current().arch() + ".tbicb"; + private static final long EXPIRED_ISSUED_AT = 1609459200000L; + private static final long EXPIRED_EXPIRES_AT = 1609545600000L; + // Mirror package-private constants of DefaultCommunityGrantService. + private static final String NOT_ALREADY_REGISTERED_MESSAGE = + "This action is only available once this deployment is confirmed as already registered under another account."; + private static final String NOTHING_TO_HAND_OVER_MESSAGE = + "This deployment is not waiting for a check result to be handed over."; + + @Autowired + private AuditLogService auditLogService; + @Autowired + private CommunityGrantFlowStateStore flowStateStore; + @Autowired + private CommunityGrantPoller poller; + @Autowired + private CommunityGrantService communityGrantService; + @Autowired + private CommunityGrantOfflineReportStore offlineReportStore; + @MockitoSpyBean + private CommunityGrantPortalClient portalClient; + @MockitoSpyBean + private CommunityGrantReportRunner reportRunner; + + @Test + public void testStateIsNotStartedBeforeAnyAction() throws Exception { + loginSysAdmin(); + + JsonNode state = doGetTyped("/api/communityGrant/state", new TypeReference() {}); + + assertThat(state.get("state").asText()).isEqualTo(CommunityGrantState.NOT_STARTED.name()); + assertThat(state.get("mode").asText()).isEqualTo("ONLINE"); + assertThat(state.get("signUpUrl").isNull()).isTrue(); + assertThat(state.get("lastPolledAt").isNull()).isTrue(); + } + + @Test + public void testStateExposesNothingBeyondTheContract() throws Exception { + loginSysAdmin(); + + ResultActions result = doGet("/api/communityGrant/state").andExpect(status().isOk()); + String body = result.andReturn().getResponse().getContentAsString(); + JsonNode state = JacksonUtil.toJsonNode(body); + + state.fieldNames().forEachRemaining(field -> assertThat(field).isIn(ALLOWED_FIELDS)); + assertThat(state.get("portalUrl").asText()).isNotBlank(); + } + + @Test + public void testStateRequiresAuthentication() throws Exception { + loginSysAdmin(); + TimeUnit.SECONDS.sleep(1); //We need to make sure that event for invalidating token was successfully processed + logout(); + doGet("/api/communityGrant/state").andExpect(status().isUnauthorized()); + } + + @Test + public void testStateIsForbiddenForATenantAdmin() throws Exception { + loginTenantAdmin(); + doGet("/api/communityGrant/state").andExpect(status().isForbidden()); + } + + @Test + public void testStartIsForbiddenForATenantAdmin() throws Exception { + loginTenantAdmin(); + doPost("/api/communityGrant/start").andExpect(status().isForbidden()); + } + + @Test + public void testOfflineReportIsForbiddenForATenantAdmin() throws Exception { + loginTenantAdmin(); + doGet("/api/communityGrant/offline/report").andExpect(status().isForbidden()); + } + + @Test + public void testOfflineReportIsDownloadedAsAPlainTextAttachment() throws Exception { + loginSysAdmin(); + offlineReportStore.put(REPORT); + try { + doGet("/api/communityGrant/offline/report") + .andExpect(status().isOk()) + .andExpect(header().string(HttpHeaders.CONTENT_DISPOSITION, + "attachment; filename=\"tb-instance-check-report.txt\"")) + .andExpect(content().contentTypeCompatibleWith(MediaType.TEXT_PLAIN)) + .andExpect(content().string(REPORT)); + } finally { + // The stored report outlives the test, and other tests expect none. + offlineReportStore.clear(); + } + } + + @Test + public void testOfflineReportIsServedFromTheDatabaseRow() throws Exception { + loginSysAdmin(); + offlineReportStore.put(REPORT); + try { + String served = doGet("/api/communityGrant/offline/report").andExpect(status().isOk()) + .andReturn().getResponse().getContentAsString(); + assertThat(served).isEqualTo(REPORT); + Mockito.verifyNoInteractions(reportRunner); + // This node also holds a local copy, so the row itself is checked. + assertThat(jdbcTemplate.queryForObject( + "SELECT json_value::json ->> 'report' FROM admin_settings WHERE key = 'communityGrantReport'", + String.class)).isEqualTo(REPORT); + } finally { + offlineReportStore.clear(); + } + } + + @Test + public void testStateCarriesTheReportOnTheStepThatShowsIt() throws Exception { + loginSysAdmin(); + offlineReportStore.put(REPORT); + try { + flowStateStore.update(state -> { + state.setState(CommunityGrantState.VALIDATING); + state.setLastOfflineCheckAt(System.currentTimeMillis()); + return state; + }); + + JsonNode state = doGetTyped("/api/communityGrant/state", new TypeReference() {}); + + assertThat(state.get("offlineReport").asText()).isEqualTo(REPORT); + } finally { + offlineReportStore.clear(); + flowStateStore.update(state -> CommunityGrantFlowState.initial()); + } + } + + @Test + public void testStateCarriesNoReportBeforeAnyCheckHasRun() throws Exception { + loginSysAdmin(); + + JsonNode state = doGetTyped("/api/communityGrant/state", new TypeReference() {}); + + assertThat(state.get("offlineReport").isNull()).isTrue(); + } + + @Test + public void testOfflineReportIsNotFoundBeforeAnyCheckHasRun() throws Exception { + loginSysAdmin(); + + doGet("/api/communityGrant/offline/report").andExpect(status().isNotFound()); + } + + @Test + public void testOfflineHandoffIsForbiddenForATenantAdmin() throws Exception { + loginTenantAdmin(); + doPost("/api/communityGrant/offline/handoff").andExpect(status().isForbidden()); + } + + @Test + public void testOfflineHandoffClaimsTheReportAndIsAudited() throws Exception { + loginSysAdmin(); + User currentUser = doGet("/api/auth/user", User.class); + offlineReportStore.put(REPORT); + try { + flowStateStore.update(state -> { + state.setMode(CommunityGrantMode.OFFLINE); + state.setState(CommunityGrantState.VALIDATING); + state.setLastOfflineCheckAt(System.currentTimeMillis()); + return state; + }); + + JsonNode state = JacksonUtil.toJsonNode(doPost("/api/communityGrant/offline/handoff") + .andExpect(status().isOk()).andReturn().getResponse().getContentAsString()); + + assertThat(state.get("state").asText()).isEqualTo(CommunityGrantState.REPORT_HANDED_OVER.name()); + assertThat(state.get("offlineReport").asText()).isEqualTo(REPORT); + assertThat(flowStateStore.get().getState()).isEqualTo(CommunityGrantState.REPORT_HANDED_OVER); + assertSingleAuditLog(currentUser, ActionType.COMMUNITY_GRANT_ENROLLMENT, ActionStatus.SUCCESS); + } finally { + offlineReportStore.clear(); + flowStateStore.update(state -> CommunityGrantFlowState.initial()); + } + } + + @Test + public void testOfflineHandoffRefusalIsAudited() throws Exception { + loginSysAdmin(); + User currentUser = doGet("/api/auth/user", User.class); + + doPost("/api/communityGrant/offline/handoff").andExpect(status().isBadRequest()); + + assertThat(assertSingleAuditLog(currentUser, ActionType.COMMUNITY_GRANT_ENROLLMENT, ActionStatus.FAILURE) + .getActionFailureDetails()).contains(NOTHING_TO_HAND_OVER_MESSAGE); + } + + @Test + public void testRequestAccessIsForbiddenForATenantAdmin() throws Exception { + loginTenantAdmin(); + doPost("/api/communityGrant/requestAccess").andExpect(status().isForbidden()); + } + + // A well-formed bundle, so the 403 comes from @PreAuthorize. + @Test + public void testOfflineRunIsForbiddenForATenantAdmin() throws Exception { + loginTenantAdmin(); + + mockMvc.perform(offlineRunRequest(bundleForThisHost(CommunityGrantBundleFixtures.relsig()))) + .andExpect(status().isForbidden()); + } + + @Test + public void testRequestAccessRefusalIsAuditedWhenNotAlreadyRegistered() throws Exception { + loginSysAdmin(); + User currentUser = doGet("/api/auth/user", User.class); + + doPost("/api/communityGrant/requestAccess").andExpect(status().isBadRequest()); + + String failureDetails = assertSingleAuditLog(currentUser, ActionType.COMMUNITY_GRANT_REQUEST_ACCESS, + ActionStatus.FAILURE).getActionFailureDetails(); + // The column carries a whole stack trace, so the refusal message is asserted rather than absent substrings. + assertThat(failureDetails).contains(NOT_ALREADY_REGISTERED_MESSAGE); + } + + // Neither tb_cluster nor the admin_settings row is reset between tests, and DaoSqlTest does not seed tb_cluster. + @Test + public void testRequestAccessSuccessIsAudited() throws Exception { + loginSysAdmin(); + User currentUser = doGet("/api/auth/user", User.class); + boolean seededClusterId = Boolean.TRUE.equals( + jdbcTemplate.queryForObject("SELECT NOT EXISTS (SELECT 1 FROM tb_cluster)", Boolean.class)); + try { + if (seededClusterId) { + jdbcTemplate.update("INSERT INTO tb_cluster (cluster_id) VALUES (?::uuid)", UUID.randomUUID().toString()); + } + flowStateStore.update(state -> { + state.setMode(CommunityGrantMode.ONLINE); + state.setState(CommunityGrantState.ALREADY_REGISTERED); + return state; + }); + Mockito.doNothing().when(portalClient).requestAccess(any()); + + doPost("/api/communityGrant/requestAccess").andExpect(status().isOk()); + + assertSingleAuditLog(currentUser, ActionType.COMMUNITY_GRANT_REQUEST_ACCESS, ActionStatus.SUCCESS); + Mockito.verify(portalClient).requestAccess(any()); + } finally { + flowStateStore.update(state -> CommunityGrantFlowState.initial()); + if (seededClusterId) { + jdbcTemplate.update("DELETE FROM tb_cluster"); + } + } + } + + @Test + public void testStartIsDrivenToATerminalStateByTheRealPoller() throws Exception { + loginSysAdmin(); + boolean seededClusterId = Boolean.TRUE.equals( + jdbcTemplate.queryForObject("SELECT NOT EXISTS (SELECT 1 FROM tb_cluster)", Boolean.class)); + try { + if (seededClusterId) { + jdbcTemplate.update("INSERT INTO tb_cluster (cluster_id) VALUES (?::uuid)", UUID.randomUUID().toString()); + } + Mockito.doReturn(true).when(portalClient).isPortalReachable(); + Mockito.doReturn(false).when(portalClient).isAlreadyRegistered(any()); + Mockito.doReturn(new CommunityGrantPortalStatus("AWAITING_SIGNUP", null, null), + new CommunityGrantPortalStatus("DONE", null, null)) + .when(portalClient).getStatus(any(), any()); + + doPost("/api/communityGrant/start").andExpect(status().isOk()); + + await("the poller reaching a terminal state").atMost(30, TimeUnit.SECONDS) + .until(() -> flowStateStore.get().getState() == CommunityGrantState.REGISTERED); + assertThat(jdbcTemplate.queryForObject("SELECT license_claim_token FROM tb_cluster", String.class)).isNull(); + } finally { + poller.disarm(); + flowStateStore.update(state -> CommunityGrantFlowState.initial()); + if (seededClusterId) { + jdbcTemplate.update("DELETE FROM tb_cluster"); + } + } + } + + @Test + public void testStartReturnsASignUpUrlToASysAdmin() throws Exception { + loginSysAdmin(); + boolean seededClusterId = Boolean.TRUE.equals( + jdbcTemplate.queryForObject("SELECT NOT EXISTS (SELECT 1 FROM tb_cluster)", Boolean.class)); + try { + if (seededClusterId) { + jdbcTemplate.update("INSERT INTO tb_cluster (cluster_id) VALUES (?::uuid)", UUID.randomUUID().toString()); + } + Mockito.doReturn(true).when(portalClient).isPortalReachable(); + Mockito.doReturn(false).when(portalClient).isAlreadyRegistered(any()); + Mockito.doReturn(new CommunityGrantPortalStatus("AWAITING_SIGNUP", null, null)) + .when(portalClient).getStatus(any(), any()); + + JsonNode state = JacksonUtil.toJsonNode(doPost("/api/communityGrant/start") + .andExpect(status().isOk()).andReturn().getResponse().getContentAsString()); + + assertThat(state.get("state").asText()).isEqualTo(CommunityGrantState.AWAITING_SIGNUP.name()); + assertThat(state.get("mode").asText()).isEqualTo(CommunityGrantMode.ONLINE.name()); + assertThat(state.get("signUpUrl").asText()).startsWith("http"); + } finally { + poller.disarm(); + flowStateStore.update(state -> CommunityGrantFlowState.initial()); + if (seededClusterId) { + jdbcTemplate.update("DELETE FROM tb_cluster"); + } + } + } + + // Zero bytes in place of the release signature: the parser passes them on and the verifier refuses them. + @Test + public void testOfflineRunRefusalIsAudited() throws Exception { + loginSysAdmin(); + User currentUser = doGet("/api/auth/user", User.class); + String previousClusterId = currentClusterId(); + try { + setClusterId(CommunityGrantBundleFixtures.CLUSTER_ID); + + mockMvc.perform(offlineRunRequest(bundleForThisHost(new byte[74]))).andExpect(status().isBadRequest()); + } finally { + setClusterId(previousClusterId); + } + + String failureDetails = assertSingleAuditLog(currentUser, ActionType.COMMUNITY_GRANT_OFFLINE_CHECKER_RUN, + ActionStatus.FAILURE).getActionFailureDetails(); + assertThat(failureDetails).contains("not a ThingsBoard release signature"); + assertThat(failureDetails.toLowerCase()).doesNotContain("secret"); + assertThat(failureDetails).doesNotContain("postgres://"); + assertThat(failureDetails.toLowerCase()).doesNotContain("password"); + } + + @Test + public void testOfflineRunWithAFileThatIsNotABundleIsRefusedAndAudited() throws Exception { + loginSysAdmin(); + User currentUser = doGet("/api/auth/user", User.class); + + mockMvc.perform(offlineRunRequest("not a bundle at all".getBytes(StandardCharsets.UTF_8))) + .andExpect(status().isBadRequest()); + + assertThat(assertSingleAuditLog(currentUser, ActionType.COMMUNITY_GRANT_OFFLINE_CHECKER_RUN, + ActionStatus.FAILURE).getActionFailureDetails()).contains("not a ThingsBoard enrollment bundle"); + Mockito.verify(reportRunner, never()).runUploadedChecker(any(), any(), any(), any()); + } + + @Test + public void testOfflineRunOnAnArchitectureWithNoCheckerBuildIsRefusedAndAudited() throws Exception { + loginSysAdmin(); + User currentUser = doGet("/api/auth/user", User.class); + // Built before os.arch is swapped, so the manifest names the real host. + byte[] bundle = bundleForThisHost(CommunityGrantBundleFixtures.relsig()); + String previousArch = System.getProperty("os.arch"); + try { + System.setProperty("os.arch", "s390x"); + + mockMvc.perform(offlineRunRequest(bundle)) + .andExpect(status().isBadRequest()) + .andExpect(content().string(Matchers.containsString("no instance checker build"))); + } finally { + System.setProperty("os.arch", previousArch); + } + + assertSingleAuditLog(currentUser, ActionType.COMMUNITY_GRANT_OFFLINE_CHECKER_RUN, ActionStatus.FAILURE); + Mockito.verify(reportRunner, never()).runUploadedChecker(any(), any(), any(), any()); + } + + @Test + public void testOfflineRunWithABundleForAnotherInstallationIsRefused() throws Exception { + loginSysAdmin(); + String previousClusterId = currentClusterId(); + try { + setClusterId(UUID.randomUUID().toString()); + + mockMvc.perform(offlineRunRequest(bundleForThisHost(CommunityGrantBundleFixtures.relsig()))) + .andExpect(status().isBadRequest()) + .andExpect(content().string(Matchers.containsString("different installation"))); + + Mockito.verify(reportRunner, never()).runUploadedChecker(any(), any(), any(), any()); + } finally { + setClusterId(previousClusterId); + } + } + + @Test + public void testOfflineRunWithAWrongPlatformBundleNamesBothPlatforms() throws Exception { + loginSysAdmin(); + CommunityGrantPlatform host = CommunityGrantPlatform.current(); + String otherOs = "linux".equals(host.os()) ? "darwin" : "linux"; + ObjectNode manifest = CommunityGrantBundleFixtures.validManifest(); + manifest.put("os", otherOs); + manifest.put("arch", host.arch()); + + mockMvc.perform(offlineRunRequest(CommunityGrantBundleFixtures.bundle(manifest))) + .andExpect(status().isBadRequest()) + .andExpect(content().string(Matchers.containsString(otherOs))) + .andExpect(content().string(Matchers.containsString(host.os()))); + + Mockito.verify(reportRunner, never()).runUploadedChecker(any(), any(), any(), any()); + } + + @Test + public void testTheRunnerIsGivenTheCheckersOwnNameAndTheManifestsInput() throws Exception { + loginSysAdmin(); + String previousClusterId = currentClusterId(); + try { + setClusterId(CommunityGrantBundleFixtures.CLUSTER_ID); + givenTheRunnerAcceptsAndReturns(REPORT); + + mockMvc.perform(offlineRunRequest(bundleForThisHost(CommunityGrantBundleFixtures.relsig()))) + .andExpect(status().isAccepted()); + awaitOfflineRunFinished(); + + ArgumentCaptor verifiedName = ArgumentCaptor.forClass(String.class); + Mockito.verify(reportRunner).verifyUploadedChecker(any(), any(), verifiedName.capture()); + assertThat(verifiedName.getValue()).isEqualTo(CHECKER_FILE_NAME_FOR_THIS_HOST); + ArgumentCaptor fileName = ArgumentCaptor.forClass(String.class); + ArgumentCaptor checkerInput = + ArgumentCaptor.forClass(CommunityGrantCheckerInput.class); + Mockito.verify(reportRunner) + .runUploadedChecker(any(), any(), fileName.capture(), checkerInput.capture()); + assertThat(fileName.getValue()).isEqualTo(CHECKER_FILE_NAME_FOR_THIS_HOST); + assertThat(checkerInput.getValue().json()) + .isEqualTo(JacksonUtil.toString(CommunityGrantBundleFixtures.validCheckerInput())); + } finally { + setClusterId(previousClusterId); + offlineReportStore.clear(); + flowStateStore.update(state -> CommunityGrantFlowState.initial()); + } + } + + @Test + public void testOfflineRunAnswers202AndTheReportArrivesThroughTheState() throws Exception { + loginSysAdmin(); + User currentUser = doGet("/api/auth/user", User.class); + String previousClusterId = currentClusterId(); + try { + setClusterId(CommunityGrantBundleFixtures.CLUSTER_ID); + givenAnOfflineEnrollment(); + givenTheRunnerAcceptsAndReturns(REPORT); + + byte[] bundle = bundleForThisHost(CommunityGrantBundleFixtures.relsig()); + String body = mockMvc.perform(offlineRunRequest(bundle)) + .andExpect(status().isAccepted()) + .andReturn().getResponse().getContentAsString(); + assertThat(JacksonUtil.toJsonNode(body).get("offlineRunInProgress").asBoolean()).isTrue(); + awaitOfflineRunFinished(); + + JsonNode state = doGetTyped("/api/communityGrant/state", new TypeReference() {}); + assertThat(state.get("offlineRunInProgress").asBoolean()).isFalse(); + assertThat(state.get("offlineRunError").isNull()).isTrue(); + assertThat(state.get("state").asText()).isEqualTo(CommunityGrantState.VALIDATING.name()); + assertThat(state.get("offlineReport").asText()).isEqualTo(REPORT); + assertSingleAuditLog(currentUser, ActionType.COMMUNITY_GRANT_OFFLINE_CHECKER_RUN, ActionStatus.SUCCESS); + } finally { + setClusterId(previousClusterId); + offlineReportStore.clear(); + flowStateStore.update(state -> CommunityGrantFlowState.initial()); + } + } + + @Test + public void testAFailedOfflineRunIsReportedThroughTheState() throws Exception { + loginSysAdmin(); + User currentUser = doGet("/api/auth/user", User.class); + String previousClusterId = currentClusterId(); + try { + setClusterId(CommunityGrantBundleFixtures.CLUSTER_ID); + givenAnOfflineEnrollment(); + Mockito.doNothing().when(reportRunner).verifyUploadedChecker(any(), any(), any()); + Mockito.doThrow(new IllegalStateException("The instance check failed with exit code 3")) + .when(reportRunner).runUploadedChecker(any(), any(), any(), any()); + + mockMvc.perform(offlineRunRequest(bundleForThisHost(CommunityGrantBundleFixtures.relsig()))) + .andExpect(status().isAccepted()); + awaitOfflineRunFinished(); + + JsonNode state = doGetTyped("/api/communityGrant/state", new TypeReference() {}); + assertThat(state.get("offlineRunInProgress").asBoolean()).isFalse(); + assertThat(state.get("offlineRunError").asText()) + .isEqualTo("Failed to run the check. The instance check failed with exit code 3"); + assertThat(state.get("state").asText()).isEqualTo(CommunityGrantState.AWAITING_SIGNUP.name()); + assertThat(assertSingleAuditLog(currentUser, ActionType.COMMUNITY_GRANT_OFFLINE_CHECKER_RUN, + ActionStatus.FAILURE).getActionFailureDetails()).contains("exit code 3"); + } finally { + setClusterId(previousClusterId); + offlineReportStore.clear(); + flowStateStore.update(state -> CommunityGrantFlowState.initial()); + } + } + + @Test + public void testOfflineRunIsRefusedWhileAnotherRunIsInProgress() throws Exception { + loginSysAdmin(); + User currentUser = doGet("/api/auth/user", User.class); + String previousClusterId = currentClusterId(); + try { + setClusterId(CommunityGrantBundleFixtures.CLUSTER_ID); + Mockito.doNothing().when(reportRunner).verifyUploadedChecker(any(), any(), any()); + flowStateStore.update(state -> { + state.setOfflineRun(CommunityGrantOfflineRun.running(UUID.randomUUID(), System.currentTimeMillis())); + return state; + }); + + mockMvc.perform(offlineRunRequest(bundleForThisHost(CommunityGrantBundleFixtures.relsig()))) + .andExpect(status().isTooManyRequests()); + + Mockito.verify(reportRunner, never()).runUploadedChecker(any(), any(), any(), any()); + JsonNode state = doGetTyped("/api/communityGrant/state", new TypeReference() {}); + assertThat(state.get("offlineRunInProgress").asBoolean()).isTrue(); + assertThat(assertSingleAuditLog(currentUser, ActionType.COMMUNITY_GRANT_OFFLINE_CHECKER_RUN, + ActionStatus.FAILURE).getActionFailureDetails()).contains("already running"); + } finally { + setClusterId(previousClusterId); + flowStateStore.update(state -> CommunityGrantFlowState.initial()); + } + } + + /** The stand-in checker is not signed by a trusted key, so both runner steps are stubbed. */ + private void givenTheRunnerAcceptsAndReturns(String report) { + Mockito.doNothing().when(reportRunner).verifyUploadedChecker(any(), any(), any()); + Mockito.doReturn(report).when(reportRunner).runUploadedChecker(any(), any(), any(), any()); + } + + private void givenAnOfflineEnrollment() { + flowStateStore.update(state -> { + state.setMode(CommunityGrantMode.OFFLINE); + state.setState(CommunityGrantState.AWAITING_SIGNUP); + return state; + }); + } + + /** The permit is released last, after the run's state write and audit call. */ + private void awaitOfflineRunFinished() { + Object service = AopTestUtils.getUltimateTargetObject(communityGrantService); + Semaphore permit = (Semaphore) ReflectionTestUtils.getField(service, "offlineRunPermit"); + await("the background offline run").atMost(10, TimeUnit.SECONDS) + .until(() -> permit.availablePermits() == 1); + } + + @Test + public void testAnExpiredChallengeWarnsAndStillReachesTheRunner() throws Exception { + loginSysAdmin(); + String previousClusterId = currentClusterId(); + try { + setClusterId(CommunityGrantBundleFixtures.CLUSTER_ID); + givenTheRunnerAcceptsAndReturns(REPORT); + ObjectNode manifest = CommunityGrantBundleFixtures.validManifest(); + manifest.put("os", CommunityGrantPlatform.current().os()); + manifest.put("arch", CommunityGrantPlatform.current().arch()); + manifest.put("issuedAt", EXPIRED_ISSUED_AT); + manifest.put("challengeExpiresAt", EXPIRED_EXPIRES_AT); + + mockMvc.perform(offlineRunRequest(CommunityGrantBundleFixtures.bundle(manifest))) + .andExpect(status().isAccepted()); + awaitOfflineRunFinished(); + + Mockito.verify(reportRunner).runUploadedChecker(any(), any(), any(), any()); + } finally { + setClusterId(previousClusterId); + offlineReportStore.clear(); + flowStateStore.update(state -> CommunityGrantFlowState.initial()); + } + } + + private String currentClusterId() { + return jdbcTemplate.query("SELECT cluster_id FROM tb_cluster LIMIT 1", + rs -> rs.next() ? rs.getString(1) : null); + } + + private void setClusterId(String clusterId) { + jdbcTemplate.update("DELETE FROM tb_cluster"); + if (clusterId != null) { + jdbcTemplate.update("INSERT INTO tb_cluster (cluster_id) VALUES (?::uuid)", clusterId); + } + } + + private static final String CHECKER_FILE_NAME_FOR_THIS_HOST = "tb-instance-check_" + + CommunityGrantPlatform.current().os() + "_" + CommunityGrantPlatform.current().arch(); + + private static byte[] bundleForThisHost(byte[] relsig) { + ObjectNode manifest = CommunityGrantBundleFixtures.validManifest(); + manifest.put("os", CommunityGrantPlatform.current().os()); + manifest.put("arch", CommunityGrantPlatform.current().arch()); + manifest.put("checkerFileName", CHECKER_FILE_NAME_FOR_THIS_HOST); + return CommunityGrantBundleFixtures.bundle(relsig, + JacksonUtil.toString(manifest).getBytes(StandardCharsets.UTF_8), + CommunityGrantBundleFixtures.standInChecker()); + } + + private MockMultipartHttpServletRequestBuilder offlineRunRequest(byte[] bundle) { + MockMultipartHttpServletRequestBuilder postRequest = + MockMvcRequestBuilders.multipart("/api/communityGrant/offline/run"); + postRequest.file(new MockMultipartFile("bundle", BUNDLE_FILE_NAME, "application/octet-stream", bundle)); + setJwtToken(postRequest); + return postRequest; + } + + /** Audit logs are written asynchronously. */ + private AuditLog assertSingleAuditLog(User user, ActionType actionType, ActionStatus expectedStatus) { + await("async audit log saving").atMost(5, TimeUnit.SECONDS) + .until(() -> !findAuditLogs(user, actionType).isEmpty()); + List auditLogs = findAuditLogs(user, actionType); + + assertThat(auditLogs).hasSize(1); + assertThat(auditLogs.get(0).getActionStatus()).isEqualTo(expectedStatus); + return auditLogs.get(0); + } + + private List findAuditLogs(User user, ActionType actionType) { + return auditLogService.findAuditLogsByTenantIdAndUserId( + user.getTenantId(), user.getId(), List.of(actionType), + new TimePageLink(new PageLink(10, 0, null, new SortOrder("createdTime", SortOrder.Direction.DESC)), + 0L, System.currentTimeMillis())).getData(); + } + +} diff --git a/application/src/test/java/org/thingsboard/server/install/ThingsboardInstallServiceTest.java b/application/src/test/java/org/thingsboard/server/install/ThingsboardInstallServiceTest.java new file mode 100644 index 0000000000..71f2d6938d --- /dev/null +++ b/application/src/test/java/org/thingsboard/server/install/ThingsboardInstallServiceTest.java @@ -0,0 +1,90 @@ +// SPDX-FileCopyrightText: Copyright The Thingsboard Authors +// SPDX-License-Identifier: Apache-2.0 +package org.thingsboard.server.install; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.InOrder; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; +import org.springframework.context.ApplicationContext; +import org.springframework.test.util.ReflectionTestUtils; +import org.thingsboard.server.service.component.ComponentDiscoveryService; +import org.thingsboard.server.service.install.DatabaseEntitiesUpgradeService; +import org.thingsboard.server.service.install.DatabaseSchemaSettingsService; +import org.thingsboard.server.service.install.EntityDatabaseSchemaService; +import org.thingsboard.server.service.install.InstallScripts; +import org.thingsboard.server.service.install.SystemDataLoaderService; +import org.thingsboard.server.service.install.TsDatabaseSchemaService; +import org.thingsboard.server.service.install.update.CacheCleanupService; +import org.thingsboard.server.service.install.update.DataUpdateService; + +import static org.mockito.Mockito.inOrder; +import static org.mockito.Mockito.verify; + +@ExtendWith(MockitoExtension.class) +class ThingsboardInstallServiceTest { + + @Mock + private EntityDatabaseSchemaService entityDatabaseSchemaService; + @Mock + private TsDatabaseSchemaService tsDatabaseSchemaService; + @Mock + private DatabaseEntitiesUpgradeService databaseEntitiesUpgradeService; + @Mock + private ComponentDiscoveryService componentDiscoveryService; + @Mock + private ApplicationContext context; + @Mock + private SystemDataLoaderService systemDataLoaderService; + @Mock + private DataUpdateService dataUpdateService; + @Mock + private CacheCleanupService cacheCleanupService; + @Mock + private InstallScripts installScripts; + @Mock + private DatabaseSchemaSettingsService databaseSchemaVersionService; + + private ThingsboardInstallService installService; + + @BeforeEach + void setUp() { + installService = new ThingsboardInstallService(); + ReflectionTestUtils.setField(installService, "entityDatabaseSchemaService", entityDatabaseSchemaService); + ReflectionTestUtils.setField(installService, "tsDatabaseSchemaService", tsDatabaseSchemaService); + ReflectionTestUtils.setField(installService, "databaseEntitiesUpgradeService", databaseEntitiesUpgradeService); + ReflectionTestUtils.setField(installService, "componentDiscoveryService", componentDiscoveryService); + ReflectionTestUtils.setField(installService, "context", context); + ReflectionTestUtils.setField(installService, "systemDataLoaderService", systemDataLoaderService); + ReflectionTestUtils.setField(installService, "dataUpdateService", dataUpdateService); + ReflectionTestUtils.setField(installService, "cacheCleanupService", cacheCleanupService); + ReflectionTestUtils.setField(installService, "installScripts", installScripts); + ReflectionTestUtils.setField(installService, "databaseSchemaVersionService", databaseSchemaVersionService); + ReflectionTestUtils.setField(installService, "loadDemo", false); + ReflectionTestUtils.setField(installService, "persistToTelemetry", false); + } + + @Test + void testUpgradeMintsTheClusterIdBeforeStampingTheSchemaVersion() { + ReflectionTestUtils.setField(installService, "isUpgrade", true); + ReflectionTestUtils.setField(installService, "upgradeFromVersion", "4.3.1.3"); + + installService.performInstall(); + + InOrder inOrder = inOrder(entityDatabaseSchemaService, databaseSchemaVersionService); + inOrder.verify(entityDatabaseSchemaService).generateClusterIdIfNotExist(); + inOrder.verify(databaseSchemaVersionService).updateSchemaVersion(); + } + + @Test + void testFreshInstallMintsTheClusterId() { + ReflectionTestUtils.setField(installService, "isUpgrade", false); + + installService.performInstall(); + + verify(entityDatabaseSchemaService).generateClusterIdIfNotExist(); + } + +} diff --git a/application/src/test/java/org/thingsboard/server/service/community_grant/CommunityGrantBundleFixtures.java b/application/src/test/java/org/thingsboard/server/service/community_grant/CommunityGrantBundleFixtures.java new file mode 100644 index 0000000000..28b68841ec --- /dev/null +++ b/application/src/test/java/org/thingsboard/server/service/community_grant/CommunityGrantBundleFixtures.java @@ -0,0 +1,126 @@ +// SPDX-FileCopyrightText: Copyright The Thingsboard Authors +// SPDX-License-Identifier: Apache-2.0 +package org.thingsboard.server.service.community_grant; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.node.ObjectNode; +import org.thingsboard.common.util.JacksonUtil; + +import java.io.IOException; +import java.io.InputStream; +import java.io.UncheckedIOException; +import java.nio.ByteBuffer; +import java.nio.charset.StandardCharsets; +import java.util.HexFormat; + +/** + * Golden {@code TBICBDL1} vectors; {@code vectors.json} records each file's size and SHA-256. + */ +public final class CommunityGrantBundleFixtures { + + public static final String CLUSTER_ID = "3f2a1c44-9f3b-11ee-8c90-0242ac120002"; + public static final String CHALLENGE = "Y2hhbGxlbmdlLTAwMS1ieXRlcw=="; + public static final String PORTAL_PUBLIC_KEY = "KTA3PkVMU1phaG92fYSLkpmgp661vMPK0djf5u30+wI="; + public static final int KEY_ID = 1; + public static final long REFERENCE_MILLIS = 1787788800000L; + public static final long ISSUED_AT = 4102444800000L; + public static final long CHALLENGE_EXPIRES_AT = 4102531200000L; + public static final String CHECKER_FILE_NAME = "tb-instance-check_linux_amd64"; + + /** Verifies the golden bundle's {@code RELSIG} under {@link #KEY_ID}. */ + public static final String RELEASE_PUBLIC_KEY = "Nqbrd0SVV4w9yZWl0cgu9I7G/URhdL3PN8mWRwnWDzE="; + public static final String TRUSTS_RELEASE_KEY = KEY_ID + ":" + RELEASE_PUBLIC_KEY; + + private static final String RELSIG_HEX = "544249435349473101013ab2afc43727f37b9388510b6c0e0b7d920a738ee" + + "df45aae5169aa7d97abe3f73796b907168188e0685566bbf792ae0977b6c38072e684ee149d6bcf161fc004"; + + private static final String VECTOR_RESOURCE_DIR = "/community-grant/"; + + private CommunityGrantBundleFixtures() { + } + + public static byte[] vector(String fileName) { + return resource(VECTOR_RESOURCE_DIR + fileName); + } + + public static JsonNode vectorsManifest() { + return JacksonUtil.fromBytes(resource(VECTOR_RESOURCE_DIR + "vectors.json")); + } + + public static byte[] relsig() { + return HexFormat.of().parseHex(RELSIG_HEX); + } + + public static byte[] standInChecker() { + byte[] checker = new byte[64]; + for (int i = 0; i < checker.length; i++) { + checker[i] = (byte) (i * 7 + 3); + } + return checker; + } + + public static ObjectNode validManifest() { + ObjectNode manifest = JacksonUtil.newObjectNode(); + manifest.put("bundleVersion", 1); + manifest.put("os", "linux"); + manifest.put("arch", "amd64"); + manifest.put("clusterId", CLUSTER_ID); + manifest.set("checkerInput", validCheckerInput()); + manifest.put("challengeExpiresAt", CHALLENGE_EXPIRES_AT); + manifest.put("issuedAt", ISSUED_AT); + manifest.put("checkerFileName", CHECKER_FILE_NAME); + return manifest; + } + + public static ObjectNode validCheckerInput() { + ObjectNode checkerInput = JacksonUtil.newObjectNode(); + checkerInput.put("clusterId", CLUSTER_ID); + checkerInput.put("keyId", KEY_ID); + checkerInput.put("publicKey", PORTAL_PUBLIC_KEY); + checkerInput.put("challenge", CHALLENGE); + checkerInput.put("referenceMillis", REFERENCE_MILLIS); + return checkerInput; + } + + public static byte[] bundle(JsonNode manifest) { + return bundle(JacksonUtil.toString(manifest)); + } + + public static byte[] bundle(String manifestJson) { + return bundle(manifestJson.getBytes(StandardCharsets.UTF_8)); + } + + public static byte[] bundle(byte[] manifest) { + return bundle(relsig(), manifest, standInChecker()); + } + + public static byte[] bundle(byte[] relsig, byte[] manifest, byte[] checker) { + return frame((byte) 1, manifest.length, checker.length, relsig, manifest, checker); + } + + /** Declared lengths are written as given, so the header can disagree with the body. */ + public static byte[] frame(byte version, long declaredManifestLen, long declaredCheckerLen, + byte[] relsig, byte[] manifest, byte[] checker) { + return ByteBuffer.allocate(CommunityGrantOfflineBundle.HEADER_LEN + manifest.length + checker.length) + .put("TBICBDL1".getBytes(StandardCharsets.US_ASCII)) + .put(version) + .putInt((int) declaredManifestLen) + .putInt((int) declaredCheckerLen) + .put(relsig) + .put(manifest) + .put(checker) + .array(); + } + + private static byte[] resource(String path) { + try (InputStream in = CommunityGrantBundleFixtures.class.getResourceAsStream(path)) { + if (in == null) { + throw new IllegalStateException(path + " is not on the test classpath"); + } + return in.readAllBytes(); + } catch (IOException e) { + throw new UncheckedIOException(e); + } + } + +} diff --git a/application/src/test/java/org/thingsboard/server/service/community_grant/CommunityGrantFlowStateStoreTest.java b/application/src/test/java/org/thingsboard/server/service/community_grant/CommunityGrantFlowStateStoreTest.java new file mode 100644 index 0000000000..1c9efca6be --- /dev/null +++ b/application/src/test/java/org/thingsboard/server/service/community_grant/CommunityGrantFlowStateStoreTest.java @@ -0,0 +1,305 @@ +// SPDX-FileCopyrightText: Copyright The Thingsboard Authors +// SPDX-License-Identifier: Apache-2.0 +package org.thingsboard.server.service.community_grant; + +import com.fasterxml.jackson.databind.JsonNode; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.ArgumentCaptor; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; +import org.thingsboard.common.util.JacksonUtil; +import org.thingsboard.server.common.data.AdminSettings; +import org.thingsboard.server.common.data.community_grant.CommunityGrantFlowState; +import org.thingsboard.server.common.data.community_grant.CommunityGrantMode; +import org.thingsboard.server.common.data.community_grant.CommunityGrantParkReason; +import org.thingsboard.server.common.data.community_grant.CommunityGrantState; +import org.thingsboard.server.common.data.id.AdminSettingsId; +import org.thingsboard.server.common.data.id.TenantId; +import org.thingsboard.server.dao.settings.AdminSettingsService; +import org.thingsboard.server.exception.DataValidationException; + +import java.util.UUID; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.argThat; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +@ExtendWith(MockitoExtension.class) +class CommunityGrantFlowStateStoreTest { + + @Mock + private AdminSettingsService adminSettingsService; + + @InjectMocks + private CommunityGrantFlowStateStore store; + + @Test + void testGetReturnsTheInitialStateWhenNothingIsStored() { + givenStored(null); + + CommunityGrantFlowState state = store.get(); + + assertThat(state.getState()).isEqualTo(CommunityGrantState.NOT_STARTED); + assertThat(state.getMode()).isEqualTo(CommunityGrantMode.ONLINE); + assertThat(state.getSignUpUrl()).isNull(); + assertThat(state.getLastPolledAt()).isNull(); + } + + @Test + void testGetReadsTheStoredState() { + CommunityGrantFlowState stored = CommunityGrantFlowState.initial(); + stored.setState(CommunityGrantState.AWAITING_SIGNUP); + stored.setMode(CommunityGrantMode.OFFLINE); + stored.setSignUpUrl("https://portal.example/signup?clusterId=x&claimToken=y&offline=true"); + stored.setLastPolledAt(42L); + givenStored(settingsOf(stored)); + + CommunityGrantFlowState state = store.get(); + + assertThat(state.getState()).isEqualTo(CommunityGrantState.AWAITING_SIGNUP); + assertThat(state.getMode()).isEqualTo(CommunityGrantMode.OFFLINE); + assertThat(state.getSignUpUrl()) + .isEqualTo("https://portal.example/signup?clusterId=x&claimToken=y&offline=true"); + assertThat(state.getLastPolledAt()).isEqualTo(42L); + } + + @Test + void testUpdateRoundTripsTheFieldsTheFlowCarriesBetweenPolls() { + givenStored(null); + + store.update(state -> { + state.setState(CommunityGrantState.COLLECTING); + state.setStartedAt(1234L); + state.setLastOfflineCheckAt(5678L); + state.setParkReason(CommunityGrantParkReason.CHECK_FAILED); + return state; + }); + + ArgumentCaptor captor = ArgumentCaptor.forClass(AdminSettings.class); + verify(adminSettingsService).saveAdminSettings(eq(TenantId.SYS_TENANT_ID), captor.capture()); + when(adminSettingsService.findAdminSettingsByKey(TenantId.SYS_TENANT_ID, CommunityGrantFlowStateStore.SETTINGS_KEY)) + .thenReturn(captor.getValue()); + + CommunityGrantFlowState reread = store.get(); + + assertThat(reread.getStartedAt()).isEqualTo(1234L); + assertThat(reread.getLastOfflineCheckAt()).isEqualTo(5678L); + assertThat(reread.getParkReason()).isEqualTo(CommunityGrantParkReason.CHECK_FAILED); + } + + @Test + void testUpdateCreatesTheSettingsRowOnFirstWrite() { + givenStored(null); + + CommunityGrantFlowState updated = store.update(state -> { + state.setState(CommunityGrantState.AWAITING_SIGNUP); + state.setSignUpUrl("https://portal.example/signup"); + return state; + }); + + assertThat(updated.getState()).isEqualTo(CommunityGrantState.AWAITING_SIGNUP); + ArgumentCaptor captor = ArgumentCaptor.forClass(AdminSettings.class); + verify(adminSettingsService).saveAdminSettings(eq(TenantId.SYS_TENANT_ID), captor.capture()); + AdminSettings saved = captor.getValue(); + assertThat(saved.getKey()).isEqualTo(CommunityGrantFlowStateStore.SETTINGS_KEY); + assertThat(saved.getTenantId()).isEqualTo(TenantId.SYS_TENANT_ID); + JsonNode json = saved.getJsonValue(); + assertThat(json.get("state").asText()).isEqualTo("AWAITING_SIGNUP"); + assertThat(json.get("signUpUrl").asText()).isEqualTo("https://portal.example/signup"); + } + + @Test + void testUpdatePreservesFieldsTheUpdaterDoesNotTouch() { + CommunityGrantFlowState stored = CommunityGrantFlowState.initial(); + stored.setState(CommunityGrantState.AWAITING_SIGNUP); + stored.setSignUpUrl("https://portal.example/signup"); + givenStored(settingsOf(stored)); + + store.update(state -> { + state.setLastPolledAt(100L); + return state; + }); + + ArgumentCaptor captor = ArgumentCaptor.forClass(AdminSettings.class); + verify(adminSettingsService).saveAdminSettings(eq(TenantId.SYS_TENANT_ID), captor.capture()); + JsonNode json = captor.getValue().getJsonValue(); + assertThat(json.get("signUpUrl").asText()).isEqualTo("https://portal.example/signup"); + assertThat(json.get("lastPolledAt").asLong()).isEqualTo(100L); + } + + @Test + void testGetFallsBackToTheInitialStateOnUnreadableJson() { + givenStored(settingsOf("{\"state\":\"NOT_A_STATE\"}")); + + assertThat(store.get().getState()).isEqualTo(CommunityGrantState.NOT_STARTED); + } + + @Test + void testUpdateThrowsOnUnreadableJsonAndLeavesTheStoredDocumentUntouched() { + givenStored(settingsOf("{\"state\":\"NOT_A_STATE\"}")); + + assertThatThrownBy(() -> store.update(state -> state)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("could not be parsed"); + + verify(adminSettingsService, never()).saveAdminSettings(any(), any()); + } + + @Test + void testUpdateRetriesAsAnUpdateWhenAConcurrentFirstWriteWinsTheCreateRace() { + CommunityGrantFlowState winnerState = CommunityGrantFlowState.initial(); + winnerState.setState(CommunityGrantState.COLLECTING); + winnerState.setSignUpUrl("https://portal.example/signup?winner=true"); + AdminSettings winnerRow = new AdminSettings(); + winnerRow.setId(new AdminSettingsId(UUID.randomUUID())); + winnerRow.setTenantId(TenantId.SYS_TENANT_ID); + winnerRow.setKey(CommunityGrantFlowStateStore.SETTINGS_KEY); + winnerRow.setJsonValue(JacksonUtil.valueToTree(winnerState)); + // No row on the first read; the re-read after the lost create finds the other node's row. + when(adminSettingsService.findAdminSettingsByKey(TenantId.SYS_TENANT_ID, CommunityGrantFlowStateStore.SETTINGS_KEY)) + .thenReturn(null, winnerRow); + when(adminSettingsService.saveAdminSettings(eq(TenantId.SYS_TENANT_ID), argThat(s -> s.getId() == null))) + .thenThrow(new DataValidationException("Admin settings with such name already exists!")); + when(adminSettingsService.saveAdminSettings(eq(TenantId.SYS_TENANT_ID), argThat(s -> s != null && s.getId() != null))) + .thenAnswer(invocation -> invocation.getArgument(1)); + + CommunityGrantFlowState result = store.update(state -> { + state.setLastPolledAt(999L); + return state; + }); + + assertThat(result.getState()).isEqualTo(CommunityGrantState.COLLECTING); + assertThat(result.getSignUpUrl()).isEqualTo("https://portal.example/signup?winner=true"); + assertThat(result.getLastPolledAt()).isEqualTo(999L); + verify(adminSettingsService, times(2)).saveAdminSettings(eq(TenantId.SYS_TENANT_ID), any(AdminSettings.class)); + } + + @Test + void testAnUnreadableWinnerDocumentThrowsAndKeepsTheCreateRaceAttached() { + AdminSettings winnerRow = new AdminSettings(); + winnerRow.setId(new AdminSettingsId(UUID.randomUUID())); + winnerRow.setTenantId(TenantId.SYS_TENANT_ID); + winnerRow.setKey(CommunityGrantFlowStateStore.SETTINGS_KEY); + winnerRow.setJsonValue(JacksonUtil.toJsonNode("{\"state\":\"NOT_A_STATE\"}")); + when(adminSettingsService.findAdminSettingsByKey(TenantId.SYS_TENANT_ID, CommunityGrantFlowStateStore.SETTINGS_KEY)) + .thenReturn(null, winnerRow); + when(adminSettingsService.saveAdminSettings(eq(TenantId.SYS_TENANT_ID), argThat(s -> s.getId() == null))) + .thenThrow(new DataValidationException("Admin settings with such name already exists!")); + + assertThatThrownBy(() -> store.update(state -> { + state.setState(CommunityGrantState.AWAITING_SIGNUP); + return state; + })) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("could not be parsed") + .satisfies(e -> assertThat(e.getSuppressed()) + .as("the create race that led to the re-read") + .anySatisfy(suppressed -> assertThat(suppressed) + .isInstanceOf(DataValidationException.class))); + + verify(adminSettingsService, times(1)).saveAdminSettings(eq(TenantId.SYS_TENANT_ID), any(AdminSettings.class)); + } + + @Test + void testUpdateDoesNotRetryWhenTheRejectedWriteWasAnUpdateRatherThanACreate() { + AdminSettings stored = settingsOf(CommunityGrantFlowState.initial()); + stored.setId(new AdminSettingsId(UUID.randomUUID())); + givenStored(stored); + when(adminSettingsService.saveAdminSettings(eq(TenantId.SYS_TENANT_ID), any(AdminSettings.class))) + .thenThrow(new DataValidationException("Admin settings with such name already exists!")); + + assertThatThrownBy(() -> store.update(state -> { + state.setState(CommunityGrantState.AWAITING_SIGNUP); + return state; + })).isInstanceOf(DataValidationException.class); + + verify(adminSettingsService, times(1)).saveAdminSettings(eq(TenantId.SYS_TENANT_ID), any(AdminSettings.class)); + } + + @Test + void testUpdateDoesNotRetryWhenTheRejectedCreateFindsNoWinnerRow() { + givenStored(null); + when(adminSettingsService.saveAdminSettings(eq(TenantId.SYS_TENANT_ID), any(AdminSettings.class))) + .thenThrow(new DataValidationException("Admin settings with such name already exists!")); + + assertThatThrownBy(() -> store.update(state -> { + state.setState(CommunityGrantState.AWAITING_SIGNUP); + return state; + })).isInstanceOf(DataValidationException.class); + + verify(adminSettingsService, times(1)).saveAdminSettings(eq(TenantId.SYS_TENANT_ID), any(AdminSettings.class)); + } + + @Test + void testUpdateSucceedsWhenTheStoredDocumentParsesButCarriesNoState() { + givenStored(settingsOf("{}")); + + CommunityGrantFlowState updated = store.update(state -> { + state.setState(CommunityGrantState.AWAITING_SIGNUP); + return state; + }); + + assertThat(updated.getState()).isEqualTo(CommunityGrantState.AWAITING_SIGNUP); + verify(adminSettingsService).saveAdminSettings(eq(TenantId.SYS_TENANT_ID), any(AdminSettings.class)); + } + + @Test + void testUpdateSucceedsWhenTheStoredJsonValueIsAJsonNull() { + givenStored(settingsOf("null")); + + CommunityGrantFlowState updated = store.update(state -> { + state.setState(CommunityGrantState.AWAITING_SIGNUP); + return state; + }); + + assertThat(updated.getState()).isEqualTo(CommunityGrantState.AWAITING_SIGNUP); + verify(adminSettingsService).saveAdminSettings(eq(TenantId.SYS_TENANT_ID), any(AdminSettings.class)); + } + + @Test + void testGetDefaultsTheModeWhenTheStoredDocumentHasNone() { + givenStored(settingsOf("{\"state\":\"COLLECTING\"}")); + + CommunityGrantFlowState state = store.get(); + + assertThat(state.getState()).isEqualTo(CommunityGrantState.COLLECTING); + assertThat(state.getMode()).isEqualTo(CommunityGrantMode.ONLINE); + } + + @Test + void testGetIgnoresUnknownJsonFieldsInsteadOfFailing() { + givenStored(settingsOf("{\"state\":\"AWAITING_SIGNUP\",\"futureField\":1}")); + + assertThat(store.get().getState()).isEqualTo(CommunityGrantState.AWAITING_SIGNUP); + } + + private AdminSettings settingsOf(CommunityGrantFlowState state) { + return settingsOf(JacksonUtil.valueToTree(state)); + } + + private AdminSettings settingsOf(String json) { + return settingsOf(JacksonUtil.toJsonNode(json)); + } + + private AdminSettings settingsOf(JsonNode jsonValue) { + AdminSettings settings = new AdminSettings(); + settings.setTenantId(TenantId.SYS_TENANT_ID); + settings.setKey(CommunityGrantFlowStateStore.SETTINGS_KEY); + settings.setJsonValue(jsonValue); + return settings; + } + + private void givenStored(AdminSettings settings) { + when(adminSettingsService.findAdminSettingsByKey(TenantId.SYS_TENANT_ID, CommunityGrantFlowStateStore.SETTINGS_KEY)) + .thenReturn(settings); + } + +} diff --git a/application/src/test/java/org/thingsboard/server/service/community_grant/CommunityGrantLibpqDsnTest.java b/application/src/test/java/org/thingsboard/server/service/community_grant/CommunityGrantLibpqDsnTest.java new file mode 100644 index 0000000000..92523c7b43 --- /dev/null +++ b/application/src/test/java/org/thingsboard/server/service/community_grant/CommunityGrantLibpqDsnTest.java @@ -0,0 +1,64 @@ +// SPDX-FileCopyrightText: Copyright The Thingsboard Authors +// SPDX-License-Identifier: Apache-2.0 +package org.thingsboard.server.service.community_grant; + +import org.junit.jupiter.api.Test; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +class CommunityGrantLibpqDsnTest { + + private static final String URL = "jdbc:postgresql://localhost:5432/thingsboard"; + + @Test + void testTheJdbcUrlIsRewrittenAsALibpqConnectionString() { + assertThat(CommunityGrantLibpqDsn.from(URL, "postgres", "secret")) + .isEqualTo("postgres://postgres:secret@localhost:5432/thingsboard"); + assertThat(CommunityGrantLibpqDsn.from(URL, "postgres", "p@ss/word?x")) + .isEqualTo("postgres://postgres:p%40ss%2Fword%3Fx@localhost:5432/thingsboard"); + // JDBC driver parameters are not libpq's, so they are dropped. + assertThat(CommunityGrantLibpqDsn.from( + "jdbc:postgresql://db.internal:5432/tb?ApplicationName=ThingsBoard&ssl=false", "postgres", "secret")) + .isEqualTo("postgres://postgres:secret@db.internal:5432/tb"); + } + + // URI leaves ':' in userinfo unescaped, but libpq splits user and password at the first colon. + @Test + void testAUsernameContainingAColonIsEncodedSeparately() { + assertThat(CommunityGrantLibpqDsn.from(URL, "a:b", "c")) + .isEqualTo("postgres://a%3Ab:c@localhost:5432/thingsboard"); + } + + // The url may carry credentials, so the refusal quotes neither it nor a cause that holds it. + @Test + void testAMalformedDatasourceUrlIsRejectedWithoutQuotingTheUrl() { + assertThatThrownBy(() -> CommunityGrantLibpqDsn.from( + "jdbc:postgresql://host:5432/tb?user=admin&password=hunter2^{}", "postgres", "secret")) + .isInstanceOf(IllegalStateException.class) + .satisfies(e -> { + assertThat(e.getMessage()).doesNotContain("hunter2"); + assertThat(e.getMessage()).doesNotContain("host:5432"); + assertThat(e).hasNoCause(); + }); + } + + @Test + void testANonPostgresqlJdbcUrlIsRejected() { + assertThatThrownBy(() -> CommunityGrantLibpqDsn.from("jdbc:mysql://localhost:3306/thingsboard", + "postgres", "secret")).isInstanceOf(IllegalStateException.class); + } + + @Test + void testAUrlWithNoDatabaseNameIsRejected() { + assertThatThrownBy(() -> CommunityGrantLibpqDsn.from("jdbc:postgresql://localhost:5432", + "postgres", "secret")).isInstanceOf(IllegalStateException.class); + } + + @Test + void testABlankUsernameIsRejected() { + assertThatThrownBy(() -> CommunityGrantLibpqDsn.from(URL, "", "secret")) + .isInstanceOf(IllegalStateException.class); + } + +} diff --git a/application/src/test/java/org/thingsboard/server/service/community_grant/CommunityGrantOfflineBundleTest.java b/application/src/test/java/org/thingsboard/server/service/community_grant/CommunityGrantOfflineBundleTest.java new file mode 100644 index 0000000000..2a565e4a2f --- /dev/null +++ b/application/src/test/java/org/thingsboard/server/service/community_grant/CommunityGrantOfflineBundleTest.java @@ -0,0 +1,421 @@ +// SPDX-FileCopyrightText: Copyright The Thingsboard Authors +// SPDX-License-Identifier: Apache-2.0 +package org.thingsboard.server.service.community_grant; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.node.IntNode; +import com.fasterxml.jackson.databind.node.NullNode; +import com.fasterxml.jackson.databind.node.ObjectNode; +import com.fasterxml.jackson.databind.node.TextNode; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.CsvSource; +import org.junit.jupiter.params.provider.MethodSource; +import org.junit.jupiter.params.provider.ValueSource; +import org.springframework.test.util.ReflectionTestUtils; +import org.thingsboard.common.util.JacksonUtil; +import org.thingsboard.server.service.community_grant.CommunityGrantBundleFormatException.Reason; + +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HexFormat; +import java.util.List; +import java.util.Locale; +import java.util.UUID; +import java.util.stream.Stream; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatCode; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.thingsboard.server.service.community_grant.CommunityGrantBundleFixtures.CHALLENGE; +import static org.thingsboard.server.service.community_grant.CommunityGrantBundleFixtures.CHALLENGE_EXPIRES_AT; +import static org.thingsboard.server.service.community_grant.CommunityGrantBundleFixtures.CHECKER_FILE_NAME; +import static org.thingsboard.server.service.community_grant.CommunityGrantBundleFixtures.CLUSTER_ID; +import static org.thingsboard.server.service.community_grant.CommunityGrantBundleFixtures.ISSUED_AT; +import static org.thingsboard.server.service.community_grant.CommunityGrantBundleFixtures.KEY_ID; +import static org.thingsboard.server.service.community_grant.CommunityGrantBundleFixtures.PORTAL_PUBLIC_KEY; +import static org.thingsboard.server.service.community_grant.CommunityGrantBundleFixtures.REFERENCE_MILLIS; +import static org.thingsboard.server.service.community_grant.CommunityGrantBundleFixtures.bundle; +import static org.thingsboard.server.service.community_grant.CommunityGrantBundleFixtures.frame; +import static org.thingsboard.server.service.community_grant.CommunityGrantBundleFixtures.relsig; +import static org.thingsboard.server.service.community_grant.CommunityGrantBundleFixtures.standInChecker; +import static org.thingsboard.server.service.community_grant.CommunityGrantBundleFixtures.validCheckerInput; +import static org.thingsboard.server.service.community_grant.CommunityGrantBundleFixtures.validManifest; +import static org.thingsboard.server.service.community_grant.CommunityGrantBundleFixtures.vector; +import static org.thingsboard.server.service.community_grant.CommunityGrantBundleFixtures.vectorsManifest; + +/** + * Vectors 05-07 are malformed in two ways at once, so they pin the order of the checks as well as the reasons. + */ +class CommunityGrantOfflineBundleTest { + + private static final String CHECKER_SHA256 = + "39e3d7b6b5d075d37d053ad89b24b41bef4f3c29760c84447cab3f3be1882241"; + + @ParameterizedTest(name = "{0}") + @MethodSource("goldenVectors") + void testEveryGoldenVectorHasItsRecordedSizeDigestAndOutcome(String fileName, int sizeBytes, String sha256, + String outcome, String reason) { + byte[] data = vector(fileName); + + assertThat(data).hasSize(sizeBytes); + assertThat(HexFormat.of().formatHex(sha256(data))).isEqualTo(sha256); + if ("REJECT".equals(outcome)) { + assertThat(reasonOf(data)).isEqualTo(Reason.valueOf(reason.substring("E_".length()))); + } else { + assertThatCode(() -> CommunityGrantOfflineBundle.parse(data)).doesNotThrowAnyException(); + } + } + + @Test + void testAFileShorterThanTheHeaderIsRefusedBeforeAnythingIsRead() { + assertThatThrownBy(() -> CommunityGrantOfflineBundle.parse(vector("02-too-short.tbicb"))) + .isInstanceOf(CommunityGrantBundleFormatException.class) + .hasMessageContaining("The uploaded file is 90 bytes") + .hasMessageContaining("shorter than the 91-byte enrollment bundle header"); + } + + @ParameterizedTest + @ValueSource(ints = {0, 1, 90}) + void testNoInputAndAnEmptyInputAreRefusedOnTheLengthFloor(int size) { + assertThat(reasonOf(new byte[size])).isEqualTo(Reason.TOO_SHORT); + assertThat(reasonOf(null)).isEqualTo(Reason.TOO_SHORT); + } + + @Test + void testTheVersionRefusalNamesBothTheDeclaredAndTheSupportedVersion() { + assertThatThrownBy(() -> CommunityGrantOfflineBundle.parse(vector("04-unknown-version.tbicb"))) + .hasMessageContaining("declares format version 2") + .hasMessageContaining("supports version 1 only"); + } + + @ParameterizedTest + @CsvSource({"05-manifest-len-zero.tbicb, 0", "06-manifest-len-too-large.tbicb, 8193"}) + void testTheManifestLengthRefusalNamesTheDeclaredValueAndThePermittedRange(String fileName, String declared) { + assertThatThrownBy(() -> CommunityGrantOfflineBundle.parse(vector(fileName))) + .hasMessageContaining("declares a manifest of " + declared + " bytes") + .hasMessageContaining("permitted range of 1 to 8192 bytes"); + } + + @Test + void testTheCheckerLengthRefusalNamesTheDeclaredValue() { + assertThatThrownBy(() -> CommunityGrantOfflineBundle.parse(vector("07-checker-len-zero.tbicb"))) + .hasMessageContaining("declares a checker of 0 bytes"); + } + + // Exact, not at-least: otherwise anything could be appended to a genuine bundle. + @ParameterizedTest + @CsvSource({"08-truncated-mid-manifest.tbicb, 301", "09-truncated-mid-checker.tbicb, 543", + "10-trailing-byte.tbicb, 576"}) + void testTheExactnessRefusalNamesBothTheExpectedAndTheActualTotal(String fileName, String actualTotal) { + assertThatThrownBy(() -> CommunityGrantOfflineBundle.parse(vector(fileName))) + .hasMessageContaining("need a file of 575 bytes") + .hasMessageContaining("uploaded file is " + actualTotal + " bytes"); + } + + // Decoding with new String(bytes, UTF_8) would substitute replacement characters and report bad JSON instead. + @Test + void testAManifestThatIsNotUtf8IsRefusedAsNotUtf8RatherThanAsNotJson() { + assertThat(reasonOf(vector("11-manifest-not-utf8.tbicb"))).isEqualTo(Reason.MANIFEST_NOT_UTF8); + } + + @ParameterizedTest + @ValueSource(strings = {"[1,2,3]", "\"x\"", "7", "null", "true"}) + void testAManifestThatIsNotAJsonObjectIsRefused(String manifestJson) { + assertThat(reasonOf(bundle(manifestJson))).isEqualTo(Reason.MANIFEST_NOT_JSON); + } + + @Test + void testAMissingManifestFieldIsRefusedByName() { + assertThatThrownBy(() -> CommunityGrantOfflineBundle.parse(vector("13-manifest-missing-field.tbicb"))) + .hasMessageContaining("clusterId"); + } + + @ParameterizedTest(name = "{0}") + @MethodSource("manifestsBrokenOneRuleAtATime") + void testEveryManifestRuleIsEnforcedAndNamesItsOwnKey(String description, JsonNode manifest, String key) { + assertThatThrownBy(() -> CommunityGrantOfflineBundle.parse(bundle(manifest))) + .isInstanceOf(CommunityGrantBundleFormatException.class) + .hasMessageContaining(key); + assertThat(reasonOf(bundle(manifest))).isEqualTo(Reason.MANIFEST_FIELD); + } + + // Parsers disagree about which duplicate wins, so the two ends could read different values. + @Test + void testADuplicateManifestKeyIsRefusedByName() { + String manifestJson = JacksonUtil.toString(validManifest()) + .replace("\"checkerInput\":", "\"clusterId\":\"" + CLUSTER_ID + "\",\"checkerInput\":"); + + assertThat(reasonOf(bundle(manifestJson))).isEqualTo(Reason.MANIFEST_FIELD); + assertThatThrownBy(() -> CommunityGrantOfflineBundle.parse(bundle(manifestJson))) + .hasMessageContaining("clusterId"); + } + + @Test + void testTheReaderDoesNotDependOnTheWritersManifestEncoding() { + ObjectNode reordered = JacksonUtil.newObjectNode(); + List keys = new ArrayList<>(); + validManifest().fieldNames().forEachRemaining(keys::add); + for (int i = keys.size() - 1; i >= 0; i--) { + reordered.set(keys.get(i), validManifest().get(keys.get(i))); + } + String reformatted = reordered.toPrettyString() + "\n"; + + assertThat(CommunityGrantOfflineBundle.parse(bundle(reformatted))) + .usingRecursiveComparison() + .isEqualTo(CommunityGrantOfflineBundle.parse(vector("01-valid.tbicb"))); + } + + @Test + void testAnUnknownManifestKeyIsIgnored() { + ObjectNode manifest = validManifest(); + manifest.put("supportRef", "abc"); + manifest.putObject("futureDetail").put("nested", 1); + manifest.putArray("futureList").add(1).add(2); + + assertThat(CommunityGrantOfflineBundle.parse(bundle(manifest))) + .usingRecursiveComparison() + .isEqualTo(CommunityGrantOfflineBundle.parse(vector("01-valid.tbicb"))); + } + + @Test + void testBothDeclaredLengthsAreReadAsUnsigned() { + byte[] manifest = JacksonUtil.toString(validManifest()).getBytes(StandardCharsets.UTF_8); + + assertThatThrownBy(() -> CommunityGrantOfflineBundle.parse( + frame((byte) 1, manifest.length, 0xFFFFFFFFL, relsig(), manifest, standInChecker()))) + .hasMessageContaining("4294967295") + .hasMessageNotContaining("-1"); + assertThatThrownBy(() -> CommunityGrantOfflineBundle.parse( + frame((byte) 1, 0xFFFFFFFFL, standInChecker().length, relsig(), manifest, standInChecker()))) + .hasMessageContaining("4294967295") + .hasMessageNotContaining("-1"); + } + + @Test + void testADeclaredLengthNeverSizesAnAllocation() { + byte[] manifest = {'{'}; + + assertThat(reasonOf(frame((byte) 1, 1, Integer.MAX_VALUE, relsig(), manifest, new byte[0]))) + .isEqualTo(Reason.LENGTH_MISMATCH); + } + + @Test + void testACorruptSignatureParsesAndIsHandedOnUnchanged() { + byte[] data = vector("15-relsig-not-tbicsig1.tbicb"); + + CommunityGrantOfflineBundle parsed = CommunityGrantOfflineBundle.parse(data); + + assertThat(parsed.signature()).hasSize(74).isEqualTo(Arrays.copyOfRange(data, 17, 91)); + assertThat(parsed.signature()).isNotEqualTo(relsig()); + } + + @Test + void testAnExpiredChallengeParsesAndReportsItselfOnlyAsAdvisory() { + CommunityGrantOfflineBundle parsed = CommunityGrantOfflineBundle.parse(vector("14-expired-challenge.tbicb")); + + assertThat(parsed.challengeExpiresAt()).isEqualTo(1609545600000L); + assertThat(parsed.isChallengeExpired(System.currentTimeMillis())).isTrue(); + assertThat(parsed.checkerInput()).isEqualTo(goldenCheckerInput()); + } + + @Test + void testTheExpiryBoundaryInstantIsStillLive() { + CommunityGrantOfflineBundle parsed = CommunityGrantOfflineBundle.parse(vector("01-valid.tbicb")); + + assertThat(parsed.isChallengeExpired(CHALLENGE_EXPIRES_AT - 1)).isFalse(); + assertThat(parsed.isChallengeExpired(CHALLENGE_EXPIRES_AT)).isFalse(); + assertThat(parsed.isChallengeExpired(CHALLENGE_EXPIRES_AT + 1)).isTrue(); + } + + @Test + void testTheGoldenBundleRoundTripsEveryValueItCarries() { + CommunityGrantOfflineBundle parsed = CommunityGrantOfflineBundle.parse(vector("01-valid.tbicb")); + + assertThat(parsed.os()).isEqualTo("linux"); + assertThat(parsed.arch()).isEqualTo("amd64"); + assertThat(parsed.clusterId()).isEqualTo(UUID.fromString(CLUSTER_ID)); + assertThat(parsed.checkerFileName()).isEqualTo(CHECKER_FILE_NAME); + assertThat(parsed.issuedAt()).isEqualTo(ISSUED_AT); + assertThat(parsed.challengeExpiresAt()).isEqualTo(CHALLENGE_EXPIRES_AT); + assertThat(parsed.checkerInput()).isEqualTo(goldenCheckerInput()); + assertThat(parsed.signature()).isEqualTo(relsig()); + assertThat(parsed.checker()).isEqualTo(standInChecker()); + assertThat(HexFormat.of().formatHex(sha256(parsed.checker()))).isEqualTo(CHECKER_SHA256); + } + + @Test + void testTheSynthesizedManifestIsTheOneTheVectorsRecord() { + JsonNode material = vectorsManifest().get("fixtureMaterial"); + + assertThat(JacksonUtil.toString(validManifest())).isEqualTo(material.get("validManifestJson").asText()); + assertThat(material.get("referenceMillis").asLong()).isEqualTo(REFERENCE_MILLIS); + } + + @Test + void testTheCheckerInputIsHandedOnUnreadAndCompact() { + ObjectNode checkerInput = validCheckerInput(); + checkerInput.put("keyId", 0); + checkerInput.put("publicKey", "not base64!!"); + checkerInput.remove("challenge"); + checkerInput.put("futureInput", true); + String manifestJson = JacksonUtil.toString(validManifest().set("checkerInput", checkerInput)) + .replace("\"futureInput\":", "\n \"futureInput\" : "); + + CommunityGrantOfflineBundle parsed = CommunityGrantOfflineBundle.parse(bundle(manifestJson)); + + assertThat(parsed.checkerInput().json()).isEqualTo("{\"clusterId\":\"" + CLUSTER_ID + "\",\"keyId\":0," + + "\"publicKey\":\"not base64!!\",\"referenceMillis\":" + REFERENCE_MILLIS + ",\"futureInput\":true}"); + } + + @Test + void testADuplicateKeyInsideTheCheckerInputIsRefusedByName() { + String manifestJson = JacksonUtil.toString(validManifest()) + .replace("\"referenceMillis\":", "\"keyId\":2,\"referenceMillis\":"); + + assertThat(reasonOf(bundle(manifestJson))).isEqualTo(Reason.MANIFEST_FIELD); + assertThatThrownBy(() -> CommunityGrantOfflineBundle.parse(bundle(manifestJson))) + .hasMessageContaining("keyId"); + } + + // The checker size cap is applied by CommunityGrantReportRunner to the extracted checker, not by the parser. + @Test + void testABundleLargerThanTheCheckerCapStillParses() { + byte[] oversized = new byte[33554433]; + Arrays.fill(oversized, (byte) 7); + byte[] manifest = JacksonUtil.toString(validManifest()).getBytes(StandardCharsets.UTF_8); + + CommunityGrantOfflineBundle parsed = CommunityGrantOfflineBundle.parse( + frame((byte) 1, manifest.length, oversized.length, relsig(), manifest, oversized)); + + assertThat(parsed.checker()).hasSize(oversized.length); + } + + @ParameterizedTest(name = "{0}") + @MethodSource("goldenVectors") + void testNoRefusalMessageIsUnsafeToPublish(String fileName, int sizeBytes, String sha256, String outcome) { + if (!"REJECT".equals(outcome)) { + return; + } + String message = messageOf(vector(fileName)); + + assertThat(message.toLowerCase()).doesNotContain("password", "secret", "token", "postgres://", "jdbc:"); + assertThat(message).doesNotContain(PORTAL_PUBLIC_KEY, CHALLENGE, CLUSTER_ID); + } + + @Test + void testTheExtractedMembersVerifyAgainstEachOtherThroughTheRealVerifier() { + CommunityGrantOfflineBundle parsed = CommunityGrantOfflineBundle.parse(vector("01-valid.tbicb")); + + assertThatCode(() -> verifierTrusting(CommunityGrantBundleFixtures.TRUSTS_RELEASE_KEY) + .verify(parsed.checker(), parsed.signature())).doesNotThrowAnyException(); + assertThatThrownBy(() -> verifierTrusting(CommunityGrantSigningFixtures.TRUSTS_A) + .verify(parsed.checker(), parsed.signature())) + .isInstanceOf(IllegalArgumentException.class); + } + + private static CommunityGrantReleaseSignatureVerifier verifierTrusting(String configured) { + CommunityGrantReleaseSignatureVerifier verifier = new CommunityGrantReleaseSignatureVerifier(); + ReflectionTestUtils.setField(verifier, "checkerReleasePublicKeys", configured); + verifier.init(); + return verifier; + } + + private static Stream goldenVectors() { + List vectors = new ArrayList<>(); + for (JsonNode fixture : vectorsManifest().get("fixtures")) { + vectors.add(Arguments.of(fixture.get("file").asText(), fixture.get("sizeBytes").asInt(), + fixture.get("sha256").asText(), fixture.get("expectedOutcome").asText(), + fixture.get("expectedReason").asText(null))); + } + return vectors.stream(); + } + + private static Stream manifestsBrokenOneRuleAtATime() { + List cases = new ArrayList<>(); + List keys = List.of("bundleVersion", "os", "arch", "clusterId", "checkerInput", + "challengeExpiresAt", "issuedAt", "checkerFileName"); + for (String key : keys) { + cases.add(Arguments.of(key + " missing", withoutKey(key), key)); + cases.add(Arguments.of(key + " of the wrong JSON type", withValue(key, + validManifest().get(key).isTextual() ? IntNode.valueOf(1) : TextNode.valueOf("x")), key)); + } + cases.add(Arguments.of("bundleVersion disagreeing with the version byte", withInt("bundleVersion", 2), "bundleVersion")); + cases.add(Arguments.of("an unknown os", withText("os", "solaris"), "os")); + cases.add(Arguments.of("an unknown arch", withText("arch", "riscv64"), "arch")); + cases.add(Arguments.of("a clusterId that is not a UUID", withText("clusterId", "not-a-uuid"), "clusterId")); + cases.add(Arguments.of("an uppercase clusterId", withText("clusterId", CLUSTER_ID.toUpperCase(Locale.ROOT)), "clusterId")); + cases.add(Arguments.of("an empty checkerInput", withValue("checkerInput", JacksonUtil.newObjectNode()), "checkerInput")); + cases.add(Arguments.of("a checkerInput that is an array", withValue("checkerInput", JacksonUtil.newArrayNode().add(1)), "checkerInput")); + cases.add(Arguments.of("a null checkerInput", withValue("checkerInput", NullNode.getInstance()), "checkerInput")); + cases.add(Arguments.of("challengeExpiresAt of zero", withLong("challengeExpiresAt", 0), "challengeExpiresAt")); + cases.add(Arguments.of("a negative challengeExpiresAt", withLong("challengeExpiresAt", -1), "challengeExpiresAt")); + cases.add(Arguments.of("issuedAt of zero", withLong("issuedAt", 0), "issuedAt")); + cases.add(Arguments.of("issuedAt after the expiry", withLong("issuedAt", CHALLENGE_EXPIRES_AT + 1), "issuedAt")); + cases.add(Arguments.of("an empty checkerFileName", withText("checkerFileName", ""), "checkerFileName")); + cases.add(Arguments.of("a checkerFileName over 255 characters", withText("checkerFileName", "x".repeat(256)), "checkerFileName")); + cases.add(Arguments.of("a checkerFileName carrying a path", withText("checkerFileName", "bin/tb-instance-check"), "checkerFileName")); + cases.add(Arguments.of("a checkerFileName carrying a windows path", withText("checkerFileName", "bin\\tb-instance-check"), "checkerFileName")); + cases.add(Arguments.of("a checkerFileName carrying a traversal", withText("checkerFileName", "../tb-instance-check"), "checkerFileName")); + return cases.stream(); + } + + private static JsonNode withoutKey(String key) { + ObjectNode manifest = validManifest(); + manifest.remove(key); + return manifest; + } + + private static JsonNode withValue(String key, JsonNode value) { + return validManifest().set(key, value); + } + + private static JsonNode withText(String key, String value) { + return validManifest().put(key, value); + } + + private static JsonNode withInt(String key, int value) { + return validManifest().put(key, value); + } + + private static JsonNode withLong(String key, long value) { + return validManifest().put(key, value); + } + + private static CommunityGrantCheckerInput goldenCheckerInput() { + return new CommunityGrantCheckerInput("{\"clusterId\":\"" + CLUSTER_ID + "\",\"keyId\":" + KEY_ID + + ",\"publicKey\":\"" + PORTAL_PUBLIC_KEY + "\",\"challenge\":\"" + CHALLENGE + + "\",\"referenceMillis\":" + REFERENCE_MILLIS + "}"); + } + + private static Reason reasonOf(byte[] data) { + try { + CommunityGrantOfflineBundle.parse(data); + } catch (CommunityGrantBundleFormatException e) { + return e.getReason(); + } + throw new AssertionError("Expected the bundle to be refused, but it parsed"); + } + + private static String messageOf(byte[] data) { + try { + CommunityGrantOfflineBundle.parse(data); + } catch (CommunityGrantBundleFormatException e) { + return e.getMessage(); + } + throw new AssertionError("Expected the bundle to be refused, but it parsed"); + } + + private static byte[] sha256(byte[] data) { + try { + return MessageDigest.getInstance("SHA-256").digest(data); + } catch (NoSuchAlgorithmException e) { + throw new IllegalStateException(e); + } + } + +} diff --git a/application/src/test/java/org/thingsboard/server/service/community_grant/CommunityGrantOfflineReportStoreTest.java b/application/src/test/java/org/thingsboard/server/service/community_grant/CommunityGrantOfflineReportStoreTest.java new file mode 100644 index 0000000000..2c93740015 --- /dev/null +++ b/application/src/test/java/org/thingsboard/server/service/community_grant/CommunityGrantOfflineReportStoreTest.java @@ -0,0 +1,216 @@ +// SPDX-FileCopyrightText: Copyright The Thingsboard Authors +// SPDX-License-Identifier: Apache-2.0 +package org.thingsboard.server.service.community_grant; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; +import org.mockito.junit.jupiter.MockitoSettings; +import org.mockito.quality.Strictness; +import org.thingsboard.server.common.data.AdminSettings; +import org.thingsboard.server.common.data.id.TenantId; +import org.thingsboard.server.dao.settings.AdminSettingsService; + +import java.util.concurrent.atomic.AtomicLong; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.when; + +@ExtendWith(MockitoExtension.class) +@MockitoSettings(strictness = Strictness.LENIENT) +class CommunityGrantOfflineReportStoreTest { + + private static final String REPORT = "-----BEGIN TB INSTANCE CHECK-----\nbody"; + + @Mock + private AdminSettingsService adminSettingsService; + + private CommunityGrantOfflineReportStore store; + + private AdminSettings stored; + + /** A counter, so two writes microseconds apart still get distinct instants. */ + private final AtomicLong clock = new AtomicLong(); + + @BeforeEach + void setUp() { + // Hands out a copy, so a save that threw cannot change what the next read sees. + when(adminSettingsService.findAdminSettingsByKey(TenantId.SYS_TENANT_ID, + CommunityGrantOfflineReportStore.SETTINGS_KEY)) + .thenAnswer(invocation -> stored == null ? null : new AdminSettings(stored)); + saveSucceeds(); + store = node(); + } + + /** A restart or a second cluster node over the same settings. */ + private CommunityGrantOfflineReportStore node() { + CommunityGrantOfflineReportStore node = new CommunityGrantOfflineReportStore(adminSettingsService); + node.setClock(clock::incrementAndGet); + return node; + } + + private void saveSucceeds() { + when(adminSettingsService.saveAdminSettings(eq(TenantId.SYS_TENANT_ID), any())) + .thenAnswer(invocation -> { + AdminSettings saved = invocation.getArgument(1); + return stored = new AdminSettings(saved); + }); + } + + private void saveFails() { + when(adminSettingsService.saveAdminSettings(eq(TenantId.SYS_TENANT_ID), any())) + .thenThrow(new IllegalStateException("connection refused")); + } + + @Test + void testNoReportIsStoredBeforeAnyRun() { + assertThat(store.get()).isEmpty(); + } + + @Test + void testAReportSurvivesTheNodeThatProducedIt() { + store.put(REPORT); + + assertThat(node().get()).contains(REPORT); + } + + @Test + void testANewRunReplacesThePreviousReport() { + store.put(REPORT); + store.put(REPORT + " (second run)"); + + assertThat(node().get()).contains(REPORT + " (second run)"); + } + + @Test + void testANewerReportFromAnotherNodeSupersedesThisNodesOwn() { + store.put(REPORT); + + node().put(REPORT + " (another node)"); + + assertThat(store.get()).contains(REPORT + " (another node)"); + } + + @Test + void testClearRemovesTheStoredReport() { + store.put(REPORT); + store.clear(); + + assertThat(store.get()).isEmpty(); + assertThat(node().get()).isEmpty(); + } + + @Test + void testAClearOnAnotherNodeRetiresTheCopyThisNodeProduced() { + store.put(REPORT); + + node().clear(); + + assertThat(store.get()).isEmpty(); + } + + @Test + void testAReportIsStillServedWhenTheDurableWriteFails() { + // An existing row, so the failed write is not hidden behind the empty-read fallback. + store.put(REPORT + " (earlier run)"); + saveFails(); + + store.put(REPORT); + + assertThat(store.get()).contains(REPORT); + } + + @Test + void testAReportIsStillServedWhenTheDurableWriteFailsAfterAClear() { + store.clear(); + saveFails(); + + store.put(REPORT); + + assertThat(store.get()).contains(REPORT); + } + + @Test + void testAFailedReadFallsBackToThisNodesOwnCopy() { + store.put(REPORT); + when(adminSettingsService.findAdminSettingsByKey(TenantId.SYS_TENANT_ID, + CommunityGrantOfflineReportStore.SETTINGS_KEY)) + .thenThrow(new IllegalStateException("connection refused")); + + assertThat(store.get()).contains(REPORT); + } + + @Test + void testAReportIsStillServedWhileTheDatabaseIsUnreachableAltogether() { + when(adminSettingsService.findAdminSettingsByKey(TenantId.SYS_TENANT_ID, + CommunityGrantOfflineReportStore.SETTINGS_KEY)) + .thenThrow(new IllegalStateException("connection refused")); + saveFails(); + + store.put(REPORT); + + assertThat(store.get()).contains(REPORT); + } + + @Test + void testAClearOnAnotherNodeAfterAFailedWriteRetiresTheCopy() { + saveFails(); + store.put(REPORT); + + saveSucceeds(); + node().clear(); + + assertThat(store.get()).isEmpty(); + } + + @Test + void testANewerReportFromAnotherNodeAfterAFailedWriteSupersedesTheCopy() { + saveFails(); + store.put(REPORT); + + saveSucceeds(); + node().put(REPORT + " (another node)"); + + assertThat(store.get()).contains(REPORT + " (another node)"); + } + + @Test + void testASupersededCopyIsNotRevivedByAnOutOfOrderWrite() { + saveFails(); + store.put(REPORT); + saveSucceeds(); + node().put(REPORT + " (another node)"); + assertThat(store.get()).contains(REPORT + " (another node)"); + + CommunityGrantOfflineReportStore nodeWithABehindClock = node(); + nodeWithABehindClock.setClock(() -> 0L); + nodeWithABehindClock.clear(); + + assertThat(store.get()).isEmpty(); + } + + @Test + void testAFailedClearDoesNotResurrectTheStoredReport() { + store.put(REPORT); + saveFails(); + + store.clear(); + + assertThat(store.get()).isEmpty(); + } + + @Test + void testAFailedReadWithNothingLocalPropagates() { + when(adminSettingsService.findAdminSettingsByKey(TenantId.SYS_TENANT_ID, + CommunityGrantOfflineReportStore.SETTINGS_KEY)) + .thenThrow(new IllegalStateException("connection refused")); + + assertThatThrownBy(() -> store.get()).isInstanceOf(IllegalStateException.class); + } + +} diff --git a/application/src/test/java/org/thingsboard/server/service/community_grant/CommunityGrantPlatformTest.java b/application/src/test/java/org/thingsboard/server/service/community_grant/CommunityGrantPlatformTest.java new file mode 100644 index 0000000000..ebde39b635 --- /dev/null +++ b/application/src/test/java/org/thingsboard/server/service/community_grant/CommunityGrantPlatformTest.java @@ -0,0 +1,59 @@ +// SPDX-FileCopyrightText: Copyright The Thingsboard Authors +// SPDX-License-Identifier: Apache-2.0 +package org.thingsboard.server.service.community_grant; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.CsvSource; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +class CommunityGrantPlatformTest { + + @ParameterizedTest + @CsvSource({ + "Mac OS X, aarch64, darwin, arm64", + "Mac OS X, x86_64, darwin, amd64", + "Windows 10, amd64, windows, amd64", + "Windows Server 2022, aarch64, windows, arm64", + "Linux, amd64, linux, amd64", + "Linux, x86_64, linux, amd64", + "Linux, aarch64, linux, arm64", + "SunOS, x64, linux, amd64" + }) + void testPlatformIsMappedToThePortalsVocabulary(String osName, String osArch, String os, String arch) { + assertThat(CommunityGrantPlatform.of(osName, osArch)).isEqualTo(new CommunityGrantPlatform(os, arch)); + } + + @ParameterizedTest + @CsvSource({"Linux, ppc64le", "Linux, s390x", "Linux, i386"}) + void testAnUnsupportedArchitectureIsRefused(String osName, String osArch) { + assertThatThrownBy(() -> CommunityGrantPlatform.of(osName, osArch)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("Unsupported architecture"); + } + + @Test + void testOnlyWindowsGetsAnExeSuffix() { + assertThat(new CommunityGrantPlatform("windows", "amd64").checkerFileName()).isEqualTo("tb-instance-check.exe"); + assertThat(new CommunityGrantPlatform("linux", "amd64").checkerFileName()).isEqualTo("tb-instance-check"); + assertThat(new CommunityGrantPlatform("darwin", "arm64").checkerFileName()).isEqualTo("tb-instance-check"); + } + + @Test + void testOnlyAFileNameNamingAnotherPlatformIsRefused() { + CommunityGrantPlatform platform = new CommunityGrantPlatform("linux", "amd64"); + + assertThat(platform.namesAnotherPlatform("tb-instance-check_windows_amd64")).isTrue(); + assertThat(platform.namesAnotherPlatform("tb-instance-check_linux_arm64")).isTrue(); + assertThat(platform.namesAnotherPlatform("TB-Instance-Check_Darwin_ARM64")).isTrue(); + assertThat(platform.namesAnotherPlatform("tb-instance-check")).isFalse(); + assertThat(platform.namesAnotherPlatform("tb-instance-check_linux_amd64")).isFalse(); + assertThat(platform.namesAnotherPlatform("tb-instance-check (1)")).isFalse(); + assertThat(platform.namesAnotherPlatform("tb-instance-check_solaris_sparc")).isFalse(); + assertThat(platform.namesAnotherPlatform(null)).isFalse(); + assertThat(platform.namesAnotherPlatform("")).isFalse(); + } + +} diff --git a/application/src/test/java/org/thingsboard/server/service/community_grant/CommunityGrantPollerTest.java b/application/src/test/java/org/thingsboard/server/service/community_grant/CommunityGrantPollerTest.java new file mode 100644 index 0000000000..f3f6bafa6f --- /dev/null +++ b/application/src/test/java/org/thingsboard/server/service/community_grant/CommunityGrantPollerTest.java @@ -0,0 +1,952 @@ +// SPDX-FileCopyrightText: Copyright The Thingsboard Authors +// SPDX-License-Identifier: Apache-2.0 +package org.thingsboard.server.service.community_grant; + +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; +import org.mockito.ArgumentCaptor; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; +import org.springframework.test.util.ReflectionTestUtils; +import org.thingsboard.common.util.JacksonUtil; +import org.thingsboard.server.common.data.community_grant.CommunityGrantFlowState; +import org.thingsboard.server.common.data.community_grant.CommunityGrantMode; +import org.thingsboard.server.common.data.community_grant.CommunityGrantParkReason; +import org.thingsboard.server.common.data.community_grant.CommunityGrantState; +import org.thingsboard.server.common.data.id.TenantId; +import org.thingsboard.server.common.msg.queue.ServiceType; +import org.thingsboard.server.common.msg.queue.TopicPartitionInfo; +import org.thingsboard.server.dao.subscription.TbClusterStore; +import org.thingsboard.server.queue.discovery.PartitionService; +import org.thingsboard.server.queue.discovery.event.PartitionChangeEvent; + +import java.util.Map; +import java.util.Optional; +import java.util.UUID; +import java.util.concurrent.RejectedExecutionException; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.ScheduledFuture; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.function.UnaryOperator; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyLong; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.clearInvocations; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.lenient; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +@ExtendWith(MockitoExtension.class) +class CommunityGrantPollerTest { + + private static final String TOKEN = "token-one"; + private static final String SIGN_UP_URL = + "https://portal.example/communityGrant?clusterId=c1&claimToken=t1"; + private static final UUID CLUSTER_ID = UUID.fromString("2f0a5b1e-1111-4a2b-9c3d-4e5f60718293"); + private static final String CHECKER_INPUT_JSON = "{\"clusterId\":\"" + CLUSTER_ID + "\",\"keyId\":7," + + "\"publicKey\":\"cHVi\",\"challenge\":\"Y2hh\",\"referenceMillis\":1787788800000}"; + private static final CommunityGrantCheckerInput CHECKER_INPUT = new CommunityGrantCheckerInput(CHECKER_INPUT_JSON); + + @Mock + private PartitionService partitionService; + @Mock + private TbClusterStore tbClusterStore; + @Mock + private CommunityGrantFlowStateStore flowStateStore; + @Mock + private CommunityGrantPortalClient portalClient; + @Mock + private CommunityGrantReportRunner reportRunner; + + /** Keeps real background ticks away from the mocks, and lets the reschedule be asserted. */ + @Mock + private ScheduledExecutorService scheduler; + @Mock + private ScheduledFuture scheduledPoll; + @Mock + private ScheduledFuture supervisorFuture; + + @InjectMocks + private CommunityGrantPoller poller; + + private CommunityGrantFlowState stored; + + @BeforeEach + void setUp() { + // Without enabled, init() returns before arming. + ReflectionTestUtils.setField(poller, "enabled", true); + ReflectionTestUtils.setField(poller, "fastPollIntervalMs", 3000L); + ReflectionTestUtils.setField(poller, "fastPollWindowMs", 120000L); + ReflectionTestUtils.setField(poller, "slowPollIntervalMs", 30000L); + ReflectionTestUtils.setField(poller, "signUpDeadlineMs", 86400000L); + ReflectionTestUtils.setField(poller, "superviseIntervalMs", 30000L); + ReflectionTestUtils.setField(poller, "scheduler", scheduler); + stored = CommunityGrantFlowState.initial(); + stored.setMode(CommunityGrantMode.ONLINE); + stored.setState(CommunityGrantState.AWAITING_SIGNUP); + stored.setStartedAt(System.currentTimeMillis()); + lenient().when(flowStateStore.get()).thenAnswer(invocation -> stored); + lenient().when(flowStateStore.update(any())).thenAnswer(invocation -> { + UnaryOperator updater = invocation.getArgument(0); + stored = updater.apply(stored); + return stored; + }); + lenient().when(tbClusterStore.getLicenseClaimToken()).thenReturn(Optional.of(TOKEN)); + lenient().when(tbClusterStore.getClusterId()).thenReturn(Optional.of(CLUSTER_ID)); + lenient().doReturn(scheduledPoll).when(scheduler).schedule(any(Runnable.class), anyLong(), any()); + // Non-null, so the supervisor's already-running guard can trip. + lenient().doReturn(supervisorFuture).when(scheduler) + .scheduleWithFixedDelay(any(), anyLong(), anyLong(), any()); + ownsSystemTenantPartition(true); + poller.arm(); + } + + @AfterEach + void tearDown() { + poller.stop(); + } + + @Test + void testAwaitingSignupIsProjected() { + poller.apply(TOKEN, status("AWAITING_SIGNUP", null)); + assertThat(stored.getState()).isEqualTo(CommunityGrantState.AWAITING_SIGNUP); + verify(tbClusterStore, never()).clearLicenseClaimToken(anyString()); + } + + @Test + void testAwaitingSignupPastTheDeadlineParksTheFlow() { + stored.setStartedAt(System.currentTimeMillis() - 86400000L - 1000L); + + poller.apply(TOKEN, status("AWAITING_SIGNUP", null)); + + assertThat(stored.getState()).isEqualTo(CommunityGrantState.RESUME); + assertThat(stored.getSignUpUrl()).isNull(); + assertThat(stored.getParkReason()).isEqualTo(CommunityGrantParkReason.SIGNUP_ABANDONED); + assertThat(poller.isArmed()).isFalse(); + verify(tbClusterStore).clearLicenseClaimToken(TOKEN); + } + + @Test + void testVerificationRequiredRunsTheReportWithThePortalsInput() { + when(reportRunner.runAndUpload(TOKEN, CHECKER_INPUT)).thenReturn("UNDER_REVIEW"); + + poller.apply(TOKEN, verificationRequired()); + + verify(reportRunner).runAndUpload(TOKEN, CHECKER_INPUT); + assertThat(stored.getState()).isEqualTo(CommunityGrantState.UNDER_REVIEW); + } + + @Test + void testVerificationRequiredUploadThatIsAcceptedOutrightIsTerminal() { + when(reportRunner.runAndUpload(TOKEN, CHECKER_INPUT)).thenReturn("DONE"); + + poller.apply(TOKEN, verificationRequired()); + + assertThat(stored.getState()).isEqualTo(CommunityGrantState.REGISTERED); + verify(tbClusterStore).clearLicenseClaimToken(TOKEN); + } + + @Test + void testVerificationRequiredUploadUnderReviewKeepsTheTokenAndKeepsWatching() { + when(reportRunner.runAndUpload(TOKEN, CHECKER_INPUT)).thenReturn("UNDER_REVIEW"); + + poller.apply(TOKEN, verificationRequired()); + + assertThat(stored.getState()).isEqualTo(CommunityGrantState.UNDER_REVIEW); + assertThat(poller.isArmed()).isTrue(); + verify(tbClusterStore, never()).clearLicenseClaimToken(anyString()); + } + + @Test + void testVerificationRequiredUploadWrongInstallationIsTerminal() { + when(reportRunner.runAndUpload(TOKEN, CHECKER_INPUT)).thenReturn("WRONG_INSTALLATION"); + + poller.apply(TOKEN, verificationRequired()); + + assertThat(stored.getState()).isEqualTo(CommunityGrantState.WRONG_INSTALLATION); + verify(tbClusterStore).clearLicenseClaimToken(TOKEN); + } + + @Test + void testVerificationRequiredUploadWithAnUnknownStatusLeavesTheFlowCollecting() { + when(reportRunner.runAndUpload(TOKEN, CHECKER_INPUT)).thenReturn("SOMETHING_NEW"); + + poller.apply(TOKEN, verificationRequired()); + + assertThat(stored.getState()).isEqualTo(CommunityGrantState.COLLECTING); + verify(tbClusterStore, never()).clearLicenseClaimToken(anyString()); + } + + @Test + void testVerificationRequiredUploadReturningNullLeavesTheFlowCollecting() { + when(reportRunner.runAndUpload(TOKEN, CHECKER_INPUT)).thenReturn(null); + + poller.apply(TOKEN, verificationRequired()); + + assertThat(stored.getState()).isEqualTo(CommunityGrantState.COLLECTING); + verify(tbClusterStore, never()).clearLicenseClaimToken(anyString()); + } + + // Refused before the runner, so a status that was never runnable does not spend the verification budget. + @ParameterizedTest + @ValueSource(strings = {"", "null", "{}", "[]", "\"text\"", "7"}) + void testVerificationRequiredWithoutAUsableInputNeverRunsTheChecker(String checkerInput) { + AtomicInteger verificationFailures = + (AtomicInteger) ReflectionTestUtils.getField(poller, "verificationFailures"); + + poller.apply(TOKEN, new CommunityGrantPortalStatus("VERIFICATION_REQUIRED", + checkerInput.isEmpty() ? null : JacksonUtil.toJsonNode(checkerInput), null)); + + verifyNoInteractions(reportRunner); + assertThat(stored.getState()).isEqualTo(CommunityGrantState.COLLECTING); + assertThat(verificationFailures).hasValue(0); + } + + @Test + void testVerificationRequiredInOfflineModeNeverRunsTheChecker() { + stored.setMode(CommunityGrantMode.OFFLINE); + + poller.apply(TOKEN, verificationRequired()); + + verifyNoInteractions(reportRunner); + assertThat(stored.getState()).isEqualTo(CommunityGrantState.COLLECTING); + } + + @Test + void testAFailedReportRunLeavesTheFlowCollecting() { + when(reportRunner.runAndUpload(TOKEN, CHECKER_INPUT)).thenThrow(new IllegalStateException("boom")); + + poller.apply(TOKEN, verificationRequired()); + + assertThat(stored.getState()).isEqualTo(CommunityGrantState.COLLECTING); + verify(tbClusterStore, never()).clearLicenseClaimToken(anyString()); + } + + @Test + void testRepeatedReportFailuresParkTheFlow() { + when(reportRunner.runAndUpload(TOKEN, CHECKER_INPUT)).thenThrow(new IllegalStateException("boom")); + + for (int i = 0; i < CommunityGrantPoller.MAX_VERIFICATION_FAILURES; i++) { + poller.apply(TOKEN, verificationRequired()); + } + + assertThat(stored.getState()).isEqualTo(CommunityGrantState.RESUME); + assertThat(stored.getParkReason()).isEqualTo(CommunityGrantParkReason.CHECK_FAILED); + assertThat(poller.isArmed()).isFalse(); + verify(tbClusterStore).clearLicenseClaimToken(TOKEN); + } + + // Only the state write is skipped; lastPolledAt still advances so the flow does not look stalled. + @Test + void testVerificationRequiredLeavesAHandedOverFlowClaimedButKeepsItsPollFresh() { + stored.setState(CommunityGrantState.REPORT_HANDED_OVER); + stored.setLastPolledAt(1L); + + poller.apply(TOKEN, verificationRequired()); + + assertThat(stored.getState()).isEqualTo(CommunityGrantState.REPORT_HANDED_OVER); + assertThat(stored.getLastPolledAt()).isGreaterThan(1L); + verify(reportRunner).runAndUpload(TOKEN, CHECKER_INPUT); + } + + @Test + void testRepeatedReportFailuresDoNotParkAHandedOverFlow() { + stored.setState(CommunityGrantState.REPORT_HANDED_OVER); + when(reportRunner.runAndUpload(TOKEN, CHECKER_INPUT)).thenThrow(new IllegalStateException("boom")); + + for (int i = 0; i < CommunityGrantPoller.MAX_VERIFICATION_FAILURES; i++) { + poller.apply(TOKEN, verificationRequired()); + } + + assertThat(stored.getState()).isEqualTo(CommunityGrantState.REPORT_HANDED_OVER); + assertThat(stored.getParkReason()).isNull(); + assertThat(poller.isArmed()).isTrue(); + verify(tbClusterStore, never()).clearLicenseClaimToken(anyString()); + } + + @Test + void testVerificationRequiredLeavesAValidatingFlowClaimedButKeepsItsPollFresh() { + stored.setState(CommunityGrantState.VALIDATING); + stored.setLastPolledAt(1L); + + poller.apply(TOKEN, verificationRequired()); + + assertThat(stored.getState()).isEqualTo(CommunityGrantState.VALIDATING); + assertThat(stored.getLastPolledAt()).isGreaterThan(1L); + } + + @Test + void testVerificationRequiredNeverRunsTheCheckerForAValidatingFlow() { + stored.setState(CommunityGrantState.VALIDATING); + + for (int i = 0; i < CommunityGrantPoller.MAX_VERIFICATION_FAILURES; i++) { + poller.apply(TOKEN, verificationRequired()); + } + + verifyNoInteractions(reportRunner); + assertThat(stored.getState()).isEqualTo(CommunityGrantState.VALIDATING); + assertThat(stored.getParkReason()).isNull(); + assertThat(poller.isArmed()).isTrue(); + verify(tbClusterStore, never()).clearLicenseClaimToken(anyString()); + } + + @Test + void testAValidatingAnswerIsTreatedAsUnrecognizedAndChangesNothing() { + poller.apply(TOKEN, status("VALIDATING", null)); + + assertThat(stored.getState()).isEqualTo(CommunityGrantState.AWAITING_SIGNUP); + verify(tbClusterStore, never()).clearLicenseClaimToken(anyString()); + } + + @Test + void testDoneIsTerminalAndRetiresTheToken() { + poller.apply(TOKEN, status("DONE", null)); + assertThat(stored.getState()).isEqualTo(CommunityGrantState.REGISTERED); + verify(tbClusterStore).clearLicenseClaimToken(TOKEN); + } + + @Test + void testDoneKeepsTheRegistrationLinkWhileRetiringEverythingElseAboutTheClaim() { + stored.setSignUpUrl(SIGN_UP_URL); + + poller.apply(TOKEN, status("DONE", null)); + + assertThat(stored.getState()).isEqualTo(CommunityGrantState.REGISTERED); + assertThat(stored.getSignUpUrl()).isEqualTo(SIGN_UP_URL); + assertThat(stored.getStartedAt()).isNull(); + verify(tbClusterStore).clearLicenseClaimToken(TOKEN); + } + + @Test + void testAWrongInstallationAnswerDropsTheRegistrationLink() { + stored.setSignUpUrl(SIGN_UP_URL); + + poller.apply(TOKEN, status("WRONG_INSTALLATION", null)); + + assertThat(stored.getState()).isEqualTo(CommunityGrantState.WRONG_INSTALLATION); + assertThat(stored.getSignUpUrl()).isNull(); + } + + @Test + void testAParkDropsTheRegistrationLink() { + stored.setSignUpUrl(SIGN_UP_URL); + + poller.apply(TOKEN, status("EXPIRED", null)); + + assertThat(stored.getState()).isEqualTo(CommunityGrantState.RESUME); + assertThat(stored.getSignUpUrl()).isNull(); + } + + @Test + void testUnderReviewKeepsTheTokenAndKeepsWatching() { + poller.apply(TOKEN, status("UNDER_REVIEW", 30)); + + assertThat(stored.getState()).isEqualTo(CommunityGrantState.UNDER_REVIEW); + assertThat(stored.getLastPolledAt()).isNotNull(); + assertThat(poller.isArmed()).isTrue(); + verify(tbClusterStore, never()).clearLicenseClaimToken(anyString()); + } + + @Test + void testUnderReviewFollowedByDoneEndsRegistered() { + poller.apply(TOKEN, status("UNDER_REVIEW", 30)); + assertThat(stored.getState()).isEqualTo(CommunityGrantState.UNDER_REVIEW); + + poller.apply(TOKEN, status("DONE", null)); + + assertThat(stored.getState()).isEqualTo(CommunityGrantState.REGISTERED); + assertThat(poller.isArmed()).isFalse(); + verify(tbClusterStore).clearLicenseClaimToken(TOKEN); + } + + @Test + void testUnderReviewIsPacedByThePortalsRetryAfter() { + when(portalClient.getStatus(TOKEN, CLUSTER_ID)).thenReturn(status("UNDER_REVIEW", 300)); + + assertThat(poller.nextDelay(poller.poll())).isEqualTo(TimeUnit.SECONDS.toMillis(300)); + } + + @Test + void testAnUnderReviewAnswerForAClearedTokenIsNotWritten() { + when(tbClusterStore.getLicenseClaimToken()).thenReturn(Optional.empty()); + + poller.apply(TOKEN, status("UNDER_REVIEW", 30)); + + assertThat(stored.getState()).isEqualTo(CommunityGrantState.AWAITING_SIGNUP); + } + + @Test + void testAwaitingSignupAndVerificationRequiredAreAlsoSkippedForAReplacedToken() { + when(tbClusterStore.getLicenseClaimToken()).thenReturn(Optional.of("a-newer-token")); + stored.setState(CommunityGrantState.NOT_STARTED); + + poller.apply(TOKEN, status("AWAITING_SIGNUP", null)); + assertThat(stored.getState()).isEqualTo(CommunityGrantState.NOT_STARTED); + + poller.apply(TOKEN, verificationRequired()); + assertThat(stored.getState()).isEqualTo(CommunityGrantState.NOT_STARTED); + assertThat(stored.getLastPolledAt()).isNull(); + verifyNoInteractions(reportRunner); + } + + @Test + void testWrongInstallationIsTerminalAndRetiresTheToken() { + poller.apply(TOKEN, status("WRONG_INSTALLATION", null)); + assertThat(stored.getState()).isEqualTo(CommunityGrantState.WRONG_INSTALLATION); + assertThat(stored.getParkReason()).isNull(); + verify(tbClusterStore).clearLicenseClaimToken(TOKEN); + } + + @Test + void testExpiredParksTheFlowForARestart() { + poller.apply(TOKEN, status("EXPIRED", null)); + assertThat(stored.getState()).isEqualTo(CommunityGrantState.RESUME); + assertThat(stored.getSignUpUrl()).isNull(); + assertThat(stored.getParkReason()).isEqualTo(CommunityGrantParkReason.LINK_EXPIRED); + verify(tbClusterStore).clearLicenseClaimToken(TOKEN); + } + + @Test + void testAnAnswerForASupersededTokenLeavesTheStateAndTheLoopAlone() { + when(tbClusterStore.getLicenseClaimToken()).thenReturn(Optional.of("token-two")); + + poller.apply(TOKEN, status("DONE", null)); + + assertThat(stored.getState()).isEqualTo(CommunityGrantState.AWAITING_SIGNUP); + assertThat(poller.isArmed()).isTrue(); + verify(tbClusterStore, never()).clearLicenseClaimToken(anyString()); + } + + @Test + void testAnUnknownStatusLeavesTheStateAlone() { + poller.apply(TOKEN, status("SOMETHING_NEW", null)); + assertThat(stored.getState()).isEqualTo(CommunityGrantState.AWAITING_SIGNUP); + verify(tbClusterStore, never()).clearLicenseClaimToken(anyString()); + } + + @Test + void testApplyWithANullStatusValueLeavesStateAloneAndDoesNotThrow() { + poller.apply(TOKEN, status(null, null)); + assertThat(stored.getState()).isEqualTo(CommunityGrantState.AWAITING_SIGNUP); + verify(tbClusterStore, never()).clearLicenseClaimToken(anyString()); + } + + @Test + void testTerminalStateAlsoClearsStartedAt() { + poller.apply(TOKEN, status("DONE", null)); + assertThat(stored.getStartedAt()).isNull(); + } + + @Test + void testTerminalStateStopsAllFurtherOutboundCalls() { + poller.apply(TOKEN, status("DONE", null)); + + assertThat(poller.poll()).isNull(); + + verify(portalClient, never()).getStatus(anyString(), any()); + } + + @Test + void testPollWithoutATokenDisarms() { + when(tbClusterStore.getLicenseClaimToken()).thenReturn(Optional.empty()); + + poller.poll(); + + verify(portalClient, never()).getStatus(anyString(), any()); + assertThat(poller.isArmed()).isFalse(); + } + + @Test + void testPollWithoutAClusterIdDisarms() { + when(tbClusterStore.getClusterId()).thenReturn(Optional.empty()); + + poller.poll(); + + verify(portalClient, never()).getStatus(anyString(), any()); + assertThat(poller.isArmed()).isFalse(); + } + + // The loop stays armed because its tick enforces the sign-up deadline. + @Test + void testPollSkipsThePortalButKeepsTheLoopWhenTheModeHasSinceBecomeOffline() { + assertThat(poller.isArmed()).isTrue(); + stored.setMode(CommunityGrantMode.OFFLINE); + + assertThat(poller.poll()).isNull(); + + verify(portalClient, never()).getStatus(anyString(), any()); + assertThat(poller.isArmed()).isTrue(); + } + + @Test + void testAnOfflineEnrollmentIsParkedAtTheSignUpDeadlineWithoutEverCallingThePortal() { + stored.setMode(CommunityGrantMode.OFFLINE); + stored.setStartedAt(System.currentTimeMillis() - 86400000L - 1000L); + + assertThat(poller.poll()).isNull(); + + verify(portalClient, never()).getStatus(anyString(), any()); + assertThat(stored.getState()).isEqualTo(CommunityGrantState.RESUME); + assertThat(stored.getParkReason()).isEqualTo(CommunityGrantParkReason.SIGNUP_ABANDONED); + verify(tbClusterStore).clearLicenseClaimToken(TOKEN); + assertThat(poller.isArmed()).isFalse(); + } + + @Test + void testAnOfflineTickInsideTheDeadlineTouchesNothing() { + stored.setMode(CommunityGrantMode.OFFLINE); + + assertThat(poller.poll()).isNull(); + + verify(portalClient, never()).getStatus(anyString(), any()); + verify(flowStateStore, never()).update(any()); + assertThat(stored.getState()).isEqualTo(CommunityGrantState.AWAITING_SIGNUP); + } + + @Test + void testAnOfflineFlowPastTheSignUpFormStopsTheLoop() { + assertThat(poller.isArmed()).isTrue(); + stored.setMode(CommunityGrantMode.OFFLINE); + stored.setState(CommunityGrantState.VALIDATING); + + assertThat(poller.poll()).isNull(); + + verify(portalClient, never()).getStatus(anyString(), any()); + verify(flowStateStore, never()).update(any()); + assertThat(poller.isArmed()).isFalse(); + } + + @Test + void testPollRecordsTheTimestampAndThrottlesTheNextCall() { + when(portalClient.getStatus(TOKEN, CLUSTER_ID)) + .thenReturn(status("AWAITING_SIGNUP", null)); + + poller.poll(); + assertThat(stored.getLastPolledAt()).isNotNull(); + + poller.poll(); + verify(portalClient).getStatus(TOKEN, CLUSTER_ID); + } + + @Test + void testPollWithANullPortalResponseLeavesStateUnchanged() { + when(portalClient.getStatus(TOKEN, CLUSTER_ID)).thenReturn(null); + + assertThat(poller.poll()).isNull(); + + assertThat(stored.getState()).isEqualTo(CommunityGrantState.AWAITING_SIGNUP); + } + + // The armed flag is untouched on this path, so the reschedule is what is asserted. + @Test + void testPortalThrowingDuringAPollDoesNotKillTheScheduledLoop() { + when(portalClient.getStatus(TOKEN, CLUSTER_ID)).thenThrow(new RuntimeException("portal unreachable")); + clearInvocations(scheduler); + + poller.pollAndReschedule(); + + assertThat(poller.isArmed()).isTrue(); + verify(scheduler).schedule(any(Runnable.class), eq(3000L), eq(TimeUnit.MILLISECONDS)); + } + + @Test + void testFlowStateStoreThrowingDuringAPollDoesNotKillTheScheduledLoop() { + when(portalClient.getStatus(TOKEN, CLUSTER_ID)) + .thenReturn(status("AWAITING_SIGNUP", null)); + doThrow(new IllegalStateException("unparseable stored document")).when(flowStateStore).update(any()); + clearInvocations(scheduler); + + poller.pollAndReschedule(); + + assertThat(poller.isArmed()).isTrue(); + verify(scheduler).schedule(any(Runnable.class), eq(3000L), eq(TimeUnit.MILLISECONDS)); + } + + @Test + void testTheFailureCountIsClearedOnlyByAPollThatReachedThePortal() { + AtomicInteger consecutiveFailures = + (AtomicInteger) ReflectionTestUtils.getField(poller, "consecutiveFailures"); + consecutiveFailures.set(4); + + // No claim token, so poll() returns before the portal. + when(tbClusterStore.getLicenseClaimToken()).thenReturn(Optional.empty()); + poller.pollAndReschedule(); + + assertThat(consecutiveFailures).hasValue(4); + verify(portalClient, never()).getStatus(anyString(), any()); + + // arm() clears the count too, so it is planted again after. + when(tbClusterStore.getLicenseClaimToken()).thenReturn(Optional.of(TOKEN)); + when(portalClient.getStatus(TOKEN, CLUSTER_ID)) + .thenReturn(status("AWAITING_SIGNUP", null)); + poller.arm(); + consecutiveFailures.set(4); + ReflectionTestUtils.setField(poller, "lastPollTs", 0L); + poller.pollAndReschedule(); + + assertThat(consecutiveFailures).hasValue(0); + } + + // Re-based in poll(), not arm(): the partition owner is not necessarily the node that served start(). + @Test + void testANewClaimTokenReBasesTheFailureBudgets() { + AtomicInteger consecutiveFailures = + (AtomicInteger) ReflectionTestUtils.getField(poller, "consecutiveFailures"); + AtomicInteger verificationFailures = + (AtomicInteger) ReflectionTestUtils.getField(poller, "verificationFailures"); + // Binds the poller to TOKEN and closes the throttle, so the next poll never reaches the portal. + poller.poll(); + consecutiveFailures.set(CommunityGrantPoller.MAX_POLL_FAILURES - 1); + verificationFailures.set(CommunityGrantPoller.MAX_VERIFICATION_FAILURES - 1); + when(tbClusterStore.getLicenseClaimToken()).thenReturn(Optional.of("token-two")); + + poller.poll(); + + assertThat(consecutiveFailures).hasValue(0); + assertThat(verificationFailures).hasValue(0); + } + + @Test + void testTheFirstClaimTokenANodeMeetsLeavesTheBudgetsAlone() { + AtomicInteger consecutiveFailures = + (AtomicInteger) ReflectionTestUtils.getField(poller, "consecutiveFailures"); + AtomicInteger verificationFailures = + (AtomicInteger) ReflectionTestUtils.getField(poller, "verificationFailures"); + consecutiveFailures.set(CommunityGrantPoller.MAX_POLL_FAILURES - 1); + verificationFailures.set(CommunityGrantPoller.MAX_VERIFICATION_FAILURES - 1); + // Closes the throttle, so the poll stops after the re-base. + ReflectionTestUtils.setField(poller, "lastPollTs", System.currentTimeMillis()); + + poller.poll(); + + assertThat(consecutiveFailures).hasValue(CommunityGrantPoller.MAX_POLL_FAILURES - 1); + assertThat(verificationFailures).hasValue(CommunityGrantPoller.MAX_VERIFICATION_FAILURES - 1); + } + + @Test + void testCadenceSwitchesFromFastToSlow() { + assertThat(poller.nextDelay(null)).isEqualTo(3000L); + ReflectionTestUtils.setField(poller, "pollingSince", System.currentTimeMillis() - 130000L); + assertThat(poller.nextDelay(null)).isEqualTo(30000L); + } + + @Test + void testRetryAfterSecOverridesBothIntervals() { + assertThat(poller.nextDelay(45)).isEqualTo(45000L); + ReflectionTestUtils.setField(poller, "pollingSince", System.currentTimeMillis() - 130000L); + assertThat(poller.nextDelay(1)).isEqualTo(1000L); + assertThat(poller.nextDelay(0)).isEqualTo(30000L); + } + + @Test + void testNegativeRetryAfterSecFallsBackToTheLocalCadence() { + assertThat(poller.nextDelay(-5)).isEqualTo(3000L); + } + + @Test + void testRetryAfterSecIsClampedToAnUpperBound() { + assertThat(poller.nextDelay(Integer.MAX_VALUE)).isEqualTo(CommunityGrantPoller.MAX_RETRY_AFTER_SEC * 1000L); + } + + @Test + void testAnUnreachablePortalStillEndsAnAbandonedSignUpAtTheDeadline() { + when(portalClient.getStatus(TOKEN, CLUSTER_ID)).thenThrow(new RuntimeException("portal unreachable")); + stored.setStartedAt(System.currentTimeMillis() - 86400000L - 1000L); + + poller.pollAndReschedule(); + + assertThat(stored.getState()).isEqualTo(CommunityGrantState.RESUME); + assertThat(stored.getParkReason()).isEqualTo(CommunityGrantParkReason.SIGNUP_ABANDONED); + verify(tbClusterStore).clearLicenseClaimToken(TOKEN); + } + + @Test + void testAnUnreachablePortalParksTheFlowOnceTheFailureBudgetIsSpent() { + when(portalClient.getStatus(TOKEN, CLUSTER_ID)).thenThrow(new RuntimeException("portal unreachable")); + stored.setState(CommunityGrantState.UNDER_REVIEW); + AtomicInteger consecutiveFailures = + (AtomicInteger) ReflectionTestUtils.getField(poller, "consecutiveFailures"); + consecutiveFailures.set(CommunityGrantPoller.MAX_POLL_FAILURES - 1); + ReflectionTestUtils.setField(poller, "lastPollTs", 0L); + + poller.pollAndReschedule(); + + assertThat(stored.getState()).isEqualTo(CommunityGrantState.RESUME); + assertThat(stored.getParkReason()).isEqualTo(CommunityGrantParkReason.PORTAL_UNREACHABLE); + verify(tbClusterStore).clearLicenseClaimToken(TOKEN); + assertThat(poller.isArmed()).isFalse(); + } + + @Test + void testAFailureBelowTheBudgetLeavesTheFlowAlone() { + when(portalClient.getStatus(TOKEN, CLUSTER_ID)).thenThrow(new RuntimeException("portal unreachable")); + stored.setState(CommunityGrantState.UNDER_REVIEW); + + poller.pollAndReschedule(); + + assertThat(stored.getState()).isEqualTo(CommunityGrantState.UNDER_REVIEW); + verify(tbClusterStore, never()).clearLicenseClaimToken(anyString()); + } + + @Test + void testTheDelayGrowsWithConsecutiveFailuresUpToACap() { + assertThat(poller.failureDelay(1)).isEqualTo(3000L); + assertThat(poller.failureDelay(3)).isEqualTo(12000L); + assertThat(poller.failureDelay(30)).isEqualTo(CommunityGrantPoller.MAX_FAILURE_BACKOFF_MS); + } + + @Test + void testInitArmsOnlyFromAPollableStoredState() { + poller.disarm(); + stored.setState(CommunityGrantState.NOT_STARTED); + poller.init(); + assertThat(poller.isArmed()).isFalse(); + + stored.setState(CommunityGrantState.VALIDATING); + poller.init(); + assertThat(poller.isArmed()).isTrue(); + } + + @Test + void testInitDoesNotArmFromATerminalState() { + poller.disarm(); + stored.setState(CommunityGrantState.REGISTERED); + poller.init(); + assertThat(poller.isArmed()).isFalse(); + verify(reportRunner, never()).runAndUpload(anyString(), any()); + verify(portalClient, never()).getStatus(eq(TOKEN), any()); + } + + @Test + void testInitDoesNotResumeOnANodeThatDoesNotOwnTheSystemTenantPartition() { + poller.disarm(); + stored.setState(CommunityGrantState.VALIDATING); + ownsSystemTenantPartition(false); + + poller.init(); + + assertThat(poller.isArmed()).isFalse(); + } + + @Test + void testTakingOverTheSystemTenantPartitionResumesAPollableFlow() { + poller.disarm(); + stored.setState(CommunityGrantState.VALIDATING); + + poller.onTbApplicationEvent(corePartitionChangeEvent()); + + assertThat(poller.isArmed()).isTrue(); + } + + @Test + void testLosingTheSystemTenantPartitionStopsTheLoop() { + ownsSystemTenantPartition(false); + + poller.onTbApplicationEvent(corePartitionChangeEvent()); + + assertThat(poller.isArmed()).isFalse(); + } + + @Test + void testArmDoesNothingWhenDisabled() { + poller.disarm(); + ReflectionTestUtils.setField(poller, "enabled", false); + + poller.arm(); + + assertThat(poller.isArmed()).isFalse(); + } + + @Test + void testAnOfflineDeploymentArmsSoItsDeadlineIsStillEnforced() { + poller.disarm(); + stored.setMode(CommunityGrantMode.OFFLINE); + + poller.arm(); + + assertThat(poller.isArmed()).isTrue(); + } + + @Test + void testInitArmsAnOfflineDeploymentStillWaitingOnTheSignUpForm() { + poller.disarm(); + stored.setMode(CommunityGrantMode.OFFLINE); + stored.setState(CommunityGrantState.AWAITING_SIGNUP); + + poller.init(); + + assertThat(poller.isArmed()).isTrue(); + } + + @Test + void testInitLeavesAnOfflineDeploymentPastTheSignUpFormDisarmed() { + poller.disarm(); + stored.setMode(CommunityGrantMode.OFFLINE); + stored.setState(CommunityGrantState.VALIDATING); + + poller.init(); + + assertThat(poller.isArmed()).isFalse(); + } + + @Test + void testInitArmsAnOnlineDeploymentAndItsPollReachesThePortal() { + poller.disarm(); + stored.setMode(CommunityGrantMode.ONLINE); + when(portalClient.getStatus(TOKEN, CLUSTER_ID)) + .thenReturn(status("AWAITING_SIGNUP", null)); + + poller.init(); + assertThat(poller.isArmed()).isTrue(); + + poller.poll(); + verify(portalClient).getStatus(TOKEN, CLUSTER_ID); + } + + @Test + void testArmDoesNothingOnANodeThatDoesNotOwnTheSystemTenantPartition() { + poller.disarm(); + clearInvocations(scheduler); // setUp() armed this node while it did own the partition + ownsSystemTenantPartition(false); + + poller.arm(); + + assertThat(poller.isArmed()).isFalse(); + verify(scheduler, never()).schedule(any(Runnable.class), anyLong(), any()); + } + + @Test + void testTheOwnersSupervisorPicksUpAFlowBegunOnAnotherNode() { + poller.disarm(); + stored.setState(CommunityGrantState.AWAITING_SIGNUP); + + poller.supervise(); + + assertThat(poller.isArmed()).isTrue(); + } + + @Test + void testTheSupervisorDoesNotArmATerminalFlow() { + poller.disarm(); + stored.setState(CommunityGrantState.REGISTERED); + + poller.supervise(); + + assertThat(poller.isArmed()).isFalse(); + } + + @Test + void testAHandedOverFlowIsWatchedOnlineAndLeftAloneOffline() { + poller.disarm(); + stored.setState(CommunityGrantState.REPORT_HANDED_OVER); + stored.setMode(CommunityGrantMode.OFFLINE); + + poller.supervise(); + assertThat(poller.isArmed()).isFalse(); + + stored.setMode(CommunityGrantMode.ONLINE); + poller.supervise(); + assertThat(poller.isArmed()).isTrue(); + } + + @Test + void testInitStartsTheSupervisor() { + poller.init(); + + verify(scheduler).scheduleWithFixedDelay(any(), eq(30000L), eq(30000L), eq(TimeUnit.MILLISECONDS)); + } + + @Test + void testGainingTheSystemTenantPartitionStartsTheSupervisor() { + poller.onTbApplicationEvent(corePartitionChangeEvent()); + + verify(scheduler).scheduleWithFixedDelay(any(), eq(30000L), eq(30000L), eq(TimeUnit.MILLISECONDS)); + } + + @Test + void testTheSupervisorIsStartedOnlyOnce() { + poller.init(); + poller.init(); + + verify(scheduler, times(1)).scheduleWithFixedDelay(any(), anyLong(), anyLong(), any()); + } + + @Test + void testLosingTheSystemTenantPartitionStopsTheSupervisor() { + poller.init(); + ownsSystemTenantPartition(false); + + poller.onTbApplicationEvent(corePartitionChangeEvent()); + + verify(supervisorFuture).cancel(false); + } + + @Test + void testArmingAgainCancelsThePendingPollRatherThanAddingASecondChain() { + clearInvocations(scheduler, scheduledPoll); // setUp() already armed, so one chain is queued + + poller.disarm(); + poller.arm(); + + verify(scheduledPoll).cancel(false); + verify(scheduler, times(1)).schedule(any(Runnable.class), eq(3000L), eq(TimeUnit.MILLISECONDS)); + } + + // Run through the captured Runnable: pollAndReschedule() passes the current generation and cannot mismatch. + @Test + void testAPollLeftOverFromAReplacedChainNeitherReschedulesItselfNorDisarms() { + ArgumentCaptor queuedPoll = ArgumentCaptor.forClass(Runnable.class); + verify(scheduler).schedule(queuedPoll.capture(), anyLong(), any()); // setUp()'s arm() queued it + + poller.disarm(); + poller.arm(); + clearInvocations(scheduler); // the re-arm's own chain is the one allowed to be queued + queuedPoll.getValue().run(); + + verify(scheduler, never()).schedule(any(Runnable.class), anyLong(), any()); + verifyNoInteractions(portalClient); + assertThat(poller.isArmed()).isTrue(); + } + + @Test + void testARejectedScheduleLeavesTheLoopDisarmed() { + poller.disarm(); + doThrow(new RejectedExecutionException("shutting down")) + .when(scheduler).schedule(any(Runnable.class), anyLong(), any()); + + poller.arm(); + + assertThat(poller.isArmed()).isFalse(); + } + + private void ownsSystemTenantPartition(boolean mine) { + lenient().when(partitionService.resolve(ServiceType.TB_CORE, TenantId.SYS_TENANT_ID, TenantId.SYS_TENANT_ID)) + .thenReturn(new TopicPartitionInfo("tb_core", TenantId.SYS_TENANT_ID, 0, mine)); + } + + private PartitionChangeEvent corePartitionChangeEvent() { + return new PartitionChangeEvent(this, ServiceType.TB_CORE, Map.of(), Map.of()); + } + + private CommunityGrantPortalStatus status(String status, Integer retryAfterSec) { + return new CommunityGrantPortalStatus(status, null, retryAfterSec); + } + + private static CommunityGrantPortalStatus verificationRequired() { + return new CommunityGrantPortalStatus("VERIFICATION_REQUIRED", JacksonUtil.toJsonNode(CHECKER_INPUT_JSON), null); + } + +} diff --git a/application/src/test/java/org/thingsboard/server/service/community_grant/CommunityGrantPortalClientTest.java b/application/src/test/java/org/thingsboard/server/service/community_grant/CommunityGrantPortalClientTest.java new file mode 100644 index 0000000000..b543373bf4 --- /dev/null +++ b/application/src/test/java/org/thingsboard/server/service/community_grant/CommunityGrantPortalClientTest.java @@ -0,0 +1,552 @@ +// SPDX-FileCopyrightText: Copyright The Thingsboard Authors +// SPDX-License-Identifier: Apache-2.0 +package org.thingsboard.server.service.community_grant; + +import org.apache.hc.client5.http.config.ConnectionConfig; +import org.apache.hc.client5.http.impl.io.PoolingHttpClientConnectionManager; +import org.apache.hc.core5.function.Resolver; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpMethod; +import org.springframework.http.HttpStatus; +import org.springframework.http.HttpStatusCode; +import org.springframework.http.MediaType; +import org.springframework.http.client.ClientHttpRequestFactory; +import org.springframework.http.client.ClientHttpResponse; +import org.springframework.http.client.HttpComponentsClientHttpRequestFactory; +import org.springframework.http.client.JdkClientHttpRequestFactory; +import org.springframework.http.client.SimpleClientHttpRequestFactory; +import org.springframework.test.util.ReflectionTestUtils; +import org.springframework.test.web.client.MockRestServiceServer; +import org.springframework.test.web.client.ResponseCreator; +import org.springframework.web.client.HttpStatusCodeException; +import org.springframework.web.client.ResourceAccessException; +import org.springframework.web.client.RestTemplate; +import org.thingsboard.server.common.data.community_grant.CommunityGrantMode; + +import java.io.IOException; +import java.io.InputStream; +import java.net.SocketTimeoutException; +import java.net.http.HttpClient; +import java.nio.charset.StandardCharsets; +import java.time.Duration; +import java.util.UUID; +import java.util.concurrent.atomic.AtomicInteger; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatNoException; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.springframework.test.web.client.match.MockRestRequestMatchers.content; +import static org.springframework.test.web.client.match.MockRestRequestMatchers.header; +import static org.springframework.test.web.client.match.MockRestRequestMatchers.method; +import static org.springframework.test.web.client.match.MockRestRequestMatchers.requestTo; +import static org.springframework.test.web.client.response.MockRestResponseCreators.withServerError; +import static org.springframework.test.web.client.response.MockRestResponseCreators.withStatus; +import static org.springframework.test.web.client.response.MockRestResponseCreators.withSuccess; + +class CommunityGrantPortalClientTest { + + private static final String BASE_URL = "https://portal.example"; + private static final String SIGN_UP_PATH = "/communityGrant"; + private static final String TOKEN = "AAAA-BBBB_CCCC"; + private static final String CLAIM_TOKEN_HEADER = "X-TB-Claim-Token"; + + private CommunityGrantPortalClient client; + private MockRestServiceServer mockServer; + + /** Captured before {@link MockRestServiceServer#createServer} replaces the request factory with its own. */ + private ClientHttpRequestFactory realRequestFactory; + + @BeforeEach + void setUp() { + client = new CommunityGrantPortalClient(); + // Without it initRestClient() skips the base-URL validation. + ReflectionTestUtils.setField(client, "enabled", true); + ReflectionTestUtils.setField(client, "baseUrl", BASE_URL); + ReflectionTestUtils.setField(client, "connectTimeoutSec", 5); + ReflectionTestUtils.setField(client, "readTimeoutSec", 10); + ReflectionTestUtils.setField(client, "maxCheckerSizeBytes", 1024L); + client.initRestClient(); + RestTemplate restTemplate = (RestTemplate) ReflectionTestUtils.getField(client, "restTemplate"); + realRequestFactory = restTemplate.getRequestFactory(); + mockServer = MockRestServiceServer.createServer(restTemplate); + } + + @Test + void testSignUpUrlPinsItsParameterNamesAndOrder() { + UUID clusterId = UUID.randomUUID(); + + onPlatform("Linux", "amd64", () -> { + assertThat(client.buildSignUpUrl(clusterId, TOKEN, CommunityGrantMode.ONLINE)) + .isEqualTo(BASE_URL + SIGN_UP_PATH + "?clusterId=" + clusterId + "&claimToken=" + TOKEN + + "&os=linux&arch=amd64"); + assertThat(client.buildSignUpUrl(clusterId, TOKEN, CommunityGrantMode.OFFLINE)) + .isEqualTo(BASE_URL + SIGN_UP_PATH + "?clusterId=" + clusterId + "&claimToken=" + TOKEN + + "&offline=true&os=linux&arch=amd64"); + }); + } + + @Test + void testSignUpUrlCarriesThePlatformEvenWhenTheDeploymentIsOnline() { + onPlatform("Mac OS X", "aarch64", () -> + assertThat(client.buildSignUpUrl(UUID.randomUUID(), TOKEN, CommunityGrantMode.ONLINE)) + .endsWith("&os=darwin&arch=arm64")); + } + + // The portal refuses a link carrying only one of os and arch, so both are dropped. + @Test + void testSignUpUrlOmitsThePlatformOnAnUnsupportedArchitecture() { + UUID clusterId = UUID.randomUUID(); + + onPlatform("Linux", "s390x", () -> + assertThat(client.buildSignUpUrl(clusterId, TOKEN, CommunityGrantMode.OFFLINE)) + .isEqualTo(BASE_URL + SIGN_UP_PATH + "?clusterId=" + clusterId + "&claimToken=" + TOKEN + + "&offline=true")); + } + + @Test + void testSignUpUrlHasNoDoubleSlashWhenTheBaseUrlEndsInOne() { + ReflectionTestUtils.setField(client, "baseUrl", BASE_URL + "/"); + UUID clusterId = UUID.randomUUID(); + + onPlatform("Linux", "amd64", () -> + assertThat(client.buildSignUpUrl(clusterId, TOKEN, CommunityGrantMode.ONLINE)) + .isEqualTo(BASE_URL + SIGN_UP_PATH + "?clusterId=" + clusterId + "&claimToken=" + TOKEN + + "&os=linux&arch=amd64")); + } + + private static void onPlatform(String osName, String osArch, Runnable body) { + String originalName = System.getProperty("os.name"); + String originalArch = System.getProperty("os.arch"); + System.setProperty("os.name", osName); + System.setProperty("os.arch", osArch); + try { + body.run(); + } finally { + restoreProperty("os.name", originalName); + restoreProperty("os.arch", originalArch); + } + } + + private static void restoreProperty(String key, String value) { + if (value == null) { + System.clearProperty(key); + } else { + System.setProperty(key, value); + } + } + + @Test + void testSignUpUrlRefusesAMalformedBaseUrl() { + ReflectionTestUtils.setField(client, "baseUrl", "ht!tp://bad host"); + + assertThatThrownBy(() -> client.buildSignUpUrl(UUID.randomUUID(), TOKEN, CommunityGrantMode.ONLINE)) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void testClusterStatus() { + UUID clusterId = UUID.randomUUID(); + mockServer.expect(requestTo(BASE_URL + "/api/noauth/communityGrant/clusterStatus?clusterId=" + clusterId)) + .andExpect(method(HttpMethod.GET)) + .andRespond(withSuccess("{\"alreadyRegistered\":true}", MediaType.APPLICATION_JSON)); + + assertThat(client.isAlreadyRegistered(clusterId)).isTrue(); + mockServer.verify(); + } + + @Test + void testClusterStatusReturnsFalseWhenNotRegistered() { + UUID clusterId = UUID.randomUUID(); + mockServer.expect(requestTo(BASE_URL + "/api/noauth/communityGrant/clusterStatus?clusterId=" + clusterId)) + .andRespond(withSuccess("{\"alreadyRegistered\":false}", MediaType.APPLICATION_JSON)); + + assertThat(client.isAlreadyRegistered(clusterId)).isFalse(); + mockServer.verify(); + } + + @Test + void testStatusIsParsedWithTheCheckerInput() { + UUID clusterId = UUID.randomUUID(); + String checkerInput = "{\"clusterId\":\"" + clusterId + "\",\"keyId\":7,\"publicKey\":\"cHVi\"," + + "\"challenge\":\"Y2hh\",\"referenceMillis\":1787788800000}"; + mockServer.expect(requestTo(BASE_URL + "/api/noauth/communityGrant/status?clusterId=" + clusterId)) + .andExpect(header(CLAIM_TOKEN_HEADER, TOKEN)) + .andRespond(withSuccess("{\"status\":\"VERIFICATION_REQUIRED\",\"checkerInput\": " + + checkerInput.replace(",", ", ") + ",\"retryAfterSec\":15}", MediaType.APPLICATION_JSON)); + + CommunityGrantPortalStatus status = client.getStatus(TOKEN, clusterId); + + assertThat(status.status()).isEqualTo("VERIFICATION_REQUIRED"); + assertThat(CommunityGrantCheckerInput.from(status.checkerInput())) + .contains(new CommunityGrantCheckerInput(checkerInput)); + assertThat(status.retryAfterSec()).isEqualTo(15); + mockServer.verify(); + } + + @Test + void testStatusToleratesNullsAndUnknownFields() { + UUID clusterId = UUID.randomUUID(); + mockServer.expect(requestTo(BASE_URL + "/api/noauth/communityGrant/status?clusterId=" + clusterId)) + .andExpect(header(CLAIM_TOKEN_HEADER, TOKEN)) + .andRespond(withSuccess("{\"status\":\"AWAITING_SIGNUP\",\"checkerInput\":null," + + "\"retryAfterSec\":null,\"somethingNew\":123}", MediaType.APPLICATION_JSON)); + + CommunityGrantPortalStatus status = client.getStatus(TOKEN, clusterId); + + assertThat(status.status()).isEqualTo("AWAITING_SIGNUP"); + assertThat(CommunityGrantCheckerInput.from(status.checkerInput())).isEmpty(); + assertThat(status.retryAfterSec()).isNull(); + mockServer.verify(); + } + + @Test + void testUploadReportSendsTokenAndReportAndReturnsStatus() { + mockServer.expect(requestTo(BASE_URL + "/api/noauth/communityGrant/report")) + .andExpect(method(HttpMethod.POST)) + .andExpect(content().json("{\"token\":\"AAAA-BBBB_CCCC\",\"report\":\"-----BEGIN TB INSTANCE CHECK-----\\nbody\"}")) + .andRespond(withSuccess("{\"status\":\"VALIDATING\"}", MediaType.APPLICATION_JSON)); + + String status = client.uploadReport(TOKEN, "-----BEGIN TB INSTANCE CHECK-----\nbody"); + + assertThat(status).isEqualTo("VALIDATING"); + mockServer.verify(); + } + + @Test + void testUploadReportReturnsNullOnEmptyBody() { + mockServer.expect(requestTo(BASE_URL + "/api/noauth/communityGrant/report")) + .andExpect(method(HttpMethod.POST)) + .andRespond(withSuccess()); + + String status = client.uploadReport(TOKEN, "-----BEGIN TB INSTANCE CHECK-----\nbody"); + + assertThat(status).isNull(); + mockServer.verify(); + } + + @Test + void testDownloadChecker() { + mockServer.expect(requestTo(BASE_URL + "/api/noauth/communityGrant/checker?os=linux&arch=amd64")) + .andExpect(header(CLAIM_TOKEN_HEADER, TOKEN)) + .andRespond(withSuccess("binary-bytes".getBytes(StandardCharsets.UTF_8), MediaType.APPLICATION_OCTET_STREAM)); + + byte[] checker = client.downloadChecker(TOKEN, "linux", "amd64"); + + assertThat(new String(checker, StandardCharsets.UTF_8)).isEqualTo("binary-bytes"); + mockServer.verify(); + } + + @Test + void testDownloadCheckerSignature() { + mockServer.expect(requestTo(BASE_URL + "/api/noauth/communityGrant/checkerSignature?os=linux&arch=amd64")) + .andExpect(method(HttpMethod.GET)) + .andExpect(header(CLAIM_TOKEN_HEADER, TOKEN)) + .andRespond(withSuccess(CommunityGrantSigningFixtures.SIGNATURE, MediaType.APPLICATION_OCTET_STREAM)); + + assertThat(client.downloadCheckerSignature(TOKEN, "linux", "amd64")) + .isEqualTo(CommunityGrantSigningFixtures.SIGNATURE); + mockServer.verify(); + } + + @Test + void testDownloadCheckerSignatureFailsWhenThePortalHasNoneStaged() { + mockServer.expect(requestTo(BASE_URL + "/api/noauth/communityGrant/checkerSignature?os=linux&arch=amd64")) + .andRespond(withStatus(HttpStatus.NOT_FOUND)); + + assertThatThrownBy(() -> client.downloadCheckerSignature(TOKEN, "linux", "amd64")) + .isInstanceOf(HttpStatusCodeException.class); + mockServer.verify(); + } + + @Test + void testDownloadCheckerSignatureIsBoundedLikeTheDownloadItAccompanies() { + ReflectionTestUtils.setField(client, "maxCheckerSizeBytes", 4L); + mockServer.expect(requestTo(BASE_URL + "/api/noauth/communityGrant/checkerSignature?os=linux&arch=amd64")) + .andRespond(withSuccess("way-too-many-bytes".getBytes(StandardCharsets.UTF_8), MediaType.APPLICATION_OCTET_STREAM)); + + assertThatThrownBy(() -> client.downloadCheckerSignature(TOKEN, "linux", "amd64")) + .isInstanceOf(CommunityGrantCheckerTooLargeException.class) + .hasMessageContaining("release signature stream exceeded"); + mockServer.verify(); + } + + @Test + void testDownloadCheckerRejectsAnOversizedContentLength() { + ReflectionTestUtils.setField(client, "maxCheckerSizeBytes", 4L); + byte[] body = "way-too-many-bytes".getBytes(StandardCharsets.UTF_8); + mockServer.expect(requestTo(BASE_URL + "/api/noauth/communityGrant/checker?os=linux&arch=amd64")) + .andRespond(withSuccess(body, MediaType.APPLICATION_OCTET_STREAM) + .header(HttpHeaders.CONTENT_LENGTH, String.valueOf(body.length))); + + assertThatThrownBy(() -> client.downloadChecker(TOKEN, "linux", "amd64")) + .isInstanceOf(CommunityGrantCheckerTooLargeException.class) + .hasMessageContaining("checker size " + body.length + " bytes exceeds"); + mockServer.verify(); + } + + @Test + void testDownloadCheckerRejectsAnOversizedStreamWithNoContentLength() { + ReflectionTestUtils.setField(client, "maxCheckerSizeBytes", 4L); + mockServer.expect(requestTo(BASE_URL + "/api/noauth/communityGrant/checker?os=linux&arch=amd64")) + .andRespond(withSuccess("way-too-many-bytes".getBytes(StandardCharsets.UTF_8), MediaType.APPLICATION_OCTET_STREAM)); + + assertThatThrownBy(() -> client.downloadChecker(TOKEN, "linux", "amd64")) + .isInstanceOf(CommunityGrantCheckerTooLargeException.class) + .hasMessageContaining("checker stream exceeded"); + mockServer.verify(); + } + + @Test + void testDownloadCheckerWrapsAStreamReadFailureAsResourceAccessException() { + mockServer.expect(requestTo(BASE_URL + "/api/noauth/communityGrant/checker?os=linux&arch=amd64")) + .andRespond(respondWith(new InputStream() { + @Override + public int read() throws IOException { + throw new IOException("connection reset"); + } + })); + + assertThatThrownBy(() -> client.downloadChecker(TOKEN, "linux", "amd64")) + .isInstanceOf(ResourceAccessException.class) + .hasMessageContaining("Failed to read the instance checker") + // The un-expanded url template; the claim token travels in a header. + .hasMessageContaining("GET " + BASE_URL + "/api/noauth/communityGrant/checker?os={os}") + .hasMessageNotContaining(TOKEN) + .hasCauseInstanceOf(IOException.class); + mockServer.verify(); + } + + @Test + void testDownloadCheckerKeepsACompletedDownloadWhenOnlyCloseFails() { + byte[] body = "a-complete-checker".getBytes(StandardCharsets.UTF_8); + mockServer.expect(requestTo(BASE_URL + "/api/noauth/communityGrant/checker?os=linux&arch=amd64")) + .andRespond(respondWith(new InputStream() { + private int position; + + @Override + public int read() { + return position < body.length ? body[position++] & 0xFF : -1; + } + + @Override + public void close() throws IOException { + throw new IOException("failed to release the connection"); + } + })); + + assertThat(client.downloadChecker(TOKEN, "linux", "amd64")).isEqualTo(body); + mockServer.verify(); + } + + @Test + void testRequestAccessSendsTheClusterId() { + UUID clusterId = UUID.randomUUID(); + mockServer.expect(requestTo(BASE_URL + "/api/noauth/communityGrant/requestAccess?clusterId=" + clusterId)) + .andExpect(method(HttpMethod.POST)) + .andRespond(withSuccess()); + + client.requestAccess(clusterId); + + mockServer.verify(); + } + + @Test + void testRequestAccessPropagatesATransportFailure() { + UUID clusterId = UUID.randomUUID(); + mockServer.expect(requestTo(BASE_URL + "/api/noauth/communityGrant/requestAccess?clusterId=" + clusterId)) + .andExpect(method(HttpMethod.POST)) + .andRespond(request -> { + throw new SocketTimeoutException("connect timed out"); + }); + + assertThatThrownBy(() -> client.requestAccess(clusterId)).isInstanceOf(ResourceAccessException.class); + mockServer.verify(); + } + + @Test + void testProbeTreatsAnyHttpAnswerAsReachable() { + mockServer.expect(requestTo(BASE_URL + "/api/noauth/communityGrant/clusterStatus?clusterId=00000000-0000-0000-0000-000000000000")) + .andRespond(withStatus(HttpStatus.NOT_FOUND)); + + assertThat(client.isPortalReachable()).isTrue(); + mockServer.verify(); + } + + @Test + void testProbeTreatsAServerErrorAsReachable() { + mockServer.expect(requestTo(BASE_URL + "/api/noauth/communityGrant/clusterStatus?clusterId=00000000-0000-0000-0000-000000000000")) + .andRespond(withServerError()); + + assertThat(client.isPortalReachable()).isTrue(); + mockServer.verify(); + } + + @Test + void testProbeFailsOnAConnectionError() { + mockServer.expect(requestTo(BASE_URL + "/api/noauth/communityGrant/clusterStatus?clusterId=00000000-0000-0000-0000-000000000000")) + .andRespond(request -> { + throw new SocketTimeoutException("connect timed out"); + }); + + assertThat(client.isPortalReachable()).isFalse(); + mockServer.verify(); + } + + @Test + void testProbeDrainsOnlyABoundedPrefixOfTheBody() { + AtomicInteger bytesRead = new AtomicInteger(); + mockServer.expect(requestTo(BASE_URL + "/api/noauth/communityGrant/clusterStatus?clusterId=00000000-0000-0000-0000-000000000000")) + .andRespond(respondWith(new InputStream() { + @Override + public int read() { + return bytesRead.incrementAndGet() <= 65536 ? 'x' : -1; + } + })); + + assertThat(client.isPortalReachable()).isTrue(); + assertThat(bytesRead).hasValueLessThan(8192); + mockServer.verify(); + } + + @Test + void testStatusReturnsNullOnEmptyBody() { + UUID clusterId = UUID.randomUUID(); + mockServer.expect(requestTo(BASE_URL + "/api/noauth/communityGrant/status?clusterId=" + clusterId)) + .andExpect(header(CLAIM_TOKEN_HEADER, TOKEN)) + .andRespond(withSuccess()); + + assertThat(client.getStatus(TOKEN, clusterId)).isNull(); + mockServer.verify(); + } + + @Test + void testClusterStatusReturnsFalseOnEmptyBody() { + UUID clusterId = UUID.randomUUID(); + mockServer.expect(requestTo(BASE_URL + "/api/noauth/communityGrant/clusterStatus?clusterId=" + clusterId)) + .andRespond(withSuccess()); + + assertThat(client.isAlreadyRegistered(clusterId)).isFalse(); + mockServer.verify(); + } + + @Test + void testATrailingSlashInTheBaseUrlIsTrimmedAtStartup() { + CommunityGrantPortalClient trailingSlashClient = newClient(BASE_URL + "/"); + RestTemplate restTemplate = (RestTemplate) ReflectionTestUtils.getField(trailingSlashClient, "restTemplate"); + MockRestServiceServer server = MockRestServiceServer.createServer(restTemplate); + UUID clusterId = UUID.randomUUID(); + server.expect(requestTo(BASE_URL + "/api/noauth/communityGrant/clusterStatus?clusterId=" + clusterId)) + .andRespond(withSuccess("{\"alreadyRegistered\":false}", MediaType.APPLICATION_JSON)); + + trailingSlashClient.isAlreadyRegistered(clusterId); + + server.verify(); + } + + @Test + void testABaseUrlThatIsNotAnAbsoluteHttpUrlIsRefusedAtStartup() { + assertThatThrownBy(() -> newClient("license.thingsboard.io")).isInstanceOf(IllegalStateException.class); + assertThatThrownBy(() -> newClient("ftp://license.thingsboard.io")).isInstanceOf(IllegalStateException.class); + } + + @Test + void testADisabledClientAcceptsABlankBaseUrlAtStartup() { + CommunityGrantPortalClient disabledClient = new CommunityGrantPortalClient(); + ReflectionTestUtils.setField(disabledClient, "enabled", false); + ReflectionTestUtils.setField(disabledClient, "baseUrl", ""); + ReflectionTestUtils.setField(disabledClient, "connectTimeoutSec", 5); + ReflectionTestUtils.setField(disabledClient, "readTimeoutSec", 10); + + assertThatNoException().isThrownBy(disabledClient::initRestClient); + } + + @Test + void testTimeoutsAreAppliedToTheBuiltRequestFactory() { + assertThat(extractConnectTimeout(realRequestFactory)).isEqualTo(Duration.ofSeconds(5)); + assertThat(extractReadTimeout(realRequestFactory)).isEqualTo(Duration.ofSeconds(10)); + } + + private static Duration extractConnectTimeout(ClientHttpRequestFactory requestFactory) { + if (requestFactory instanceof SimpleClientHttpRequestFactory) { + Integer millis = (Integer) ReflectionTestUtils.getField(requestFactory, "connectTimeout"); + return Duration.ofMillis(millis); + } + if (requestFactory instanceof HttpComponentsClientHttpRequestFactory) { + return Duration.ofMillis(httpComponentsDefaultConnectionConfig(requestFactory).getConnectTimeout().toMilliseconds()); + } + if (requestFactory instanceof JdkClientHttpRequestFactory) { + HttpClient httpClient = (HttpClient) ReflectionTestUtils.getField(requestFactory, "httpClient"); + return httpClient.connectTimeout() + .orElseThrow(() -> new AssertionError("JdkClientHttpRequestFactory's HttpClient has no connect timeout configured")); + } + throw new AssertionError("Unrecognized request factory type, extend this test: " + requestFactory.getClass()); + } + + private static Duration extractReadTimeout(ClientHttpRequestFactory requestFactory) { + if (requestFactory instanceof SimpleClientHttpRequestFactory) { + Integer millis = (Integer) ReflectionTestUtils.getField(requestFactory, "readTimeout"); + return Duration.ofMillis(millis); + } + if (requestFactory instanceof HttpComponentsClientHttpRequestFactory) { + return Duration.ofMillis(httpComponentsDefaultConnectionConfig(requestFactory).getSocketTimeout().toMilliseconds()); + } + if (requestFactory instanceof JdkClientHttpRequestFactory) { + return (Duration) ReflectionTestUtils.getField(requestFactory, "readTimeout"); + } + throw new AssertionError("Unrecognized request factory type, extend this test: " + requestFactory.getClass()); + } + + /** Spring Boot's builder puts the timeouts on the connection manager's {@link ConnectionConfig}, not the factory. */ + private static ConnectionConfig httpComponentsDefaultConnectionConfig(ClientHttpRequestFactory requestFactory) { + Object httpClient = ReflectionTestUtils.getField(requestFactory, "httpClient"); + Object connManager = ReflectionTestUtils.getField(httpClient, "connManager"); + if (!(connManager instanceof PoolingHttpClientConnectionManager)) { + throw new AssertionError("Unrecognized connection manager type, extend this test: " + connManager); + } + @SuppressWarnings("unchecked") + Resolver resolver = + (Resolver) ReflectionTestUtils.getField(connManager, "connectionConfigResolver"); + return resolver.resolve(null); + } + + private static CommunityGrantPortalClient newClient(String baseUrl) { + CommunityGrantPortalClient client = new CommunityGrantPortalClient(); + ReflectionTestUtils.setField(client, "enabled", true); + ReflectionTestUtils.setField(client, "baseUrl", baseUrl); + ReflectionTestUtils.setField(client, "connectTimeoutSec", 5); + ReflectionTestUtils.setField(client, "readTimeoutSec", 10); + client.initRestClient(); + return client; + } + + private static ResponseCreator respondWith(InputStream body) { + return request -> new ClientHttpResponse() { + @Override + public HttpStatusCode getStatusCode() { + return HttpStatus.OK; + } + + @Override + public String getStatusText() { + return "OK"; + } + + @Override + public void close() { + } + + @Override + public InputStream getBody() { + return body; + } + + @Override + public HttpHeaders getHeaders() { + return new HttpHeaders(); + } + }; + } + +} diff --git a/application/src/test/java/org/thingsboard/server/service/community_grant/CommunityGrantReleaseSignatureVerifierTest.java b/application/src/test/java/org/thingsboard/server/service/community_grant/CommunityGrantReleaseSignatureVerifierTest.java new file mode 100644 index 0000000000..96b2043976 --- /dev/null +++ b/application/src/test/java/org/thingsboard/server/service/community_grant/CommunityGrantReleaseSignatureVerifierTest.java @@ -0,0 +1,260 @@ +// SPDX-FileCopyrightText: Copyright The Thingsboard Authors +// SPDX-License-Identifier: Apache-2.0 +package org.thingsboard.server.service.community_grant; + +import org.junit.jupiter.api.Test; +import org.springframework.test.util.ReflectionTestUtils; + +import java.util.Arrays; +import java.util.Base64; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatCode; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.thingsboard.server.service.community_grant.CommunityGrantSigningFixtures.CHECKER; +import static org.thingsboard.server.service.community_grant.CommunityGrantSigningFixtures.OTHER_CHECKER; +import static org.thingsboard.server.service.community_grant.CommunityGrantSigningFixtures.OTHER_SIGNATURE; +import static org.thingsboard.server.service.community_grant.CommunityGrantSigningFixtures.PUBLIC_KEY_A; +import static org.thingsboard.server.service.community_grant.CommunityGrantSigningFixtures.PUBLIC_KEY_B; +import static org.thingsboard.server.service.community_grant.CommunityGrantSigningFixtures.SIGNATURE; +import static org.thingsboard.server.service.community_grant.CommunityGrantSigningFixtures.SIGNATURE_FROM_WRONG_KEY_UNDER_KEY_ID_1; +import static org.thingsboard.server.service.community_grant.CommunityGrantSigningFixtures.SIGNATURE_UNDER_KEY_ID_2; +import static org.thingsboard.server.service.community_grant.CommunityGrantSigningFixtures.TRUSTS_A; +import static org.thingsboard.server.service.community_grant.CommunityGrantSigningFixtures.TRUSTS_A_AND_B; + +class CommunityGrantReleaseSignatureVerifierTest { + + @Test + void testAGenuineReleaseSignatureVerifies() { + assertThatCode(() -> verifierTrusting(TRUSTS_A).verify(CHECKER, SIGNATURE)).doesNotThrowAnyException(); + } + + @Test + void testASingleFlippedBitInTheBinaryIsRejected() { + byte[] tampered = CHECKER.clone(); + tampered[10] ^= 0x01; + + assertRejected(TRUSTS_A, tampered, SIGNATURE, "does not match its release signature"); + } + + @Test + void testATruncatedBinaryIsRejected() { + byte[] truncated = Arrays.copyOf(CHECKER, CHECKER.length - 1); + + assertRejected(TRUSTS_A, truncated, SIGNATURE, "does not match its release signature"); + } + + @Test + void testABinaryWithBytesAppendedIsRejected() { + byte[] extended = Arrays.copyOf(CHECKER, CHECKER.length + 1); + + assertRejected(TRUSTS_A, extended, SIGNATURE, "does not match its release signature"); + } + + @Test + void testASignatureForADifferentBinaryIsRejected() { + assertRejected(TRUSTS_A, CHECKER, OTHER_SIGNATURE, "does not match its release signature"); + // The swapped signature still verifies against its own binary, so the rejection is about the pairing. + assertThatCode(() -> verifierTrusting(TRUSTS_A).verify(OTHER_CHECKER, OTHER_SIGNATURE)) + .doesNotThrowAnyException(); + } + + @Test + void testASignatureFromTheWrongPrivateKeyUnderATrustedKeyIdIsRejected() { + assertRejected(TRUSTS_A, CHECKER, SIGNATURE_FROM_WRONG_KEY_UNDER_KEY_ID_1, + "does not match its release signature"); + } + + // An all-ones S is not a valid encoding, so the provider throws instead of returning false. + @Test + void testASignatureWhoseEncodingTheProviderRejectsOutrightIsStillARejection() { + byte[] unencodable = SIGNATURE.clone(); + Arrays.fill(unencodable, 42, 74, (byte) 0xFF); + + assertRejected(TRUSTS_A, CHECKER, unencodable, "does not match its release signature"); + } + + @Test + void testACorruptedMagicIsRejected() { + byte[] corrupted = SIGNATURE.clone(); + corrupted[3] = 'X'; + + assertRejected(TRUSTS_A, CHECKER, corrupted, "not a ThingsBoard release signature"); + } + + @Test + void testAnUnknownVersionIsRejected() { + byte[] futureVersion = SIGNATURE.clone(); + futureVersion[8] = 0x02; + + assertRejected(TRUSTS_A, CHECKER, futureVersion, "version 2"); + } + + // The untrusted-key message also names key id 0, so the reserved phrase is asserted and the untrusted one excluded. + @Test + void testTheReservedKeyIdZeroIsRejectedAsReservedRatherThanAsUntrusted() { + byte[] reservedKeyId = SIGNATURE.clone(); + reservedKeyId[9] = 0x00; + + for (String trustedKeys : new String[]{TRUSTS_A, TRUSTS_A_AND_B, ""}) { + assertThatThrownBy(() -> verifierTrusting(trustedKeys).verify(CHECKER, reservedKeyId)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("reserved and never valid") + .hasMessageNotContaining("does not trust") + .hasMessageNotContaining(CommunityGrantReleaseSignatureVerifier.PUBLIC_KEYS_PROPERTY); + } + } + + @Test + void testAKeyIdTheTrustStoreDoesNotHoldIsRejectedAsUntrusted() { + byte[] unknownKeyId = SIGNATURE.clone(); + unknownKeyId[9] = 0x09; + + assertThatThrownBy(() -> verifierTrusting(TRUSTS_A).verify(CHECKER, unknownKeyId)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("key id 9") + .hasMessageContaining("does not trust") + .hasMessageNotContaining("reserved"); + assertRejected(TRUSTS_A, CHECKER, SIGNATURE_UNDER_KEY_ID_2, "key id 2"); + } + + @Test + void testASignatureFileOfAnyOtherLengthIsRejected() { + assertRejected(TRUSTS_A, CHECKER, Arrays.copyOf(SIGNATURE, 73), "73 bytes"); + assertRejected(TRUSTS_A, CHECKER, Arrays.copyOf(SIGNATURE, 75), "75 bytes"); + assertRejected(TRUSTS_A, CHECKER, new byte[]{0x54}, "1 bytes"); + } + + @Test + void testAnAbsentOrEmptySignatureFileIsRejected() { + assertRejected(TRUSTS_A, CHECKER, null, "carries no release signature"); + assertRejected(TRUSTS_A, CHECKER, new byte[0], "carries no release signature"); + } + + @Test + void testAnEmptyOrAbsentBinaryIsRejected() { + assertRejected(TRUSTS_A, new byte[0], SIGNATURE, "empty"); + assertRejected(TRUSTS_A, null, SIGNATURE, "empty"); + } + + @Test + void testNothingVerifiesWhenNoKeyIsConfigured() { + for (String unconfigured : new String[]{"", " ", null}) { + assertThatThrownBy(() -> verifierTrusting(unconfigured).verify(CHECKER, SIGNATURE)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining(CommunityGrantReleaseSignatureVerifier.PUBLIC_KEYS_PROPERTY) + .hasMessageContaining("refuses"); + } + } + + @Test + void testAnUnparseablePropertyRefusesEveryUploadAndSaysSo() { + assertThatThrownBy(() -> verifierTrusting("1:" + PUBLIC_KEY_A + ",2:not base64!").verify(CHECKER, SIGNATURE)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining(CommunityGrantReleaseSignatureVerifier.PUBLIC_KEYS_PROPERTY) + .hasMessageContaining("could not be parsed"); + } + + // init() runs once per bean in production; calling it again is the only way to observe a failed reparse. + @Test + void testAFailedReparseLeavesNothingTrustedRatherThanThePreviousKeys() { + CommunityGrantReleaseSignatureVerifier verifier = verifierTrusting(TRUSTS_A); + assertThatCode(() -> verifier.verify(CHECKER, SIGNATURE)).doesNotThrowAnyException(); + + ReflectionTestUtils.setField(verifier, "checkerReleasePublicKeys", "1:" + PUBLIC_KEY_A + ",2:not base64!"); + verifier.init(); + + assertThatThrownBy(() -> verifier.verify(CHECKER, SIGNATURE)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("could not be parsed"); + } + + @Test + void testATrustStoreWithTwoKeysAcceptsReleasesSignedUnderEither() { + CommunityGrantReleaseSignatureVerifier verifier = verifierTrusting(TRUSTS_A_AND_B); + + assertThatCode(() -> verifier.verify(CHECKER, SIGNATURE)).doesNotThrowAnyException(); + assertThatCode(() -> verifier.verify(CHECKER, SIGNATURE_UNDER_KEY_ID_2)).doesNotThrowAnyException(); + // Each key id resolves to its own key. + assertRejected(TRUSTS_A_AND_B, CHECKER, SIGNATURE_FROM_WRONG_KEY_UNDER_KEY_ID_1, + "does not match its release signature"); + } + + @Test + void testWhitespaceAroundEntriesIsTolerated() { + assertThatCode(() -> verifierTrusting(" 1 : " + PUBLIC_KEY_A + " , 2 : " + PUBLIC_KEY_B + " ") + .verify(CHECKER, SIGNATURE_UNDER_KEY_ID_2)).doesNotThrowAnyException(); + } + + @Test + void testAKeyIdOutsideOneToTwoFiveFiveCannotBeConfigured() { + assertUnparseable("0:" + PUBLIC_KEY_A, "reserved"); + assertUnparseable("256:" + PUBLIC_KEY_A, "1-255"); + assertUnparseable("-1:" + PUBLIC_KEY_A, "1-255"); + } + + @Test + void testMalformedEntriesAreRefusedRatherThanSkipped() { + assertUnparseable(PUBLIC_KEY_A, "keyId:base64PublicKey"); + assertUnparseable("one:" + PUBLIC_KEY_A, "not a number"); + assertUnparseable("1:" + PUBLIC_KEY_A + ",", "empty entry"); + assertUnparseable("1:" + PUBLIC_KEY_A + ",1:" + PUBLIC_KEY_B, "more than once"); + assertUnparseable("1:", "0 bytes"); + assertUnparseable("1:AAAA", "3 bytes"); + } + + @Test + void testAnX509WrappedPublicKeyIsRefused() { + byte[] raw = Base64.getDecoder().decode(PUBLIC_KEY_A); + byte[] wrapped = new byte[12 + raw.length]; + System.arraycopy(new byte[]{0x30, 0x2a, 0x30, 0x05, 0x06, 0x03, 0x2b, 0x65, 0x70, 0x03, 0x21, 0x00}, + 0, wrapped, 0, 12); + System.arraycopy(raw, 0, wrapped, 12, raw.length); + + assertUnparseable("1:" + Base64.getEncoder().encodeToString(wrapped), "44 bytes"); + } + + // KeyFactory accepts some off-curve values and only fails at verification time. + @Test + void testAKeyThatIsNotAValidEd25519PointIsRefused() { + byte[] notAPoint = new byte[32]; + Arrays.fill(notAPoint, (byte) 0xFF); + + assertUnparseable("1:" + Base64.getEncoder().encodeToString(notAPoint), "not a usable Ed25519 public key"); + } + + @Test + void testRefusalMessagesCarryNoKeyMaterialOrUploadedBytes() { + byte[][] rejectedSignatures = {null, new byte[0], Arrays.copyOf(SIGNATURE, 75), OTHER_SIGNATURE, + SIGNATURE_FROM_WRONG_KEY_UNDER_KEY_ID_1, SIGNATURE_UNDER_KEY_ID_2}; + for (byte[] rejected : rejectedSignatures) { + assertThatThrownBy(() -> verifierTrusting(TRUSTS_A).verify(CHECKER, rejected)) + .isInstanceOf(IllegalArgumentException.class) + .satisfies(e -> { + assertThat(e.getMessage()).doesNotContain(PUBLIC_KEY_A); + assertThat(e.getMessage()).doesNotContain(PUBLIC_KEY_B); + assertThat(e.getMessage()).doesNotContain("#!/bin/sh"); + }); + } + } + + private static void assertRejected(String trustedKeys, byte[] checker, byte[] signature, String expectedInMessage) { + assertThatThrownBy(() -> verifierTrusting(trustedKeys).verify(checker, signature)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining(expectedInMessage); + } + + private static void assertUnparseable(String configured, String expectedInMessage) { + assertThatThrownBy(() -> CommunityGrantReleaseSignatureVerifier.parsePublicKeys(configured)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining(expectedInMessage); + } + + private static CommunityGrantReleaseSignatureVerifier verifierTrusting(String configured) { + CommunityGrantReleaseSignatureVerifier verifier = new CommunityGrantReleaseSignatureVerifier(); + ReflectionTestUtils.setField(verifier, "checkerReleasePublicKeys", configured); + verifier.init(); + return verifier; + } + +} diff --git a/application/src/test/java/org/thingsboard/server/service/community_grant/CommunityGrantReportRunnerTest.java b/application/src/test/java/org/thingsboard/server/service/community_grant/CommunityGrantReportRunnerTest.java new file mode 100644 index 0000000000..922f0fb1db --- /dev/null +++ b/application/src/test/java/org/thingsboard/server/service/community_grant/CommunityGrantReportRunnerTest.java @@ -0,0 +1,529 @@ +// SPDX-FileCopyrightText: Copyright The Thingsboard Authors +// SPDX-License-Identifier: Apache-2.0 +package org.thingsboard.server.service.community_grant; + +import ch.qos.logback.classic.Level; +import ch.qos.logback.classic.Logger; +import ch.qos.logback.classic.spi.ILoggingEvent; +import ch.qos.logback.core.read.ListAppender; +import org.apache.commons.io.FileUtils; +import org.apache.commons.lang3.SystemUtils; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.Spy; +import org.mockito.junit.jupiter.MockitoExtension; +import org.slf4j.LoggerFactory; +import org.springframework.boot.info.BuildProperties; +import org.springframework.http.HttpStatus; +import org.springframework.test.util.ReflectionTestUtils; +import org.springframework.web.client.HttpClientErrorException; + +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.attribute.PosixFilePermissions; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.Arrays; +import java.util.HashMap; +import java.util.HexFormat; +import java.util.List; +import java.util.Map; +import java.util.Properties; +import java.util.UUID; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.junit.jupiter.api.Assumptions.assumeFalse; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +@ExtendWith(MockitoExtension.class) +class CommunityGrantReportRunnerTest { + + private static final String TOKEN = "token-one"; + private static final String REPORT = "-----BEGIN TB INSTANCE CHECK-----\nZmFrZS1yZXBvcnQtYm9keQ==\n-----END TB INSTANCE CHECK-----"; + private static final UUID CLUSTER_ID = UUID.randomUUID(); + private static final String CHECKER_INPUT_JSON = "{\"clusterId\":\"" + CLUSTER_ID + "\",\"keyId\":7," + + "\"publicKey\":\"cHVi\",\"challenge\":\"Y2hh\",\"referenceMillis\":1787788800000}"; + private static final CommunityGrantCheckerInput CHECKER_INPUT = new CommunityGrantCheckerInput(CHECKER_INPUT_JSON); + private static final String TB_VERSION = "4.3.1.4"; + + private static final String RELEASE_PUBLIC_KEY = CommunityGrantSigningFixtures.PUBLIC_KEY_A; + private static final String TRUSTED_KEYS = CommunityGrantSigningFixtures.TRUSTS_A; + private static final byte[] SIGNED_CHECKER = CommunityGrantSigningFixtures.CHECKER; + private static final byte[] RELEASE_SIGNATURE = CommunityGrantSigningFixtures.SIGNATURE; + + @Mock + private CommunityGrantPortalClient portalClient; + + /** Real, not stubbed, so the refusal assertions depend on actual verification. */ + @Spy + private CommunityGrantReleaseSignatureVerifier releaseSignatureVerifier = + new CommunityGrantReleaseSignatureVerifier(); + + @Spy + @InjectMocks + private CommunityGrantReportRunner runner; + + private ListAppender testLogAppender; + + // No class-wide POSIX assumption: most tests never execute a script and must run on Windows too. + @BeforeEach + void setUp() { + ReflectionTestUtils.setField(runner, "dbUrl", "jdbc:postgresql://localhost:5432/thingsboard"); + ReflectionTestUtils.setField(runner, "dbUserName", "postgres"); + ReflectionTestUtils.setField(runner, "dbPassword", "secret"); + ReflectionTestUtils.setField(runner, "checkerTimeoutSec", 30); + ReflectionTestUtils.setField(runner, "maxReportSizeBytes", 1048576); + ReflectionTestUtils.setField(runner, "maxCheckerSizeBytes", 33554432L); + ReflectionTestUtils.setField(runner, "buildProperties", buildProperties(TB_VERSION)); + trustReleaseKeys(TRUSTED_KEYS); + Logger logger = (Logger) LoggerFactory.getLogger(CommunityGrantReportRunner.class); + testLogAppender = new ListAppender<>(); + testLogAppender.start(); + logger.addAppender(testLogAppender); + } + + @AfterEach + void tearDown() { + if (testLogAppender != null) { + testLogAppender.stop(); + Logger logger = (Logger) LoggerFactory.getLogger(CommunityGrantReportRunner.class); + logger.detachAppender(testLogAppender); + } + } + + @Test + void testRunAndUploadRunsTheCheckerAndUploadsItsOutput() throws IOException { + Path checker = fakeChecker("#!/bin/sh\ncat <<'EOF'\n" + REPORT + "\nEOF\n"); + doReturn(checker).when(runner).fetchChecker(TOKEN); + when(portalClient.uploadReport(TOKEN, REPORT)).thenReturn("DONE"); + + String status = runner.runAndUpload(TOKEN, CHECKER_INPUT); + + assertThat(status).isEqualTo("DONE"); + verify(portalClient).uploadReport(TOKEN, REPORT); + } + + @Test + void testTheCheckerBinaryIsDeletedAfterTheRun() throws IOException { + Path checker = fakeChecker("#!/bin/sh\ncat <<'EOF'\n" + REPORT + "\nEOF\n"); + doReturn(checker).when(runner).fetchChecker(TOKEN); + when(portalClient.uploadReport(anyString(), anyString())).thenReturn("DONE"); + + runner.runAndUpload(TOKEN, CHECKER_INPUT); + + assertThat(Files.exists(checker)).isFalse(); + assertThat(Files.exists(checker.getParent())).isFalse(); + } + + @Test + void testTheDsnAndTheInputArePassedThroughTheEnvironmentAndOnlyTheVersionOnArgv() throws IOException { + String report = runCheckerEchoingItsInvocation(); + + assertThat(report).contains("env=postgres://postgres:secret@localhost:5432/thingsboard"); + assertThat(report).contains("input=" + CHECKER_INPUT_JSON); + + // The checker refuses a flag it does not know, so argv is pinned exactly. + String argvLine = argvLine(report); + assertThat(argvLine).isEqualTo("argv=--tb-version " + TB_VERSION); + assertThat(argvLine).doesNotContain("secret"); + } + + @Test + void testTheVersionIsLeftOffWhereTheBuildCarriesNone() throws IOException { + ReflectionTestUtils.setField(runner, "buildProperties", null); + + String report = runCheckerEchoingItsInvocation(); + + assertThat(argvLine(report)).isEqualTo("argv="); + } + + // A constructed map: a spawned child would only see the PG* variables this host happens to export. + @Test + void testThePgEnvironmentIsStrippedWhileTheRestOfItSurvives() { + Map environment = new HashMap<>(); + environment.put("PGHOST", "attacker.example"); + environment.put("PGPASSWORD", "not-the-configured-one"); + environment.put("PGSERVICE", "redirected"); + environment.put("PGSSLMODE", "disable"); + // The Windows environment is case-insensitive, so this would reach the child as PGHOST. + environment.put("Pghost", "attacker.example"); + environment.put("PATH", "/usr/bin"); + environment.put("HOME", "/home/thingsboard"); + environment.put("HTTPS_PROXY", "http://proxy.internal:3128"); + environment.put("TB_IC_INPUT", "{\"inherited\":true}"); + + CommunityGrantReportRunner.prepareCheckerEnvironment(environment, "postgres://u:p@localhost:5432/tb", + CHECKER_INPUT); + + assertThat(environment).doesNotContainKeys("PGHOST", "PGPASSWORD", "PGSERVICE", "PGSSLMODE", "Pghost"); + assertThat(environment) + .containsEntry("PATH", "/usr/bin") + .containsEntry("HOME", "/home/thingsboard") + .containsEntry("HTTPS_PROXY", "http://proxy.internal:3128") + .containsEntry("TB_IC_DSN", "postgres://u:p@localhost:5432/tb") + .containsEntry("TB_IC_INPUT", CHECKER_INPUT_JSON); + } + + @Test + void testANonZeroExitIsAFailureAndNothingIsUploaded() throws IOException { + Path checker = fakeChecker("#!/bin/sh\necho \"-----BEGIN TB INSTANCE CHECK-----\"\nexit 3\n"); + doReturn(checker).when(runner).fetchChecker(TOKEN); + + assertThatThrownBy(() -> runner.runAndUpload(TOKEN, CHECKER_INPUT)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("3"); + verify(portalClient, never()).uploadReport(anyString(), anyString()); + assertThat(Files.exists(checker.getParent())).isFalse(); + } + + @Test + void testACheckerThatHangsIsKilledAtTheTimeout() throws IOException { + ReflectionTestUtils.setField(runner, "checkerTimeoutSec", 1); + Path checker = fakeChecker("#!/bin/sh\nsleep 30\n"); + doReturn(checker).when(runner).fetchChecker(TOKEN); + + assertThatThrownBy(() -> runner.runAndUpload(TOKEN, CHECKER_INPUT)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("did not finish"); + verify(portalClient, never()).uploadReport(anyString(), anyString()); + } + + @Test + void testOversizedOutputIsRefused() throws IOException { + ReflectionTestUtils.setField(runner, "maxReportSizeBytes", 64); + Path checker = fakeChecker("#!/bin/sh\necho \"-----BEGIN TB INSTANCE CHECK-----\"\n" + + "i=0\nwhile [ $i -lt 5000 ]; do echo \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"; i=$((i+1)); done\n"); + doReturn(checker).when(runner).fetchChecker(TOKEN); + + assertThatThrownBy(() -> runner.runAndUpload(TOKEN, CHECKER_INPUT)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("more output than the configured limit"); + verify(portalClient, never()).uploadReport(anyString(), anyString()); + } + + @Test + void testOutputThatIsNotAReportIsRefused() throws IOException { + Path checker = fakeChecker("#!/bin/sh\necho \"hello from somewhere else\"\n"); + doReturn(checker).when(runner).fetchChecker(TOKEN); + + assertThatThrownBy(() -> runner.runAndUpload(TOKEN, CHECKER_INPUT)) + .isInstanceOf(IllegalStateException.class); + verify(portalClient, never()).uploadReport(anyString(), anyString()); + } + + @Test + void testOutputThatIsMissingTheTrailerIsRefused() throws IOException { + Path checker = fakeChecker("#!/bin/sh\necho \"-----BEGIN TB INSTANCE CHECK-----\"\n" + + "echo \"ZmFrZS1yZXBvcnQtYm9keQ==\"\n"); + doReturn(checker).when(runner).fetchChecker(TOKEN); + + assertThatThrownBy(() -> runner.runAndUpload(TOKEN, CHECKER_INPUT)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("unexpected output"); + verify(portalClient, never()).uploadReport(anyString(), anyString()); + } + + @Test + void testFetchCheckerWritesThePortalsBytesAsAnExecutableChecker() throws IOException { + assumeFalse(SystemUtils.IS_OS_WINDOWS, "The downloaded fixture is a POSIX shell script and is executed"); + CommunityGrantPlatform platform = CommunityGrantPlatform.current(); + when(portalClient.downloadChecker(TOKEN, platform.os(), platform.arch())).thenReturn(SIGNED_CHECKER); + when(portalClient.downloadCheckerSignature(TOKEN, platform.os(), platform.arch())) + .thenReturn(RELEASE_SIGNATURE); + + Path checker = runner.fetchChecker(TOKEN); + + try { + assertThat(checker).exists(); + assertThat(Files.isExecutable(checker)).isTrue(); + assertThat(runner.runChecker(checker, CHECKER_INPUT)).isEqualTo(REPORT); + } finally { + FileUtils.deleteQuietly(checker.getParent().toFile()); + } + } + + @Test + void testADownloadedCheckerThatDoesNotMatchItsReleaseSignatureIsRefusedAndNeverWritten() throws IOException { + CommunityGrantPlatform platform = CommunityGrantPlatform.current(); + when(portalClient.downloadChecker(TOKEN, platform.os(), platform.arch())).thenReturn(SIGNED_CHECKER); + when(portalClient.downloadCheckerSignature(TOKEN, platform.os(), platform.arch())) + .thenReturn(CommunityGrantSigningFixtures.OTHER_SIGNATURE); + + assertThatThrownBy(() -> runner.fetchChecker(TOKEN)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("does not match the release signature"); + verify(runner, never()).writeChecker(any(), anyString()); + } + + @Test + void testADownloadedCheckerWithNoReleaseSignatureStagedIsRefusedAndNeverWritten() throws IOException { + CommunityGrantPlatform platform = CommunityGrantPlatform.current(); + when(portalClient.downloadChecker(TOKEN, platform.os(), platform.arch())).thenReturn(SIGNED_CHECKER); + when(portalClient.downloadCheckerSignature(TOKEN, platform.os(), platform.arch())) + .thenThrow(new HttpClientErrorException(HttpStatus.NOT_FOUND)); + + assertThatThrownBy(() -> runner.fetchChecker(TOKEN)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("no release signature"); + verify(runner, never()).writeChecker(any(), anyString()); + } + + @Test + void testTheOnlineRouteRefusesToRunWhenNoReleaseKeyIsConfigured() throws IOException { + for (String unusable : new String[]{"", "1:not base64!"}) { + trustReleaseKeys(unusable); + + assertThatThrownBy(() -> runner.fetchChecker(TOKEN)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining(CommunityGrantReleaseSignatureVerifier.PUBLIC_KEYS_PROPERTY) + .hasMessageContaining("was not run"); + } + verify(portalClient, never()).downloadChecker(anyString(), anyString(), anyString()); + verify(runner, never()).writeChecker(any(), anyString()); + } + + @Test + void testTheStagedCheckerIsOwnerOnlyAndNotWritable() throws IOException { + assumeFalse(SystemUtils.IS_OS_WINDOWS, "POSIX permissions"); + Path checker = runner.writeChecker("#!/bin/sh\n".getBytes(StandardCharsets.UTF_8), "tb-instance-check"); + + try { + assertThat(Files.getPosixFilePermissions(checker)) + .isEqualTo(PosixFilePermissions.fromString("r-x------")); + assertThat(Files.getPosixFilePermissions(checker.getParent())) + .isEqualTo(PosixFilePermissions.fromString("rwx------")); + } finally { + FileUtils.deleteQuietly(checker.getParent().toFile()); + } + } + + @Test + void testCurrentPlatformIsMappedToThePortalVocabulary() { + CommunityGrantPlatform platform = CommunityGrantPlatform.current(); + assertThat(platform.os()).isIn("linux", "darwin", "windows"); + assertThat(platform.arch()).isIn("amd64", "arm64"); + } + + @Test + void testUploadedCheckerRunsWhenItsReleaseSignatureVerifies() { + assumeFalse(SystemUtils.IS_OS_WINDOWS, "The signed fixture is a POSIX shell script and is actually executed"); + String report = runner.runUploadedChecker(SIGNED_CHECKER, RELEASE_SIGNATURE, null, CHECKER_INPUT); + + assertThat(report).isEqualTo(REPORT); + } + + @Test + void testATamperedUploadedCheckerIsRefusedAndNeverExecuted() throws IOException { + byte[] tampered = SIGNED_CHECKER.clone(); + tampered[10] ^= 0x01; + + assertThatThrownBy(() -> runner.runUploadedChecker(tampered, RELEASE_SIGNATURE, null, CHECKER_INPUT)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("does not match its release signature"); + // Never written either, which pins the check ahead of writeChecker. + verify(runner, never()).writeChecker(any(), anyString()); + verify(runner, never()).runChecker(any(), any()); + verify(portalClient, never()).uploadReport(anyString(), anyString()); + } + + @Test + void testVerifyingAnUploadRefusesATamperedCheckerAndNeverWritesOrRunsOne() throws IOException { + byte[] tampered = SIGNED_CHECKER.clone(); + tampered[10] ^= 0x01; + + assertThatThrownBy(() -> runner.verifyUploadedChecker(tampered, RELEASE_SIGNATURE, null)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("does not match its release signature"); + runner.verifyUploadedChecker(SIGNED_CHECKER, RELEASE_SIGNATURE, null); + + verify(runner, never()).writeChecker(any(), anyString()); + verify(runner, never()).runChecker(any(), any()); + } + + // Refusals ahead of the signature check do not log; the controller's audit row records them. + @Test + void testAnEmptyUploadIsRefusedWithoutWritingOrExecutingAnything() throws IOException { + assertThatThrownBy(() -> runner.runUploadedChecker(new byte[0], RELEASE_SIGNATURE, null, CHECKER_INPUT)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("is empty"); + + assertNothingWasWrittenExecutedOrLogged(); + } + + @Test + void testAnOversizedUploadIsRefusedWithoutWritingOrExecutingAnything() throws IOException { + ReflectionTestUtils.setField(runner, "maxCheckerSizeBytes", (long) SIGNED_CHECKER.length - 1); + + assertThatThrownBy(() -> runner.runUploadedChecker(SIGNED_CHECKER, RELEASE_SIGNATURE, null, CHECKER_INPUT)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("larger than the configured limit"); + + assertNothingWasWrittenExecutedOrLogged(); + } + + @Test + void testAnUploadNamingAnotherPlatformIsRefusedWithoutWritingOrExecutingAnything() throws IOException { + assertThatThrownBy(() -> runner.runUploadedChecker(SIGNED_CHECKER, RELEASE_SIGNATURE, + anotherPlatformFileName(), CHECKER_INPUT)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("does not match this server's platform"); + + assertNothingWasWrittenExecutedOrLogged(); + } + + @Test + void testAFileNameNamingNoOtherPlatformReachesTheSignatureCheck() { + CommunityGrantPlatform platform = CommunityGrantPlatform.current(); + byte[] tampered = SIGNED_CHECKER.clone(); + tampered[10] ^= 0x01; + + for (String fileName : List.of(platform.checkerFileName(), + "tb-instance-check_" + platform.os() + "_" + platform.arch())) { + assertThatThrownBy(() -> runner.runUploadedChecker(tampered, RELEASE_SIGNATURE, fileName, CHECKER_INPUT)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("does not match its release signature"); + } + } + + @Test + void testAnUploadedCheckerWithNoSignatureIsRefusedAndNeverExecuted() throws IOException { + assertThatThrownBy(() -> runner.runUploadedChecker(SIGNED_CHECKER, null, null, CHECKER_INPUT)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("carries no release signature"); + verify(runner, never()).writeChecker(any(), anyString()); + verify(runner, never()).runChecker(any(), any()); + } + + @Test + void testARefusedUploadIsLoggedAtWarnWithTheUploadedDigestAndNoSecrets() { + byte[] tampered = SIGNED_CHECKER.clone(); + tampered[10] ^= 0x01; + String uploadedDigest = sha256Hex(tampered); + + assertThatThrownBy(() -> runner.runUploadedChecker(tampered, RELEASE_SIGNATURE, null, CHECKER_INPUT)) + .isInstanceOf(IllegalArgumentException.class); + + assertThat(testLogAppender.list).hasSize(1); + ILoggingEvent event = testLogAppender.list.get(0); + assertThat(event.getLevel()).isEqualTo(Level.WARN); + String formatted = event.getFormattedMessage(); + assertThat(formatted).contains("Refused").contains(uploadedDigest); + assertThat(formatted).doesNotContain(RELEASE_PUBLIC_KEY); + assertNoSecretsLeaked(formatted); + } + + @Test + void testAnUploadedCheckerIsRefusedWhenNoReleaseKeyIsConfigured() throws IOException { + trustReleaseKeys(""); + + assertThatThrownBy(() -> runner.runUploadedChecker(SIGNED_CHECKER, RELEASE_SIGNATURE, null, CHECKER_INPUT)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("community-grant.checker-release-public-keys"); + verify(runner, never()).writeChecker(any(), anyString()); + verify(runner, never()).runChecker(any(), any()); + } + + @Test + void testAnUnconfiguredAndAMisconfiguredDeploymentAreRefusedDifferently() throws IOException { + trustReleaseKeys(""); + assertThatThrownBy(() -> runner.runUploadedChecker(SIGNED_CHECKER, RELEASE_SIGNATURE, null, CHECKER_INPUT)) + .hasMessageContaining("refuses to run one") + .hasMessageNotContaining("could not be parsed"); + + trustReleaseKeys("1:" + RELEASE_PUBLIC_KEY + ",2:not base64!"); + assertThatThrownBy(() -> runner.runUploadedChecker(SIGNED_CHECKER, RELEASE_SIGNATURE, null, CHECKER_INPUT)) + .hasMessageContaining("could not be parsed") + .hasMessageNotContaining("refuses to run one"); + + verify(runner, never()).writeChecker(any(), anyString()); + verify(runner, never()).runChecker(any(), any()); + } + + @Test + void testTheRefusalMessagesNeverLeakTheDatasourcePasswordOrDsn() { + byte[] tampered = SIGNED_CHECKER.clone(); + tampered[10] ^= 0x01; + + assertThatThrownBy(() -> runner.runUploadedChecker(tampered, RELEASE_SIGNATURE, null, CHECKER_INPUT)) + .satisfies(e -> assertNoSecretsLeaked(e.getMessage())); + + trustReleaseKeys(""); + assertThatThrownBy(() -> runner.runUploadedChecker(SIGNED_CHECKER, RELEASE_SIGNATURE, null, CHECKER_INPUT)) + .satisfies(e -> assertNoSecretsLeaked(e.getMessage())); + } + + private static String anotherPlatformFileName() { + CommunityGrantPlatform platform = CommunityGrantPlatform.current(); + return "tb-instance-check_" + ("linux".equals(platform.os()) ? "windows" : "linux") + "_" + platform.arch(); + } + + private void trustReleaseKeys(String configured) { + ReflectionTestUtils.setField(releaseSignatureVerifier, "checkerReleasePublicKeys", configured); + releaseSignatureVerifier.init(); + } + + private void assertNoSecretsLeaked(String message) { + assertThat(message).doesNotContain("secret"); + assertThat(message).doesNotContain("postgres://"); + assertThat(message).doesNotContain(TOKEN); + } + + private static String sha256Hex(byte[] data) { + try { + return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(data)); + } catch (NoSuchAlgorithmException e) { + throw new IllegalStateException(e); + } + } + + private static BuildProperties buildProperties(String version) { + Properties properties = new Properties(); + properties.setProperty("version", version); + return new BuildProperties(properties); + } + + private String runCheckerEchoingItsInvocation() throws IOException { + Path checker = fakeChecker("#!/bin/sh\n" + + "echo \"-----BEGIN TB INSTANCE CHECK-----\"\n" + + "echo \"env=$TB_IC_DSN\"\n" + + "echo \"input=$TB_IC_INPUT\"\n" + + "echo \"argv=$*\"\n" + + "echo \"-----END TB INSTANCE CHECK-----\"\n"); + try { + return runner.runChecker(checker, CHECKER_INPUT); + } finally { + FileUtils.deleteQuietly(checker.getParent().toFile()); + } + } + + private static String argvLine(String report) { + return Arrays.stream(report.split("\n")) + .filter(line -> line.startsWith("argv=")) + .findFirst() + .orElseThrow(() -> new AssertionError("The fake checker's output has no argv line")); + } + + private Path fakeChecker(String script) throws IOException { + assumeFalse(SystemUtils.IS_OS_WINDOWS, "The fake checker is a POSIX shell script with POSIX permissions"); + return runner.writeChecker(script.getBytes(StandardCharsets.UTF_8), "tb-instance-check"); + } + + private void assertNothingWasWrittenExecutedOrLogged() throws IOException { + verify(runner, never()).writeChecker(any(), anyString()); + verify(runner, never()).runChecker(any(), any()); + assertThat(testLogAppender.list).isEmpty(); + } + +} diff --git a/application/src/test/java/org/thingsboard/server/service/community_grant/CommunityGrantSigningFixtures.java b/application/src/test/java/org/thingsboard/server/service/community_grant/CommunityGrantSigningFixtures.java new file mode 100644 index 0000000000..58b2ddd782 --- /dev/null +++ b/application/src/test/java/org/thingsboard/server/service/community_grant/CommunityGrantSigningFixtures.java @@ -0,0 +1,50 @@ +// SPDX-FileCopyrightText: Copyright The Thingsboard Authors +// SPDX-License-Identifier: Apache-2.0 +package org.thingsboard.server.service.community_grant; + +import java.util.Base64; + +/** + * Test-only keypairs; only the public halves appear here. + */ +final class CommunityGrantSigningFixtures { + + static final String PUBLIC_KEY_A = "jHpPieuz8lNtJdrhzz0vi0hzXAxljhABo1FfIRtjBb0="; + static final String PUBLIC_KEY_B = "aqbhyeoLeaeAqQhjO3vDN+PX3U66ptqY8rHSbfrbpMI="; + + static final String TRUSTS_A = "1:" + PUBLIC_KEY_A; + static final String TRUSTS_A_AND_B = "1:" + PUBLIC_KEY_A + ",2:" + PUBLIC_KEY_B; + + /** A shell script that prints a well-formed report, so a runner can execute it. */ + static final byte[] CHECKER = decode( + "IyEvYmluL3NoCmNhdCA8PCdFT0YnCi0tLS0tQkVHSU4gVEIgSU5TVEFOQ0UgQ0hFQ0stLS0tLQpabUZyWlMxeVpYQnZjb" + + "lF0WW05a2VRPT0KLS0tLS1FTkQgVEIgSU5TVEFOQ0UgQ0hFQ0stLS0tLQpFT0YK"); + + static final byte[] OTHER_CHECKER = decode( + "IyEvYmluL3NoCmVjaG8gIi0tLS0tQkVHSU4gVEIgSU5TVEFOQ0UgQ0hFQ0stLS0tLSIKZWNobyAiYSBkaWZmZXJlbnQgY" + + "2hlY2tlciBidWlsZCIK"); + + static final byte[] SIGNATURE = decode( + "VEJJQ1NJRzEBAWRjh7y4j1vNYnedESE5qBZss7R7LeimEWHJcX9du8OyGFpbWAxdi49A40GotXjo7EhXw9sUFxDiPuz1p" + + "wAjzgs="); + + static final byte[] OTHER_SIGNATURE = decode( + "VEJJQ1NJRzEBATCrpGddBA5MxIwkJOTMQZq/pg6b4IYEwA8a29TxsyYL2H52QRENSnlUCpl4y+IVgkKFdTMEp+0AmNft/" + + "FE64wc="); + + static final byte[] SIGNATURE_FROM_WRONG_KEY_UNDER_KEY_ID_1 = decode( + "VEJJQ1NJRzEBASiAzItE5P7weSOkVkY8W6V9aOQ45jlwt6IW5POZkctc9inj2C5jrMaHNRK3tJ03ljhAOl9Ugsq3oYtCG" + + "9JFIgo="); + + static final byte[] SIGNATURE_UNDER_KEY_ID_2 = decode( + "VEJJQ1NJRzEBAiiAzItE5P7weSOkVkY8W6V9aOQ45jlwt6IW5POZkctc9inj2C5jrMaHNRK3tJ03ljhAOl9Ugsq3oYtCG" + + "9JFIgo="); + + private CommunityGrantSigningFixtures() { + } + + private static byte[] decode(String base64) { + return Base64.getDecoder().decode(base64); + } + +} diff --git a/application/src/test/java/org/thingsboard/server/service/community_grant/CommunityGrantStateInfoTest.java b/application/src/test/java/org/thingsboard/server/service/community_grant/CommunityGrantStateInfoTest.java new file mode 100644 index 0000000000..113dda0614 --- /dev/null +++ b/application/src/test/java/org/thingsboard/server/service/community_grant/CommunityGrantStateInfoTest.java @@ -0,0 +1,70 @@ +// SPDX-FileCopyrightText: Copyright The Thingsboard Authors +// SPDX-License-Identifier: Apache-2.0 +package org.thingsboard.server.service.community_grant; + +import com.fasterxml.jackson.databind.JsonNode; +import org.junit.jupiter.api.Test; +import org.thingsboard.common.util.JacksonUtil; +import org.thingsboard.server.common.data.community_grant.CommunityGrantFlowState; +import org.thingsboard.server.common.data.community_grant.CommunityGrantOfflineRun; +import org.thingsboard.server.common.data.community_grant.CommunityGrantParkReason; +import org.thingsboard.server.common.data.community_grant.CommunityGrantState; +import org.thingsboard.server.common.data.community_grant.CommunityGrantStateInfo; + +import java.util.ArrayList; +import java.util.List; +import java.util.UUID; + +import static org.assertj.core.api.Assertions.assertThat; + +class CommunityGrantStateInfoTest { + + @Test + void testStateInfoSerializesExactlyTheNineAllowedFields() { + CommunityGrantFlowState flowState = CommunityGrantFlowState.initial(); + flowState.setSignUpUrl("https://portal.example/signup"); + flowState.setLastPolledAt(7L); + flowState.setParkReason(CommunityGrantParkReason.CHECK_FAILED); + // Must not reach the widget. + flowState.setStartedAt(3L); + flowState.setOfflineRun(CommunityGrantOfflineRun.running(UUID.randomUUID(), 5L)); + + JsonNode json = JacksonUtil.valueToTree( + CommunityGrantStateInfo.of(flowState, "https://portal.example")); + + List fieldNames = new ArrayList<>(); + json.fieldNames().forEachRemaining(fieldNames::add); + assertThat(fieldNames).containsExactlyInAnyOrder("mode", "state", "signUpUrl", "lastPolledAt", + "parkReason", "portalUrl", "offlineReport", "offlineRunInProgress", "offlineRunError"); + assertThat(json.get("parkReason").asText()).isEqualTo("CHECK_FAILED"); + assertThat(json.get("portalUrl").asText()).isEqualTo("https://portal.example"); + assertThat(json.get("offlineReport").isNull()).isTrue(); + assertThat(json.get("offlineRunInProgress").asBoolean()).isFalse(); + assertThat(json.get("offlineRunError").isNull()).isTrue(); + } + + @Test + void testOnlyARecordedByHandRunOnTheReportStepCarriesTheReport() { + CommunityGrantFlowState flowState = CommunityGrantFlowState.initial(); + flowState.setState(CommunityGrantState.VALIDATING); + assertThat(CommunityGrantStateInfo.carriesOfflineReport(flowState)).isFalse(); + + flowState.setLastOfflineCheckAt(11L); + assertThat(CommunityGrantStateInfo.carriesOfflineReport(flowState)).isTrue(); + + flowState.setState(CommunityGrantState.COLLECTING); + assertThat(CommunityGrantStateInfo.carriesOfflineReport(flowState)).isFalse(); + flowState.setState(CommunityGrantState.REGISTERED); + assertThat(CommunityGrantStateInfo.carriesOfflineReport(flowState)).isFalse(); + } + + @Test + void testTheHandedOverStepKeepsCarryingTheReport() { + CommunityGrantFlowState flowState = CommunityGrantFlowState.initial(); + flowState.setState(CommunityGrantState.REPORT_HANDED_OVER); + flowState.setLastOfflineCheckAt(11L); + + assertThat(CommunityGrantStateInfo.carriesOfflineReport(flowState)).isTrue(); + } + +} diff --git a/application/src/test/java/org/thingsboard/server/service/community_grant/CommunityGrantStateTest.java b/application/src/test/java/org/thingsboard/server/service/community_grant/CommunityGrantStateTest.java new file mode 100644 index 0000000000..51e5b853b2 --- /dev/null +++ b/application/src/test/java/org/thingsboard/server/service/community_grant/CommunityGrantStateTest.java @@ -0,0 +1,48 @@ +// SPDX-FileCopyrightText: Copyright The Thingsboard Authors +// SPDX-License-Identifier: Apache-2.0 +package org.thingsboard.server.service.community_grant; + +import org.junit.jupiter.api.Test; +import org.thingsboard.server.common.data.community_grant.CommunityGrantState; + +import static org.assertj.core.api.Assertions.assertThat; + +class CommunityGrantStateTest { + + @Test + void testTerminalAndPollableFlags() { + assertThat(CommunityGrantState.REGISTERED.isTerminal()).isTrue(); + assertThat(CommunityGrantState.ALREADY_REGISTERED.isTerminal()).isTrue(); + assertThat(CommunityGrantState.WRONG_INSTALLATION.isTerminal()).isTrue(); + assertThat(CommunityGrantState.RESUME.isTerminal()).isFalse(); + assertThat(CommunityGrantState.RESUME.isPollable()).isFalse(); + assertThat(CommunityGrantState.NOT_STARTED.isPollable()).isFalse(); + assertThat(CommunityGrantState.AWAITING_SIGNUP.isPollable()).isTrue(); + assertThat(CommunityGrantState.COLLECTING.isPollable()).isTrue(); + assertThat(CommunityGrantState.VALIDATING.isPollable()).isTrue(); + } + + @Test + void testUnderReviewIsPollableAndNotTerminal() { + assertThat(CommunityGrantState.UNDER_REVIEW.isTerminal()).isFalse(); + assertThat(CommunityGrantState.UNDER_REVIEW.isPollable()).isTrue(); + } + + @Test + void testTheHandOverIsPolledAndIsNotAnEnding() { + assertThat(CommunityGrantState.REPORT_HANDED_OVER.isTerminal()).isFalse(); + assertThat(CommunityGrantState.REPORT_HANDED_OVER.isPollable()).isTrue(); + assertThat(CommunityGrantState.REPORT_HANDED_OVER.isAwaitingOrPastDecision()).isTrue(); + } + + @Test + void testAwaitingOrPastDecisionCoversTheDecidedStatesAndUnderReview() { + assertThat(CommunityGrantState.REGISTERED.isAwaitingOrPastDecision()).isTrue(); + assertThat(CommunityGrantState.ALREADY_REGISTERED.isAwaitingOrPastDecision()).isTrue(); + assertThat(CommunityGrantState.UNDER_REVIEW.isAwaitingOrPastDecision()).isTrue(); + assertThat(CommunityGrantState.VALIDATING.isAwaitingOrPastDecision()).isFalse(); + assertThat(CommunityGrantState.RESUME.isAwaitingOrPastDecision()).isFalse(); + assertThat(CommunityGrantState.NOT_STARTED.isAwaitingOrPastDecision()).isFalse(); + } + +} diff --git a/application/src/test/java/org/thingsboard/server/service/community_grant/CommunityGrantUploadPayloadLimitTest.java b/application/src/test/java/org/thingsboard/server/service/community_grant/CommunityGrantUploadPayloadLimitTest.java new file mode 100644 index 0000000000..7353c95711 --- /dev/null +++ b/application/src/test/java/org/thingsboard/server/service/community_grant/CommunityGrantUploadPayloadLimitTest.java @@ -0,0 +1,143 @@ +// SPDX-FileCopyrightText: Copyright The Thingsboard Authors +// SPDX-License-Identifier: Apache-2.0 +package org.thingsboard.server.service.community_grant; + +import jakarta.servlet.FilterChain; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; +import org.junit.jupiter.api.Test; +import org.thingsboard.server.transport.http.config.PayloadSizeFilter; + +import java.io.PrintWriter; +import java.io.StringWriter; +import java.nio.charset.StandardCharsets; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +/** + * The offline upload carries a whole checker, so it needs its own {@code server.http.max_payload_size} entry. + * Not a MockMvc test: a mock multipart request's content length does not reflect the parts attached to it. + */ +class CommunityGrantUploadPayloadLimitTest { + + private static final String OFFLINE_RUN_URI = "/api/communityGrant/offline/run"; + + private static final long API_DEFAULT_LIMIT = 16777216L; + + @Test + void testTheCheckerCapPlusTheBundlesOwnOverheadFitsUnderTheEndpointsEntry() { + assertThat(maxCheckerSizeFromYaml() + CommunityGrantOfflineBundle.MAX_OVERHEAD_BYTES) + .as("community-grant.max-checker-size-bytes plus the bundle header and manifest must leave " + + "room under the %s entry in server.http.max_payload_size, which is compared " + + "against the whole request body", OFFLINE_RUN_URI) + .isLessThan(limitFor(OFFLINE_RUN_URI)); + } + + @Test + void testABundleAtTheDocumentedMaximumReachesTheControllerRatherThanA413() throws Exception { + FilterChain chain = mock(FilterChain.class); + // With a writer, a 413 fails the assertions below instead of throwing an NPE inside the filter. + HttpServletResponse response = mockResponseWithWriter(); + + filter().doFilterInternal(requestOf(OFFLINE_RUN_URI, + maxCheckerSizeFromYaml() + CommunityGrantOfflineBundle.MAX_OVERHEAD_BYTES + 65536), response, chain); + + verify(chain).doFilter(any(), any()); + verify(response, never()).setStatus(413); + } + + @Test + void testABodyPastTheEndpointsOwnEntryIsStillRefused() throws Exception { + FilterChain chain = mock(FilterChain.class); + HttpServletResponse response = mockResponseWithWriter(); + + filter().doFilterInternal(requestOf(OFFLINE_RUN_URI, 64L * 1024 * 1024), response, chain); + + verify(chain, never()).doFilter(any(), any()); + verify(response).setStatus(413); + } + + @Test + void testEveryOtherApiPathKeepsTheStockSixteenMegabyteCap() throws Exception { + FilterChain chain = mock(FilterChain.class); + HttpServletResponse response = mockResponseWithWriter(); + + filter().doFilterInternal(requestOf("/api/plugins/telemetry/DEVICE/x/values/timeseries", + API_DEFAULT_LIMIT + 1), response, chain); + + verify(chain, never()).doFilter(any(), any()); + verify(response).setStatus(413); + } + + @Test + void testTheEndpointsEntryPrecedesTheCatchAllItWouldOtherwiseFallTo() { + String limits = payloadLimitsFromYaml(); + + int endpointEntry = limits.indexOf(OFFLINE_RUN_URI + "="); + int catchAllEntry = limits.indexOf("/api/**="); + + assertThat(endpointEntry).as("the offline upload needs its own entry in server.http.max_payload_size") + .isNotNegative(); + assertThat(endpointEntry).as("it is ignored unless it precedes /api/**, which matches the same URI") + .isLessThan(catchAllEntry); + } + + private static PayloadSizeFilter filter() { + return new PayloadSizeFilter(payloadLimitsFromYaml()); + } + + private static HttpServletRequest requestOf(String uri, long contentLength) { + HttpServletRequest request = mock(HttpServletRequest.class); + when(request.getRequestURI()).thenReturn(uri); + when(request.getContentLength()).thenReturn(Math.toIntExact(contentLength)); + return request; + } + + private static HttpServletResponse mockResponseWithWriter() throws Exception { + HttpServletResponse response = mock(HttpServletResponse.class); + when(response.getWriter()).thenReturn(new PrintWriter(new StringWriter())); + return response; + } + + private static long limitFor(String pattern) { + for (String entry : payloadLimitsFromYaml().split(";")) { + if (entry.startsWith(pattern + "=")) { + return Long.parseLong(entry.substring(pattern.length() + 1)); + } + } + throw new IllegalStateException("server.http.max_payload_size has no entry for " + pattern); + } + + private static long maxCheckerSizeFromYaml() { + return Long.parseLong(matchInYaml( + "max-checker-size-bytes:\\s*\"\\$\\{COMMUNITY_GRANT_MAX_CHECKER_SIZE_BYTES:(\\d+)}\"", + "community-grant.max-checker-size-bytes")); + } + + private static String payloadLimitsFromYaml() { + return matchInYaml("max_payload_size:\\s*\"\\$\\{HTTP_MAX_PAYLOAD_SIZE_LIMIT_CONFIGURATION:([^}]*)}\"", + "server.http.max_payload_size"); + } + + private static String matchInYaml(String regex, String property) { + String yaml; + try (var in = CommunityGrantUploadPayloadLimitTest.class.getResourceAsStream("/thingsboard.yml")) { + yaml = new String(in.readAllBytes(), StandardCharsets.UTF_8); + } catch (Exception e) { + throw new IllegalStateException("thingsboard.yml is not on the test classpath", e); + } + Matcher matcher = Pattern.compile(regex).matcher(yaml); + if (!matcher.find()) { + throw new IllegalStateException(property + " is not declared the way this test reads it"); + } + return matcher.group(1); + } + +} diff --git a/application/src/test/java/org/thingsboard/server/service/community_grant/DefaultCommunityGrantServiceConcurrencyTest.java b/application/src/test/java/org/thingsboard/server/service/community_grant/DefaultCommunityGrantServiceConcurrencyTest.java new file mode 100644 index 0000000000..f301dd4967 --- /dev/null +++ b/application/src/test/java/org/thingsboard/server/service/community_grant/DefaultCommunityGrantServiceConcurrencyTest.java @@ -0,0 +1,149 @@ +// SPDX-FileCopyrightText: Copyright The Thingsboard Authors +// SPDX-License-Identifier: Apache-2.0 +package org.thingsboard.server.service.community_grant; + +import com.google.common.util.concurrent.FluentFuture; +import org.junit.jupiter.api.Test; +import org.springframework.test.util.ReflectionTestUtils; +import org.thingsboard.server.common.data.AdminSettings; +import org.thingsboard.server.common.data.EntityType; +import org.thingsboard.server.common.data.community_grant.CommunityGrantMode; +import org.thingsboard.server.common.data.community_grant.CommunityGrantState; +import org.thingsboard.server.common.data.exception.ThingsboardException; +import org.thingsboard.server.common.data.id.AdminSettingsId; +import org.thingsboard.server.common.data.id.EntityId; +import org.thingsboard.server.common.data.id.HasId; +import org.thingsboard.server.common.data.id.TenantId; +import org.thingsboard.server.common.data.page.PageData; +import org.thingsboard.server.common.data.page.PageLink; +import org.thingsboard.server.dao.settings.AdminSettingsService; +import org.thingsboard.server.dao.subscription.TbClusterStore; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.UUID; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.CyclicBarrier; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.concurrent.TimeUnit; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +/** + * Uses a real {@link CommunityGrantFlowStateStore} over an in-memory settings map, so racing callers genuinely contend. + */ +class DefaultCommunityGrantServiceConcurrencyTest { + + private static final UUID CLUSTER_ID = UUID.randomUUID(); + private static final int THREADS = 8; + + @Test + void testConcurrentRequestAccessReachesThePortalExactlyOnce() throws Exception { + InMemoryAdminSettingsService adminSettingsService = new InMemoryAdminSettingsService(); + CommunityGrantFlowStateStore flowStateStore = new CommunityGrantFlowStateStore(adminSettingsService); + flowStateStore.update(state -> { + state.setMode(CommunityGrantMode.ONLINE); + state.setState(CommunityGrantState.ALREADY_REGISTERED); + return state; + }); + + TbClusterStore tbClusterStore = mock(TbClusterStore.class); + when(tbClusterStore.getClusterId()).thenReturn(Optional.of(CLUSTER_ID)); + CommunityGrantPortalClient portalClient = mock(CommunityGrantPortalClient.class); + CommunityGrantPoller poller = mock(CommunityGrantPoller.class); + CommunityGrantReportRunner reportRunner = mock(CommunityGrantReportRunner.class); + CommunityGrantOfflineReportStore offlineReportStore = + new CommunityGrantOfflineReportStore(adminSettingsService); + DefaultCommunityGrantService service = new DefaultCommunityGrantService( + tbClusterStore, flowStateStore, portalClient, poller, reportRunner, offlineReportStore); + ReflectionTestUtils.setField(service, "enabled", true); + + CyclicBarrier barrier = new CyclicBarrier(THREADS); + ExecutorService executor = Executors.newFixedThreadPool(THREADS); + try { + List> futures = new ArrayList<>(); + for (int i = 0; i < THREADS; i++) { + futures.add(executor.submit(() -> { + barrier.await(); + try { + service.requestAccess(); + } catch (ThingsboardException expectedForAllButOneCaller) { + } + return null; + })); + } + for (Future future : futures) { + future.get(10, TimeUnit.SECONDS); + } + } finally { + executor.shutdown(); + assertThat(executor.awaitTermination(10, TimeUnit.SECONDS)).isTrue(); + } + + verify(portalClient, times(1)).requestAccess(eq(CLUSTER_ID)); + } + + private static final class InMemoryAdminSettingsService implements AdminSettingsService { + + private final Map rows = new ConcurrentHashMap<>(); + + @Override + public AdminSettings findAdminSettingsByKey(TenantId tenantId, String key) { + return rows.get(key); + } + + @Override + public AdminSettings saveAdminSettings(TenantId tenantId, AdminSettings adminSettings) { + if (adminSettings.getId() == null) { + adminSettings.setId(new AdminSettingsId(UUID.randomUUID())); + } + rows.put(adminSettings.getKey(), adminSettings); + return adminSettings; + } + + @Override + public AdminSettings findAdminSettingsById(TenantId tenantId, AdminSettingsId adminSettingsId) { + throw new UnsupportedOperationException("Not used by CommunityGrantFlowStateStore"); + } + + @Override + public AdminSettings findAdminSettingsByTenantIdAndKey(TenantId tenantId, String key) { + throw new UnsupportedOperationException("Not used by CommunityGrantFlowStateStore"); + } + + @Override + public PageData findAllByTenantId(TenantId tenantId, PageLink pageLink) { + throw new UnsupportedOperationException("Not used by CommunityGrantFlowStateStore"); + } + + @Override + public boolean deleteAdminSettingsByTenantIdAndKey(TenantId tenantId, String key) { + throw new UnsupportedOperationException("Not used by CommunityGrantFlowStateStore"); + } + + @Override + public Optional> findEntity(TenantId tenantId, EntityId entityId) { + throw new UnsupportedOperationException("Not used by CommunityGrantFlowStateStore"); + } + + @Override + public FluentFuture>> findEntityAsync(TenantId tenantId, EntityId entityId) { + throw new UnsupportedOperationException("Not used by CommunityGrantFlowStateStore"); + } + + @Override + public EntityType getEntityType() { + throw new UnsupportedOperationException("Not used by CommunityGrantFlowStateStore"); + } + } + +} diff --git a/application/src/test/java/org/thingsboard/server/service/community_grant/DefaultCommunityGrantServiceTest.java b/application/src/test/java/org/thingsboard/server/service/community_grant/DefaultCommunityGrantServiceTest.java new file mode 100644 index 0000000000..456585c195 --- /dev/null +++ b/application/src/test/java/org/thingsboard/server/service/community_grant/DefaultCommunityGrantServiceTest.java @@ -0,0 +1,1171 @@ +// SPDX-FileCopyrightText: Copyright The Thingsboard Authors +// SPDX-License-Identifier: Apache-2.0 +package org.thingsboard.server.service.community_grant; + +import com.google.common.util.concurrent.MoreExecutors; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.EnumSource; +import org.mockito.ArgumentCaptor; +import org.mockito.InOrder; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; +import org.mockito.junit.jupiter.MockitoSettings; +import org.mockito.quality.Strictness; +import org.springframework.test.util.ReflectionTestUtils; +import org.thingsboard.server.common.data.community_grant.CommunityGrantFlowState; +import org.thingsboard.server.common.data.community_grant.CommunityGrantMode; +import org.thingsboard.server.common.data.community_grant.CommunityGrantOfflineRun; +import org.thingsboard.server.common.data.community_grant.CommunityGrantOfflineRunStatus; +import org.thingsboard.server.common.data.community_grant.CommunityGrantParkReason; +import org.thingsboard.server.common.data.community_grant.CommunityGrantState; +import org.thingsboard.server.common.data.community_grant.CommunityGrantStateInfo; +import org.thingsboard.server.common.data.exception.ThingsboardErrorCode; +import org.thingsboard.server.common.data.exception.ThingsboardException; +import org.thingsboard.server.dao.subscription.TbClusterStore; + +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; +import java.util.UUID; +import java.util.concurrent.AbstractExecutorService; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicReference; +import java.util.function.UnaryOperator; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.doAnswer; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.inOrder; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +@ExtendWith(MockitoExtension.class) +@MockitoSettings(strictness = Strictness.LENIENT) +class DefaultCommunityGrantServiceTest { + + private static final UUID CLUSTER_ID = UUID.randomUUID(); + private static final CommunityGrantCheckerInput CHECKER_INPUT = new CommunityGrantCheckerInput("{\"keyId\":7}"); + private static final int CHECKER_TIMEOUT_SEC = 600; + /** A run still marked running after this long has lost its node. */ + private static final long STALE_AFTER_MS = + TimeUnit.SECONDS.toMillis(CHECKER_TIMEOUT_SEC) + DefaultCommunityGrantService.OFFLINE_RUN_GRACE_MS; + + @Mock + private TbClusterStore tbClusterStore; + @Mock + private CommunityGrantFlowStateStore flowStateStore; + @Mock + private CommunityGrantPortalClient portalClient; + @Mock + private CommunityGrantPoller poller; + @Mock + private CommunityGrantReportRunner reportRunner; + @Mock + private CommunityGrantOfflineReportStore offlineReportStore; + + @InjectMocks + private DefaultCommunityGrantService service; + + private CommunityGrantFlowState stored; + /** What each background run reported on completion: {@code null} for a success. */ + private final List completion = new ArrayList<>(); + + @BeforeEach + void setUp() { + ReflectionTestUtils.setField(service, "enabled", true); + ReflectionTestUtils.setField(service, "offlineRunExecutor", MoreExecutors.newDirectExecutorService()); + when(reportRunner.getCheckerTimeoutSec()).thenReturn(CHECKER_TIMEOUT_SEC); + stored = CommunityGrantFlowState.initial(); + when(flowStateStore.get()).thenAnswer(invocation -> stored); + when(flowStateStore.update(any())).thenAnswer(invocation -> { + UnaryOperator updater = invocation.getArgument(0); + stored = updater.apply(stored); + return stored; + }); + when(tbClusterStore.getClusterId()).thenReturn(Optional.of(CLUSTER_ID)); + } + + private void givenReachablePortal() { + when(portalClient.isPortalReachable()).thenReturn(true); + when(portalClient.isAlreadyRegistered(CLUSTER_ID)).thenReturn(false); + givenSignUpUrl(); + } + + private void givenSignUpUrl() { + when(portalClient.buildSignUpUrl(any(), anyString(), any())).thenAnswer(invocation -> + signUpUrl(invocation.getArgument(1), invocation.getArgument(2))); + } + + private static String signUpUrl(String token, CommunityGrantMode mode) { + return "https://portal.example/signup?clusterId=" + CLUSTER_ID + "&claimToken=" + token + + (mode == CommunityGrantMode.OFFLINE ? "&offline=true" : ""); + } + + /** With the direct executor, the background run has finished by the time this returns. */ + private CommunityGrantStateInfo runChecker() throws ThingsboardException { + return service.runOfflineChecker(new byte[]{1}, new byte[]{2}, "checker", CHECKER_INPUT, completion::add); + } + + @Test + void testStateCarriesTheReportOnceAByHandRunHasBeenRecorded() { + stored.setState(CommunityGrantState.VALIDATING); + stored.setMode(CommunityGrantMode.OFFLINE); + stored.setLastOfflineCheckAt(System.currentTimeMillis()); + when(offlineReportStore.get()).thenReturn(Optional.of("report-body")); + + assertThat(service.getStateInfo().offlineReport()).isEqualTo("report-body"); + } + + @Test + void testStateCarriesNoReportBeforeAnyRun() { + stored.setState(CommunityGrantState.AWAITING_SIGNUP); + + assertThat(service.getStateInfo().offlineReport()).isNull(); + verifyNoInteractions(offlineReportStore); + } + + @Test + void testTheOnlineWaitCarriesNoReportAndNeverReadsTheStore() { + stored.setState(CommunityGrantState.VALIDATING); + stored.setMode(CommunityGrantMode.ONLINE); + + assertThat(service.getStateInfo().offlineReport()).isNull(); + verifyNoInteractions(offlineReportStore); + } + + @Test + void testStartClearsTheByHandRunTimestampSoNoReportLeaksIntoTheNextEnrollment() throws ThingsboardException { + stored.setState(CommunityGrantState.RESUME); + stored.setLastOfflineCheckAt(System.currentTimeMillis()); + givenReachablePortal(); + + service.start(); + + assertThat(stored.getLastOfflineCheckAt()).isNull(); + stored.setState(CommunityGrantState.VALIDATING); + assertThat(service.getStateInfo().offlineReport()).isNull(); + verify(offlineReportStore, never()).get(); + } + + @Test + void testTheStateCarriesThePortalThisDeploymentIsConfiguredAgainst() { + when(portalClient.getPortalUrl()).thenReturn("https://portal.staging.example"); + + assertThat(service.getStateInfo().portalUrl()).isEqualTo("https://portal.staging.example"); + } + + @Test + void testAnUnreadableReportStoreStillAnswersWithTheState() { + stored.setState(CommunityGrantState.VALIDATING); + stored.setLastOfflineCheckAt(System.currentTimeMillis()); + when(offlineReportStore.get()).thenThrow(new IllegalStateException("boom")); + + CommunityGrantStateInfo info = service.getStateInfo(); + + assertThat(info.state()).isEqualTo(CommunityGrantState.VALIDATING); + assertThat(info.offlineReport()).isNull(); + } + + @Test + void testStartAsksAboutTheInstallationBeforeMintingAToken() throws ThingsboardException { + givenReachablePortal(); + + CommunityGrantStateInfo info = service.start(); + + InOrder inOrder = inOrder(tbClusterStore, portalClient); + inOrder.verify(portalClient).isAlreadyRegistered(CLUSTER_ID); + inOrder.verify(tbClusterStore).saveLicenseClaimToken(anyString()); + assertThat(info.state()).isEqualTo(CommunityGrantState.AWAITING_SIGNUP); + assertThat(info.mode()).isEqualTo(CommunityGrantMode.ONLINE); + ArgumentCaptor tokenCaptor = ArgumentCaptor.forClass(String.class); + verify(tbClusterStore).saveLicenseClaimToken(tokenCaptor.capture()); + verify(portalClient).buildSignUpUrl(CLUSTER_ID, tokenCaptor.getValue(), CommunityGrantMode.ONLINE); + assertThat(info.signUpUrl()).isEqualTo(signUpUrl(tokenCaptor.getValue(), CommunityGrantMode.ONLINE)); + verify(poller).arm(); + } + + @Test + void testMintedTokenIsUrlSafeAndLongEnough() throws ThingsboardException { + givenReachablePortal(); + + service.start(); + + ArgumentCaptor tokenCaptor = ArgumentCaptor.forClass(String.class); + verify(tbClusterStore).saveLicenseClaimToken(tokenCaptor.capture()); + String token = tokenCaptor.getValue(); + assertThat(token).hasSize(43).matches("[A-Za-z0-9_-]+"); + } + + @Test + void testStartFallsBackToOfflineWhenThePortalIsUnreachable() throws ThingsboardException { + when(portalClient.isPortalReachable()).thenReturn(false); + givenSignUpUrl(); + + CommunityGrantStateInfo info = service.start(); + + assertThat(info.mode()).isEqualTo(CommunityGrantMode.OFFLINE); + assertThat(info.state()).isEqualTo(CommunityGrantState.AWAITING_SIGNUP); + ArgumentCaptor tokenCaptor = ArgumentCaptor.forClass(String.class); + verify(tbClusterStore).saveLicenseClaimToken(tokenCaptor.capture()); + verify(portalClient).buildSignUpUrl(CLUSTER_ID, tokenCaptor.getValue(), CommunityGrantMode.OFFLINE); + assertThat(info.signUpUrl()).isEqualTo(signUpUrl(tokenCaptor.getValue(), CommunityGrantMode.OFFLINE)); + verify(portalClient, never()).isAlreadyRegistered(any()); + // Armed offline too: the tick enforces the sign-up deadline. + verify(poller).arm(); + verify(poller, never()).disarm(); + } + + // Asserts the mode arm() reads when it is called, not just the order of the calls. + @Test + void testRecoveringFromOfflineToOnlineWritesTheNewModeBeforeArming() throws ThingsboardException { + stored.setMode(CommunityGrantMode.OFFLINE); + stored.setState(CommunityGrantState.AWAITING_SIGNUP); + givenReachablePortal(); + AtomicReference modeVisibleToArm = new AtomicReference<>(); + doAnswer(invocation -> { + modeVisibleToArm.set(flowStateStore.get().getMode()); + return null; + }).when(poller).arm(); + + CommunityGrantStateInfo info = service.start(); + + assertThat(info.mode()).isEqualTo(CommunityGrantMode.ONLINE); + verify(poller).arm(); + assertThat(modeVisibleToArm).hasValue(CommunityGrantMode.ONLINE); + } + + @Test + void testAStoreFailureOnTheAlreadyRegisteredPathIsReportedCleanly() { + when(portalClient.isPortalReachable()).thenReturn(true); + when(portalClient.isAlreadyRegistered(CLUSTER_ID)).thenReturn(true); + doThrow(new IllegalStateException("db down")).when(flowStateStore).update(any()); + + assertThatThrownBy(() -> service.start()) + .isInstanceOf(ThingsboardException.class) + .hasMessageContaining("Failed to start") + .hasNoCause(); + } + + @Test + void testStartStopsAtAlreadyRegisteredWithoutEverMintingAToken() throws ThingsboardException { + when(portalClient.isPortalReachable()).thenReturn(true); + when(portalClient.isAlreadyRegistered(CLUSTER_ID)).thenReturn(true); + + CommunityGrantStateInfo info = service.start(); + + assertThat(info.state()).isEqualTo(CommunityGrantState.ALREADY_REGISTERED); + assertThat(info.signUpUrl()).isNull(); + verify(tbClusterStore, never()).saveLicenseClaimToken(anyString()); + verify(tbClusterStore).forceClearLicenseClaimToken(); + verify(poller, never()).arm(); + verify(poller).disarm(); + } + + @Test + void testStartContinuesWhenTheClusterStatusCallFails() throws ThingsboardException { + when(portalClient.isPortalReachable()).thenReturn(true); + givenSignUpUrl(); + when(portalClient.isAlreadyRegistered(CLUSTER_ID)) + .thenThrow(new RuntimeException("portal hiccup")); + + CommunityGrantStateInfo info = service.start(); + + assertThat(info.state()).isEqualTo(CommunityGrantState.AWAITING_SIGNUP); + verify(poller).arm(); + } + + @Test + void testStartFailsWithoutAdvancingWhenTheTokenCannotBeStored() { + givenReachablePortal(); + doThrow(new IllegalStateException("empty table")).when(tbClusterStore).saveLicenseClaimToken(anyString()); + + assertThatThrownBy(() -> service.start()) + .isInstanceOf(ThingsboardException.class) + .hasMessageContaining("Failed to start") + .hasNoCause(); + + assertThat(stored.getState()).isEqualTo(CommunityGrantState.NOT_STARTED); + verify(poller, never()).arm(); + } + + @Test + void testStartClearsTheExactTokenWhenTheFlowStateCannotBePersisted() { + givenReachablePortal(); + // doThrow(): re-stubbing with when() would run setUp()'s answer with a null updater. + doThrow(new IllegalStateException("stored document is unreadable")).when(flowStateStore).update(any()); + + assertThatThrownBy(() -> service.start()).isInstanceOf(ThingsboardException.class).hasNoCause(); + + ArgumentCaptor tokenCaptor = ArgumentCaptor.forClass(String.class); + verify(tbClusterStore).saveLicenseClaimToken(tokenCaptor.capture()); + verify(tbClusterStore).clearLicenseClaimToken(tokenCaptor.getValue()); + verify(poller, never()).arm(); + } + + @Test + void testStartFailsCleanlyWhenThePortalBaseUrlIsMalformed() { + when(portalClient.isPortalReachable()).thenReturn(true); + when(portalClient.isAlreadyRegistered(CLUSTER_ID)).thenReturn(false); + when(portalClient.buildSignUpUrl(any(), anyString(), any())) + .thenThrow(new IllegalArgumentException("URI is not absolute")); + + assertThatThrownBy(() -> service.start()) + .isInstanceOf(ThingsboardException.class) + .hasMessageContaining("misconfigured") + .hasNoCause(); + + verify(tbClusterStore, never()).saveLicenseClaimToken(anyString()); + verify(tbClusterStore, never()).clearLicenseClaimToken(anyString()); + verify(poller, never()).arm(); + } + + @Test + void testStartFailsWhenTheDeploymentHasNoClusterId() { + when(tbClusterStore.getClusterId()).thenReturn(Optional.empty()); + + assertThatThrownBy(() -> service.start()).isInstanceOf(ThingsboardException.class); + verify(tbClusterStore, never()).saveLicenseClaimToken(anyString()); + } + + @Test + void testStartFromResumeMintsAFreshToken() throws ThingsboardException { + stored.setState(CommunityGrantState.RESUME); + givenReachablePortal(); + + CommunityGrantStateInfo info = service.start(); + + assertThat(info.state()).isEqualTo(CommunityGrantState.AWAITING_SIGNUP); + assertThat(info.signUpUrl()).contains("claimToken="); + } + + @Test + void testStartingAgainClearsTheParkReason() throws ThingsboardException { + givenReachablePortal(); + stored.setState(CommunityGrantState.RESUME); + stored.setParkReason(CommunityGrantParkReason.CHECK_FAILED); + + service.start(); + + assertThat(stored.getParkReason()).isNull(); + } + + // The pre-flight cannot say whose registration it found; on a flow begun here it is most likely this one's. + @Test + void testStartAgainOutOfAParkReMintsInsteadOfDeadEndingOnThePreFlight() throws ThingsboardException { + when(portalClient.isPortalReachable()).thenReturn(true); + givenSignUpUrl(); + stored.setState(CommunityGrantState.RESUME); + stored.setParkReason(CommunityGrantParkReason.LINK_EXPIRED); + + CommunityGrantStateInfo info = service.start(); + + assertThat(info.state()).isEqualTo(CommunityGrantState.AWAITING_SIGNUP); + assertThat(info.parkReason()).isNull(); + verify(portalClient, never()).isAlreadyRegistered(any()); + verify(tbClusterStore).saveLicenseClaimToken(anyString()); + } + + @Test + void testThePreFlightStillRefusesADeploymentThatHasNeverEnrolledFromHere() throws ThingsboardException { + when(portalClient.isPortalReachable()).thenReturn(true); + when(portalClient.isAlreadyRegistered(CLUSTER_ID)).thenReturn(true); + + CommunityGrantStateInfo info = service.start(); + + assertThat(info.state()).isEqualTo(CommunityGrantState.ALREADY_REGISTERED); + verify(tbClusterStore, never()).saveLicenseClaimToken(anyString()); + } + + @Test + void testStartIsRefusedOnATerminalState() { + stored.setState(CommunityGrantState.REGISTERED); + + assertThatThrownBy(() -> service.start()).isInstanceOf(ThingsboardException.class); + verify(tbClusterStore, never()).saveLicenseClaimToken(anyString()); + } + + @Test + void testStartIsRefusedWhileTheRegistrationIsUnderReview() { + stored.setState(CommunityGrantState.UNDER_REVIEW); + + assertThatThrownBy(() -> service.start()) + .isInstanceOf(ThingsboardException.class) + .hasMessage(DefaultCommunityGrantService.UNDER_REVIEW_MESSAGE); + verify(tbClusterStore, never()).saveLicenseClaimToken(anyString()); + verify(poller, never()).disarm(); + } + + @Test + void testStartIsRefusedWhenTheFeatureIsDisabled() { + ReflectionTestUtils.setField(service, "enabled", false); + + assertThatThrownBy(() -> service.start()).isInstanceOf(ThingsboardException.class); + verify(portalClient, never()).isPortalReachable(); + } + + @Test + void testStartingRetiresThePreviousRunsReport() throws ThingsboardException { + givenReachablePortal(); + + service.start(); + + verify(offlineReportStore).clear(); + } + + @Test + void testStartingAsAlreadyRegisteredRetiresThePreviousRunsReport() throws ThingsboardException { + when(portalClient.isPortalReachable()).thenReturn(true); + when(portalClient.isAlreadyRegistered(CLUSTER_ID)).thenReturn(true); + + CommunityGrantStateInfo info = service.start(); + + assertThat(info.state()).isEqualTo(CommunityGrantState.ALREADY_REGISTERED); + verify(offlineReportStore).clear(); + } + + @Test + void testAFailedStartLeavesTheReportAlone() { + givenReachablePortal(); + doThrow(new IllegalStateException("connection refused")).when(flowStateStore).update(any()); + + assertThatThrownBy(() -> service.start()).isInstanceOf(ThingsboardException.class); + + verify(offlineReportStore, never()).clear(); + } + + @Test + void testRunOfflineCheckerMovesToValidatingOnSuccess() throws ThingsboardException { + stored.setMode(CommunityGrantMode.OFFLINE); + when(reportRunner.runUploadedChecker(any(), any(), any(), any())) + .thenReturn("report-body"); + + runChecker(); + + verify(reportRunner).runUploadedChecker(any(), any(), any(), eq(CHECKER_INPUT)); + verify(offlineReportStore).put("report-body"); + assertThat(stored.getState()).isEqualTo(CommunityGrantState.VALIDATING); + assertThat(stored.getMode()).isEqualTo(CommunityGrantMode.OFFLINE); + assertThat(stored.getLastOfflineCheckAt()).isNotNull(); + } + + @Test + void testTheUploadAnswersWithARunInProgressAndTheReportArrivesThroughTheState() throws ThingsboardException { + stored.setMode(CommunityGrantMode.OFFLINE); + stored.setState(CommunityGrantState.AWAITING_SIGNUP); + ReflectionTestUtils.setField(service, "offlineRunExecutor", new QueuedExecutorService()); + when(reportRunner.runUploadedChecker(any(), any(), any(), any())).thenReturn("report-body"); + when(offlineReportStore.get()).thenReturn(Optional.of("report-body")); + + CommunityGrantStateInfo answer = runChecker(); + + assertThat(answer.offlineRunInProgress()).isTrue(); + assertThat(answer.offlineRunError()).isNull(); + verify(reportRunner).verifyUploadedChecker(any(), any(), any()); + verify(reportRunner, never()).runUploadedChecker(any(), any(), any(), any()); + assertThat(service.getStateInfo().offlineRunInProgress()).isTrue(); + + runQueuedTasks(); + + CommunityGrantStateInfo state = service.getStateInfo(); + assertThat(state.offlineRunInProgress()).isFalse(); + assertThat(state.offlineRunError()).isNull(); + assertThat(state.state()).isEqualTo(CommunityGrantState.VALIDATING); + assertThat(state.offlineReport()).isEqualTo("report-body"); + assertThat(stored.getOfflineRun()).isNull(); + assertThat(completion).containsExactly((Exception) null); + } + + @Test + void testAFailedRunIsReportedThroughTheState() throws ThingsboardException { + stored.setMode(CommunityGrantMode.OFFLINE); + stored.setState(CommunityGrantState.AWAITING_SIGNUP); + when(reportRunner.runUploadedChecker(any(), any(), any(), any())) + .thenThrow(new IllegalStateException("The instance check failed with exit code 3")); + + CommunityGrantStateInfo answer = runChecker(); + + assertThat(answer.offlineRunInProgress()).isTrue(); + CommunityGrantStateInfo state = service.getStateInfo(); + assertThat(state.offlineRunInProgress()).isFalse(); + assertThat(state.offlineRunError()) + .isEqualTo("Failed to run the check. The instance check failed with exit code 3"); + assertThat(state.state()).isEqualTo(CommunityGrantState.AWAITING_SIGNUP); + assertThat(stored.getOfflineRun().getStatus()).isEqualTo(CommunityGrantOfflineRunStatus.FAILED); + assertThat(completion).hasSize(1); + assertThat(completion.get(0)).isInstanceOf(ThingsboardException.class) + .hasMessage(state.offlineRunError()); + verify(offlineReportStore, never()).put(any()); + } + + @Test + void testARunningRecordPastItsTimeIsReportedAsInterrupted() { + long now = System.currentTimeMillis(); + stored.setOfflineRun(CommunityGrantOfflineRun.running(UUID.randomUUID(), now - STALE_AFTER_MS - 1000)); + + CommunityGrantStateInfo state = service.getStateInfo(); + + assertThat(state.offlineRunInProgress()).isFalse(); + assertThat(state.offlineRunError()).isEqualTo(DefaultCommunityGrantService.OFFLINE_RUN_INTERRUPTED_MESSAGE); + } + + @Test + void testARunningRecordWithinItsTimeIsReportedAsInProgress() { + long now = System.currentTimeMillis(); + stored.setOfflineRun(CommunityGrantOfflineRun.running(UUID.randomUUID(), now - STALE_AFTER_MS + 60_000)); + + CommunityGrantStateInfo state = service.getStateInfo(); + + assertThat(state.offlineRunInProgress()).isTrue(); + assertThat(state.offlineRunError()).isNull(); + } + + @Test + void testASecondStartIsRefusedWhileARunIsInProgress() { + UUID otherRun = UUID.randomUUID(); + stored.setOfflineRun(CommunityGrantOfflineRun.running(otherRun, System.currentTimeMillis())); + + assertThatThrownBy(this::runChecker) + .isInstanceOf(ThingsboardException.class) + .hasMessage(DefaultCommunityGrantService.OFFLINE_RUN_IN_PROGRESS_MESSAGE) + .satisfies(e -> assertThat(((ThingsboardException) e).getErrorCode()) + .isEqualTo(ThingsboardErrorCode.TOO_MANY_REQUESTS)); + + assertThat(stored.getOfflineRun().getRunId()).isEqualTo(otherRun); + assertThat(stored.getOfflineRun().getStatus()).isEqualTo(CommunityGrantOfflineRunStatus.RUNNING); + verify(reportRunner, never()).runUploadedChecker(any(), any(), any(), any()); + assertThat(completion).isEmpty(); + } + + @Test + void testAStaleRunDoesNotRefuseTheNextStart() throws ThingsboardException { + stored.setOfflineRun(CommunityGrantOfflineRun.running(UUID.randomUUID(), + System.currentTimeMillis() - STALE_AFTER_MS - 1000)); + when(reportRunner.runUploadedChecker(any(), any(), any(), any())).thenReturn("report-body"); + + runChecker(); + + verify(reportRunner).runUploadedChecker(any(), any(), any(), any()); + assertThat(stored.getOfflineRun()).isNull(); + } + + @Test + void testASecondStartOnTheSameNodeIsRefusedWhileItsRunIsQueued() throws ThingsboardException { + ReflectionTestUtils.setField(service, "offlineRunExecutor", new QueuedExecutorService()); + runChecker(); + // Stands in for another node's clear, so only the permit is left to refuse. + stored.setOfflineRun(null); + + assertThatThrownBy(this::runChecker) + .isInstanceOf(ThingsboardException.class) + .hasMessage(DefaultCommunityGrantService.OFFLINE_RUN_IN_PROGRESS_MESSAGE); + verify(reportRunner, times(1)).verifyUploadedChecker(any(), any(), any()); + } + + // Two starts on two nodes can both pass the per-node lock; the later record wins. + @Test + void testACompletionLeavesAnotherRunsRecordAlone() throws ThingsboardException { + ReflectionTestUtils.setField(service, "offlineRunExecutor", new QueuedExecutorService()); + when(reportRunner.runUploadedChecker(any(), any(), any(), any())) + .thenThrow(new IllegalStateException("The instance check failed with exit code 3")); + runChecker(); + UUID newerRun = UUID.randomUUID(); + stored.setOfflineRun(CommunityGrantOfflineRun.running(newerRun, System.currentTimeMillis())); + + runQueuedTasks(); + + assertThat(stored.getOfflineRun().getRunId()).isEqualTo(newerRun); + assertThat(stored.getOfflineRun().getStatus()).isEqualTo(CommunityGrantOfflineRunStatus.RUNNING); + assertThat(completion).hasSize(1); + } + + @Test + void testASupersededSuccessfulRunDiscardsItsResult() throws ThingsboardException { + stored.setMode(CommunityGrantMode.OFFLINE); + stored.setState(CommunityGrantState.AWAITING_SIGNUP); + ReflectionTestUtils.setField(service, "offlineRunExecutor", new QueuedExecutorService()); + when(reportRunner.runUploadedChecker(any(), any(), any(), any())).thenReturn("report-body"); + runChecker(); + UUID newerRun = UUID.randomUUID(); + stored.setOfflineRun(CommunityGrantOfflineRun.running(newerRun, System.currentTimeMillis())); + + runQueuedTasks(); + + assertThat(stored.getOfflineRun().getRunId()).isEqualTo(newerRun); + assertThat(stored.getOfflineRun().getStatus()).isEqualTo(CommunityGrantOfflineRunStatus.RUNNING); + assertThat(stored.getState()).isEqualTo(CommunityGrantState.AWAITING_SIGNUP); + assertThat(stored.getLastOfflineCheckAt()).isNull(); + verify(offlineReportStore, never()).put(any()); + assertThat(completion).hasSize(1); + assertThat(completion.get(0)).hasMessage(DefaultCommunityGrantService.OFFLINE_RUN_SUPERSEDED_MESSAGE); + } + + @Test + void testARunThatAStartReplacedDiscardsItsResult() throws ThingsboardException { + givenReachablePortal(); + stored.setMode(CommunityGrantMode.OFFLINE); + stored.setState(CommunityGrantState.AWAITING_SIGNUP); + ReflectionTestUtils.setField(service, "offlineRunExecutor", new QueuedExecutorService()); + when(reportRunner.runUploadedChecker(any(), any(), any(), any())).thenReturn("report-body"); + runChecker(); + + service.start(); + runQueuedTasks(); + + assertThat(stored.getState()).isEqualTo(CommunityGrantState.AWAITING_SIGNUP); + assertThat(stored.getOfflineRun()).isNull(); + assertThat(stored.getLastOfflineCheckAt()).isNull(); + verify(offlineReportStore, never()).put(any()); + assertThat(completion).hasSize(1); + assertThat(completion.get(0)).hasMessage(DefaultCommunityGrantService.OFFLINE_RUN_SUPERSEDED_MESSAGE); + } + + @Test + void testAStartLandingBetweenTheOwnershipCheckAndTheWriteLeavesTheStateAlone() throws ThingsboardException { + stored.setMode(CommunityGrantMode.OFFLINE); + stored.setState(CommunityGrantState.AWAITING_SIGNUP); + when(reportRunner.runUploadedChecker(any(), any(), any(), any())).thenReturn("report-body"); + // Stands in for a start() clearing the record right after the report was put. + doAnswer(invocation -> { + stored.setOfflineRun(null); + return null; + }).when(offlineReportStore).put(any()); + + runChecker(); + + assertThat(stored.getState()).isEqualTo(CommunityGrantState.AWAITING_SIGNUP); + assertThat(stored.getLastOfflineCheckAt()).isNull(); + assertThat(completion.get(0)).hasMessage(DefaultCommunityGrantService.OFFLINE_RUN_SUPERSEDED_MESSAGE); + } + + @Test + void testARunThatCannotBeScheduledIsRecordedAsFailedAndReleasesThePermit() throws ThingsboardException { + ExecutorService rejecting = MoreExecutors.newDirectExecutorService(); + rejecting.shutdown(); + ReflectionTestUtils.setField(service, "offlineRunExecutor", rejecting); + + assertThatThrownBy(this::runChecker) + .isInstanceOf(ThingsboardException.class) + .hasMessage(DefaultCommunityGrantService.OFFLINE_RUN_NOT_SCHEDULED_MESSAGE); + + assertThat(stored.getOfflineRun().getStatus()).isEqualTo(CommunityGrantOfflineRunStatus.FAILED); + assertThat(stored.getOfflineRun().getError()) + .isEqualTo(DefaultCommunityGrantService.OFFLINE_RUN_NOT_SCHEDULED_MESSAGE); + assertThat(service.getStateInfo().offlineRunError()) + .isEqualTo(DefaultCommunityGrantService.OFFLINE_RUN_NOT_SCHEDULED_MESSAGE); + + ReflectionTestUtils.setField(service, "offlineRunExecutor", MoreExecutors.newDirectExecutorService()); + when(reportRunner.runUploadedChecker(any(), any(), any(), any())).thenReturn("report-body"); + runChecker(); + + verify(reportRunner).runUploadedChecker(any(), any(), any(), any()); + } + + @Test + void testStartClearsTheOfflineRun() throws ThingsboardException { + givenReachablePortal(); + stored.setState(CommunityGrantState.AWAITING_SIGNUP); + stored.setOfflineRun(CommunityGrantOfflineRun.running(UUID.randomUUID(), System.currentTimeMillis())); + + service.start(); + + assertThat(stored.getOfflineRun()).isNull(); + } + + @Test + void testARefusedBundleRecordsNoRun() { + doThrow(new IllegalArgumentException("The uploaded checker does not match its release signature")) + .when(reportRunner).verifyUploadedChecker(any(), any(), any()); + + assertThatThrownBy(this::runChecker) + .isInstanceOf(ThingsboardException.class) + .hasMessage("The uploaded checker does not match its release signature") + .satisfies(e -> assertThat(((ThingsboardException) e).getErrorCode()) + .isEqualTo(ThingsboardErrorCode.BAD_REQUEST_PARAMS)); + + assertThat(stored.getOfflineRun()).isNull(); + verify(reportRunner, never()).runUploadedChecker(any(), any(), any(), any()); + assertThat(completion).isEmpty(); + } + + @Test + void testARefusedBundleReleasesThePermit() throws ThingsboardException { + doThrow(new IllegalArgumentException("refused")).doNothing() + .when(reportRunner).verifyUploadedChecker(any(), any(), any()); + when(reportRunner.runUploadedChecker(any(), any(), any(), any())).thenReturn("report-body"); + + assertThatThrownBy(this::runChecker).isInstanceOf(ThingsboardException.class); + runChecker(); + + verify(reportRunner).runUploadedChecker(any(), any(), any(), any()); + } + + private void runQueuedTasks() { + ExecutorService executor = (ExecutorService) ReflectionTestUtils.getField(service, "offlineRunExecutor"); + ((QueuedExecutorService) executor).runAll(); + } + + @Test + void testRunOfflineCheckerIsRefusedWhenTheFeatureIsDisabled() { + ReflectionTestUtils.setField(service, "enabled", false); + + assertThatThrownBy(this::runChecker) + .isInstanceOf(ThingsboardException.class) + .hasMessageContaining("not available on this deployment"); + verifyNoInteractions(reportRunner); + } + + @Test + void testRunOfflineCheckerPreservesAnAlreadyOnlineMode() throws ThingsboardException { + stored.setMode(CommunityGrantMode.ONLINE); + stored.setState(CommunityGrantState.COLLECTING); + when(reportRunner.runUploadedChecker(any(), any(), any(), any())) + .thenReturn("report-body"); + + runChecker(); + + assertThat(stored.getMode()).isEqualTo(CommunityGrantMode.ONLINE); + assertThat(stored.getState()).isEqualTo(CommunityGrantState.VALIDATING); + } + + // The audit log renders the whole cause chain, so no cause may be attached. + @Test + void testOfflineStateWriteFailureIsReportedCleanlyWithoutACause() throws ThingsboardException { + stored.setMode(CommunityGrantMode.OFFLINE); + when(reportRunner.runUploadedChecker(any(), any(), any(), any())) + .thenReturn("report-body"); + failUpdatesAfterTheFirst(new IllegalStateException( + "connection refused: jdbc:postgresql://db.internal:5432/tb?user=tb&password=hunter2")); + + runChecker(); + + assertThat(completion).hasSize(1); + assertThat(completion.get(0)) + .isInstanceOf(ThingsboardException.class) + .hasMessage(DefaultCommunityGrantService.OFFLINE_STATE_NOT_PERSISTED_MESSAGE) + .hasNoCause() + .satisfies(e -> { + assertThat(e.getMessage()).doesNotContain("hunter2"); + assertThat(e.getMessage()).doesNotContain("jdbc:postgresql"); + }); + } + + @Test + void testTheReportIsStoredEvenWhenTheStateWriteFails() throws ThingsboardException { + stored.setMode(CommunityGrantMode.OFFLINE); + when(reportRunner.runUploadedChecker(any(), any(), any(), any())).thenReturn("report-body"); + failUpdatesAfterTheFirst(new IllegalStateException("connection refused")); + + runChecker(); + + assertThat(completion.get(0)).isInstanceOf(ThingsboardException.class); + verify(offlineReportStore).put("report-body"); + } + + @Test + void testAFailedReadAfterTheRunStoresNothingAndPromisesNoDownload() throws ThingsboardException { + stored.setMode(CommunityGrantMode.OFFLINE); + stored.setState(CommunityGrantState.AWAITING_SIGNUP); + when(reportRunner.runUploadedChecker(any(), any(), any(), any())).thenAnswer(invocation -> { + // The checker has run; the database goes away before its result is recorded. + doThrow(new IllegalStateException("connection refused: jdbc:postgresql://db.internal:5432/tb")) + .when(flowStateStore).get(); + return "report-body"; + }); + + runChecker(); + + verify(offlineReportStore, never()).put(any()); + assertThat(stored.getState()).isEqualTo(CommunityGrantState.AWAITING_SIGNUP); + assertThat(stored.getOfflineRun().getError()) + .isEqualTo(DefaultCommunityGrantService.OFFLINE_RESULT_NOT_RECORDED_MESSAGE) + .doesNotContain("download"); + assertThat(completion.get(0)) + .hasMessage(DefaultCommunityGrantService.OFFLINE_RESULT_NOT_RECORDED_MESSAGE) + .hasNoCause(); + } + + @Test + void testAStartThatCannotBeRecordedIsRefusedWithoutACause() { + doThrow(new IllegalStateException("connection refused: jdbc:postgresql://db.internal:5432/tb")) + .when(flowStateStore).update(any()); + + assertThatThrownBy(this::runChecker) + .isInstanceOf(ThingsboardException.class) + .hasMessage(DefaultCommunityGrantService.OFFLINE_RUN_START_FAILED_MESSAGE) + .hasNoCause(); + + verify(reportRunner, never()).runUploadedChecker(any(), any(), any(), any()); + assertThat(completion).isEmpty(); + } + + @Test + void testRunOfflineCheckerDoesNotAdvanceTheStateWhenTheRunFails() throws ThingsboardException { + stored.setState(CommunityGrantState.AWAITING_SIGNUP); + stored.setMode(CommunityGrantMode.OFFLINE); + when(reportRunner.runUploadedChecker(any(), any(), any(), any())) + .thenThrow(new IllegalArgumentException("the uploaded checker does not match its release signature")); + + runChecker(); + + assertThat(stored.getState()).isEqualTo(CommunityGrantState.AWAITING_SIGNUP); + assertThat(stored.getLastOfflineCheckAt()).isNull(); + assertThat(stored.getOfflineRun().getError()) + .isEqualTo("the uploaded checker does not match its release signature"); + verify(offlineReportStore, never()).put(any()); + } + + /** The first write - the one recording the start - lands; every later one throws {@code failure}. */ + private void failUpdatesAfterTheFirst(RuntimeException failure) { + AtomicInteger calls = new AtomicInteger(); + doAnswer(invocation -> { + if (calls.incrementAndGet() > 1) { + throw failure; + } + UnaryOperator updater = invocation.getArgument(0); + stored = updater.apply(stored); + return stored; + }).when(flowStateStore).update(any()); + } + + @Test + void testRunOfflineCheckerCanBeRunAgainFromValidating() throws ThingsboardException { + stored.setState(CommunityGrantState.VALIDATING); + stored.setMode(CommunityGrantMode.OFFLINE); + when(reportRunner.runUploadedChecker(any(), any(), any(), any())) + .thenReturn("second-report-body"); + + runChecker(); + + verify(offlineReportStore).put("second-report-body"); + assertThat(stored.getState()).isEqualTo(CommunityGrantState.VALIDATING); + } + + @Test + void testRunOfflineCheckerFromAParkedResumeClearsTheParkReason() throws ThingsboardException { + stored.setState(CommunityGrantState.RESUME); + stored.setParkReason(CommunityGrantParkReason.LINK_EXPIRED); + stored.setMode(CommunityGrantMode.OFFLINE); + when(reportRunner.runUploadedChecker(any(), any(), any(), any())) + .thenReturn("report-body"); + + runChecker(); + + assertThat(stored.getState()).isEqualTo(CommunityGrantState.VALIDATING); + assertThat(stored.getParkReason()).isNull(); + } + + @Test + void testRunOfflineCheckerLeavesATerminalStateAlone() throws ThingsboardException { + stored.setState(CommunityGrantState.ALREADY_REGISTERED); + stored.setMode(CommunityGrantMode.OFFLINE); + when(reportRunner.runUploadedChecker(any(), any(), any(), any())) + .thenReturn("report-body"); + + runChecker(); + + verify(offlineReportStore).put("report-body"); + assertThat(stored.getState()).isEqualTo(CommunityGrantState.ALREADY_REGISTERED); + assertThat(stored.getLastOfflineCheckAt()).isNotNull(); + } + + @Test + void testRunOfflineCheckerLeavesAnUnderReviewFlowAlone() throws ThingsboardException { + stored.setState(CommunityGrantState.UNDER_REVIEW); + stored.setMode(CommunityGrantMode.OFFLINE); + when(reportRunner.runUploadedChecker(any(), any(), any(), any())) + .thenReturn("report-body"); + + runChecker(); + + verify(offlineReportStore).put("report-body"); + assertThat(stored.getState()).isEqualTo(CommunityGrantState.UNDER_REVIEW); + } + + @Test + void testRequestAccessIsRefusedOnTheWrongInstallationRefusal() { + stored.setState(CommunityGrantState.WRONG_INSTALLATION); + + assertThatThrownBy(() -> service.requestAccess()) + .isInstanceOf(ThingsboardException.class) + .hasMessage(DefaultCommunityGrantService.NOT_ALREADY_REGISTERED_MESSAGE); + verifyNoInteractions(portalClient); + } + + @Test + void testRequestAccessCallsThePortalWithTheClusterId() throws ThingsboardException { + stored.setState(CommunityGrantState.ALREADY_REGISTERED); + + service.requestAccess(); + + verify(portalClient).requestAccess(CLUSTER_ID); + } + + @Test + void testRequestAccessFailsCleanlyWhenThePortalCallFails() { + stored.setState(CommunityGrantState.ALREADY_REGISTERED); + doThrow(new RuntimeException("connect timed out")).when(portalClient).requestAccess(CLUSTER_ID); + + assertThatThrownBy(() -> service.requestAccess()) + .isInstanceOf(ThingsboardException.class) + .hasMessage(DefaultCommunityGrantService.REQUEST_ACCESS_FAILED_MESSAGE); + } + + @Test + void testRequestAccessIsRefusedWhenNotAlreadyRegistered() { + stored.setState(CommunityGrantState.AWAITING_SIGNUP); + + assertThatThrownBy(() -> service.requestAccess()) + .isInstanceOf(ThingsboardException.class) + .hasMessage(DefaultCommunityGrantService.NOT_ALREADY_REGISTERED_MESSAGE); + verify(portalClient, never()).requestAccess(any()); + } + + @Test + void testRequestAccessIsRefusedWhenTheFeatureIsDisabled() { + ReflectionTestUtils.setField(service, "enabled", false); + stored.setState(CommunityGrantState.ALREADY_REGISTERED); + + assertThatThrownBy(() -> service.requestAccess()).isInstanceOf(ThingsboardException.class); + verify(portalClient, never()).requestAccess(any()); + } + + @Test + void testRequestAccessIsRateLimitedWithinCooldownWindow() { + stored.setState(CommunityGrantState.ALREADY_REGISTERED); + stored.setLastRequestAccessAt(System.currentTimeMillis() - 1000); + + assertThatThrownBy(() -> service.requestAccess()) + .isInstanceOf(ThingsboardException.class) + .hasMessage(DefaultCommunityGrantService.REQUEST_ACCESS_RATE_LIMITED_MESSAGE); + verify(portalClient, never()).requestAccess(any()); + } + + @Test + void testRequestAccessIsAllowedAfterTheCooldownWindowElapses() throws ThingsboardException { + stored.setState(CommunityGrantState.ALREADY_REGISTERED); + stored.setLastRequestAccessAt(System.currentTimeMillis() + - DefaultCommunityGrantService.REQUEST_ACCESS_COOLDOWN_MS - 1000); + + service.requestAccess(); + + verify(portalClient).requestAccess(CLUSTER_ID); + } + + @Test + void testRequestAccessRecordsTheTimestampEvenWhenThePortalCallFails() { + stored.setState(CommunityGrantState.ALREADY_REGISTERED); + doThrow(new RuntimeException("connect timed out")).when(portalClient).requestAccess(CLUSTER_ID); + + assertThatThrownBy(() -> service.requestAccess()).isInstanceOf(ThingsboardException.class); + + assertThat(stored.getLastRequestAccessAt()).isNotNull(); + } + + @Test + void testRequestAccessFailsWhenTheDeploymentHasNoClusterId() { + stored.setState(CommunityGrantState.ALREADY_REGISTERED); + when(tbClusterStore.getClusterId()).thenReturn(Optional.empty()); + + assertThatThrownBy(() -> service.requestAccess()) + .isInstanceOf(ThingsboardException.class) + .hasMessage(DefaultCommunityGrantService.NO_CLUSTER_ID_MESSAGE); + verify(portalClient, never()).requestAccess(any()); + } + + @Test + void testRequestAccessFailsCleanlyWhenTheFlowStateCannotBePersisted() { + stored.setState(CommunityGrantState.ALREADY_REGISTERED); + doThrow(new IllegalStateException("stored document is unreadable")).when(flowStateStore).update(any()); + + assertThatThrownBy(() -> service.requestAccess()) + .isInstanceOf(ThingsboardException.class) + .hasMessage(DefaultCommunityGrantService.REQUEST_ACCESS_STORE_FAILED_MESSAGE) + .hasNoCause(); + verify(portalClient, never()).requestAccess(any()); + } + + @Test + void testRequestAccessFailsCleanlyWhenTheClusterIdLookupFails() { + stored.setState(CommunityGrantState.ALREADY_REGISTERED); + when(tbClusterStore.getClusterId()).thenThrow(new RuntimeException("connection refused")); + + assertThatThrownBy(() -> service.requestAccess()) + .isInstanceOf(ThingsboardException.class) + .hasMessage(DefaultCommunityGrantService.REQUEST_ACCESS_STORE_FAILED_MESSAGE); + verify(portalClient, never()).requestAccess(any()); + verify(flowStateStore, never()).update(any()); + } + + @Test + void testGetOfflineReportReturnsTheStoredReportVerbatim() throws ThingsboardException { + when(offlineReportStore.get()).thenReturn(Optional.of("-----BEGIN TB INSTANCE CHECK-----\nbody")); + + assertThat(service.getOfflineReport()).isEqualTo("-----BEGIN TB INSTANCE CHECK-----\nbody"); + } + + @Test + void testGetOfflineReportRefusesWhenNoCheckHasRun() { + when(offlineReportStore.get()).thenReturn(Optional.empty()); + + assertThatThrownBy(() -> service.getOfflineReport()) + .isInstanceOf(ThingsboardException.class) + .hasMessage(DefaultCommunityGrantService.NO_OFFLINE_REPORT_MESSAGE) + .extracting(e -> ((ThingsboardException) e).getErrorCode()) + .isEqualTo(ThingsboardErrorCode.ITEM_NOT_FOUND); + } + + @Test + void testConfirmOfflineHandoffRecordsTheClaimAndAnswersWithTheReport() throws ThingsboardException { + stored.setState(CommunityGrantState.VALIDATING); + stored.setMode(CommunityGrantMode.OFFLINE); + stored.setLastOfflineCheckAt(System.currentTimeMillis()); + when(offlineReportStore.get()).thenReturn(Optional.of("report-body")); + + CommunityGrantStateInfo info = service.confirmOfflineHandoff(); + + assertThat(stored.getState()).isEqualTo(CommunityGrantState.REPORT_HANDED_OVER); + assertThat(info.state()).isEqualTo(CommunityGrantState.REPORT_HANDED_OVER); + assertThat(info.offlineReport()).isEqualTo("report-body"); + // Online the poller is already armed; offline it stays disarmed. + verifyNoInteractions(poller); + } + + @Test + void testConfirmOfflineHandoffIsIdempotent() throws ThingsboardException { + stored.setState(CommunityGrantState.REPORT_HANDED_OVER); + stored.setLastOfflineCheckAt(System.currentTimeMillis()); + when(offlineReportStore.get()).thenReturn(Optional.of("report-body")); + + CommunityGrantStateInfo info = service.confirmOfflineHandoff(); + + assertThat(info.state()).isEqualTo(CommunityGrantState.REPORT_HANDED_OVER); + assertThat(info.offlineReport()).isEqualTo("report-body"); + verify(flowStateStore, never()).update(any()); + } + + @ParameterizedTest + @EnumSource(value = CommunityGrantState.class, mode = EnumSource.Mode.EXCLUDE, + names = {"VALIDATING", "REPORT_HANDED_OVER"}) + void testConfirmOfflineHandoffIsRefusedFromEveryOtherState(CommunityGrantState state) { + stored.setState(state); + + assertThatThrownBy(() -> service.confirmOfflineHandoff()) + .isInstanceOf(ThingsboardException.class) + .hasMessage(DefaultCommunityGrantService.NOTHING_TO_HAND_OVER_MESSAGE); + verify(flowStateStore, never()).update(any()); + } + + @Test + void testConfirmOfflineHandoffIsRefusedWhenTheFeatureIsDisabled() { + ReflectionTestUtils.setField(service, "enabled", false); + stored.setState(CommunityGrantState.VALIDATING); + + assertThatThrownBy(() -> service.confirmOfflineHandoff()) + .isInstanceOf(ThingsboardException.class) + .hasMessage(DefaultCommunityGrantService.NOT_AVAILABLE_MESSAGE) + .extracting(e -> ((ThingsboardException) e).getErrorCode()) + .isEqualTo(ThingsboardErrorCode.ITEM_NOT_FOUND); + verify(flowStateStore, never()).update(any()); + } + + // A poll can land between this call's read and write; the updater re-tests under the store's lock. + @Test + void testConfirmOfflineHandoffLosesToADecisionThatLandsMidCall() throws ThingsboardException { + stored.setState(CommunityGrantState.VALIDATING); + doAnswer(invocation -> { + // The poller's retire() landing between the read and the write. + stored.setState(CommunityGrantState.REGISTERED); + UnaryOperator updater = invocation.getArgument(0); + stored = updater.apply(stored); + return stored; + }).when(flowStateStore).update(any()); + + CommunityGrantStateInfo info = service.confirmOfflineHandoff(); + + assertThat(stored.getState()).isEqualTo(CommunityGrantState.REGISTERED); + assertThat(info.state()).isEqualTo(CommunityGrantState.REGISTERED); + } + + @Test + void testConfirmOfflineHandoffFailsCleanlyWhenTheFlowStateCannotBePersisted() { + stored.setState(CommunityGrantState.VALIDATING); + doThrow(new IllegalStateException("connection refused")).when(flowStateStore).update(any()); + + assertThatThrownBy(() -> service.confirmOfflineHandoff()) + .isInstanceOf(ThingsboardException.class) + .hasMessage(DefaultCommunityGrantService.HANDOFF_FAILED_MESSAGE) + .hasNoCause(); + } + + @Test + void testStartIsRefusedAfterTheReportHasBeenHandedOverAndLeavesTheReportInPlace() { + stored.setState(CommunityGrantState.REPORT_HANDED_OVER); + stored.setMode(CommunityGrantMode.OFFLINE); + stored.setLastOfflineCheckAt(System.currentTimeMillis()); + givenReachablePortal(); + when(offlineReportStore.get()).thenReturn(Optional.of("report-body")); + + assertThatThrownBy(() -> service.start()) + .isInstanceOf(ThingsboardException.class) + .hasMessage(DefaultCommunityGrantService.REPORT_HANDED_OVER_MESSAGE); + + verify(offlineReportStore, never()).clear(); + verify(tbClusterStore, never()).saveLicenseClaimToken(anyString()); + assertThat(stored.getState()).isEqualTo(CommunityGrantState.REPORT_HANDED_OVER); + assertThat(service.getStateInfo().offlineReport()).isEqualTo("report-body"); + } + + /** Holds submitted tasks until the test runs them, so a test can act between a start and its completion. */ + private static final class QueuedExecutorService extends AbstractExecutorService { + private final List tasks = new ArrayList<>(); + + void runAll() { + List queued = new ArrayList<>(tasks); + tasks.clear(); + queued.forEach(Runnable::run); + } + + @Override + public void execute(Runnable command) { + tasks.add(command); + } + + @Override + public void shutdown() { + } + + @Override + public List shutdownNow() { + return List.of(); + } + + @Override + public boolean isShutdown() { + return false; + } + + @Override + public boolean isTerminated() { + return false; + } + + @Override + public boolean awaitTermination(long timeout, TimeUnit unit) { + return true; + } + } + +} diff --git a/application/src/test/java/org/thingsboard/server/service/install/AbstractInstallPostgresTest.java b/application/src/test/java/org/thingsboard/server/service/install/AbstractInstallPostgresTest.java new file mode 100644 index 0000000000..107b858cab --- /dev/null +++ b/application/src/test/java/org/thingsboard/server/service/install/AbstractInstallPostgresTest.java @@ -0,0 +1,34 @@ +// SPDX-FileCopyrightText: Copyright The Thingsboard Authors +// SPDX-License-Identifier: Apache-2.0 +package org.thingsboard.server.service.install; + +import org.junit.jupiter.api.BeforeAll; +import org.testcontainers.containers.PostgreSQLContainer; + +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.SQLException; +import java.sql.Statement; + +abstract class AbstractInstallPostgresTest { + + private static final String POSTGRES_IMAGE = "postgres:18"; + + protected static PostgreSQLContainer postgres; + + @BeforeAll + static void startDatabase() { + if (postgres == null) { + postgres = new PostgreSQLContainer<>(POSTGRES_IMAGE); + postgres.start(); + } + } + + protected static void execute(String sql) throws SQLException { + try (Connection conn = DriverManager.getConnection(postgres.getJdbcUrl(), postgres.getUsername(), postgres.getPassword()); + Statement statement = conn.createStatement()) { + statement.execute(sql); + } + } + +} diff --git a/application/src/test/java/org/thingsboard/server/service/install/InstallTestSupport.java b/application/src/test/java/org/thingsboard/server/service/install/InstallTestSupport.java new file mode 100644 index 0000000000..4c4ee42e6c --- /dev/null +++ b/application/src/test/java/org/thingsboard/server/service/install/InstallTestSupport.java @@ -0,0 +1,60 @@ +// SPDX-FileCopyrightText: Copyright The Thingsboard Authors +// SPDX-License-Identifier: Apache-2.0 +package org.thingsboard.server.service.install; + +import java.io.IOException; +import java.io.InputStream; +import java.io.UncheckedIOException; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.ArrayList; +import java.util.List; +import java.util.Objects; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +final class InstallTestSupport { + + private static final Pattern TB_CLUSTER_DDL = Pattern.compile( + "^\\s*(CREATE\\s+(?:TABLE|UNIQUE\\s+INDEX)[^;]*\\btb_cluster\\b[^;]*;)", + Pattern.CASE_INSENSITIVE | Pattern.MULTILINE); + + private InstallTestSupport() { + } + + // The working directory is either the repository root or the application module, depending on how tests are run. + static Path dataDir() { + String workDir = System.getProperty("user.dir"); + Path applicationDir = workDir.endsWith("application") ? Paths.get(workDir) : Paths.get(workDir, "application"); + return applicationDir.resolve(Paths.get("src", "main", "data")); + } + + static String readFile(Path path) { + try { + return Files.readString(path); + } catch (IOException e) { + throw new UncheckedIOException("Failed to read " + path, e); + } + } + + static String readResource(String name) { + try (InputStream in = InstallTestSupport.class.getClassLoader().getResourceAsStream(name)) { + return new String(Objects.requireNonNull(in, name + " is missing from the test classpath").readAllBytes(), + StandardCharsets.UTF_8); + } catch (IOException e) { + throw new UncheckedIOException("Failed to read " + name, e); + } + } + + static List tbClusterStatements(String sql) { + List statements = new ArrayList<>(); + Matcher matcher = TB_CLUSTER_DDL.matcher(sql); + while (matcher.find()) { + statements.add(matcher.group(1)); + } + return statements; + } + +} diff --git a/application/src/test/java/org/thingsboard/server/service/install/SchemaUpdateSqlUpgradeOrderTest.java b/application/src/test/java/org/thingsboard/server/service/install/SchemaUpdateSqlUpgradeOrderTest.java new file mode 100644 index 0000000000..3f061e7bd4 --- /dev/null +++ b/application/src/test/java/org/thingsboard/server/service/install/SchemaUpdateSqlUpgradeOrderTest.java @@ -0,0 +1,60 @@ +// SPDX-FileCopyrightText: Copyright The Thingsboard Authors +// SPDX-License-Identifier: Apache-2.0 +package org.thingsboard.server.service.install; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.sql.SQLException; + +import static org.assertj.core.api.Assertions.assertThatCode; +import static org.thingsboard.server.service.install.InstallTestSupport.dataDir; +import static org.thingsboard.server.service.install.InstallTestSupport.readResource; + +/** + * {@code basic/schema_update.sql} runs before {@code schema-entities.sql}, so it must not reference a table + * that only the latter creates. The fixture schema predates {@code tb_cluster}. + */ +class SchemaUpdateSqlUpgradeOrderTest extends AbstractInstallPostgresTest { + + @BeforeEach + void setUp() throws SQLException { + execute("DROP SCHEMA public CASCADE; CREATE SCHEMA public;"); + execute(readResource("install/pre-upgrade-schema-entities.sql")); + } + + @Test + void testSchemaUpdateRunsCleanlyBeforeTbClusterExists() throws IOException { + String sql = Files.readString(schemaUpdateSqlFile()); + + assertThatCode(() -> execute(sql)).doesNotThrowAnyException(); + } + + @Test + void testALegitimateStatementAgainstALongStandingTableIsNotFlagged() throws IOException { + String sql = Files.readString(schemaUpdateSqlFile()) + + "\nALTER TABLE device ADD COLUMN IF NOT EXISTS probe_column varchar(1);\n"; + + assertThatCode(() -> execute(sql)).doesNotThrowAnyException(); + } + + @Test + void testLtsSchemaUpdateCreatesTbClusterBeforeItsIndex() throws IOException { + String sql = Files.readString(ltsSchemaUpdateSqlFile("4.3.1.6")); + + assertThatCode(() -> execute(sql)).doesNotThrowAnyException(); + } + + private static Path schemaUpdateSqlFile() { + return dataDir().resolve(Paths.get("upgrade", "basic", "schema_update.sql")); + } + + private static Path ltsSchemaUpdateSqlFile(String version) { + return dataDir().resolve(Paths.get("upgrade", "lts", version, "schema_update.sql")); + } + +} diff --git a/application/src/test/java/org/thingsboard/server/service/install/SqlEntityDatabaseSchemaServiceClusterIdTest.java b/application/src/test/java/org/thingsboard/server/service/install/SqlEntityDatabaseSchemaServiceClusterIdTest.java new file mode 100644 index 0000000000..389d4abee1 --- /dev/null +++ b/application/src/test/java/org/thingsboard/server/service/install/SqlEntityDatabaseSchemaServiceClusterIdTest.java @@ -0,0 +1,106 @@ +// SPDX-FileCopyrightText: Copyright The Thingsboard Authors +// SPDX-License-Identifier: Apache-2.0 +package org.thingsboard.server.service.install; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.springframework.test.util.ReflectionTestUtils; + +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; +import java.util.ArrayList; +import java.util.List; +import java.util.UUID; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.thingsboard.server.service.install.InstallTestSupport.readResource; +import static org.thingsboard.server.service.install.InstallTestSupport.tbClusterStatements; + +class SqlEntityDatabaseSchemaServiceClusterIdTest extends AbstractInstallPostgresTest { + + private SqlEntityDatabaseSchemaService schemaService; + + @BeforeEach + void setUp() throws SQLException { + execute("DROP TABLE IF EXISTS tb_cluster;"); + for (String statement : productionClusterDdl()) { + execute(statement); + } + schemaService = new SqlEntityDatabaseSchemaService(); + ReflectionTestUtils.setField(schemaService, "dbUrl", postgres.getJdbcUrl()); + ReflectionTestUtils.setField(schemaService, "dbUserName", postgres.getUsername()); + ReflectionTestUtils.setField(schemaService, "dbPassword", postgres.getPassword()); + } + + @Test + void testFreshInstallMintsExactlyOneClusterId() throws SQLException { + schemaService.generateClusterIdIfNotExist(); + List ids = readClusterIds(); + assertThat(ids).hasSize(1); + assertThat(ids.get(0)).isNotNull(); + } + + @Test + void testSecondCallIsANoOp() throws SQLException { + schemaService.generateClusterIdIfNotExist(); + UUID first = readClusterIds().get(0); + schemaService.generateClusterIdIfNotExist(); + schemaService.generateClusterIdIfNotExist(); + List ids = readClusterIds(); + assertThat(ids).containsExactly(first); + } + + @Test + void testExistingClusterIdSurvivesAnUpgrade() throws SQLException { + UUID existing = UUID.randomUUID(); + execute("INSERT INTO tb_cluster (cluster_id) VALUES ('" + existing + "');"); + schemaService.generateClusterIdIfNotExist(); + assertThat(readClusterIds()).containsExactly(existing); + } + + @Test + void testSecondRowInsertIsRejectedByUniqueIndex() throws SQLException { + UUID existing = UUID.randomUUID(); + execute("INSERT INTO tb_cluster (cluster_id) VALUES ('" + existing + "');"); + + UUID other = UUID.randomUUID(); + assertThatThrownBy(() -> execute("INSERT INTO tb_cluster (cluster_id) VALUES ('" + other + "');")) + .isInstanceOf(SQLException.class) + .hasMessageContaining("tb_cluster_single_row"); + + assertThat(readClusterIds()).containsExactly(existing); + } + + @Test + void testConnectionFailurePropagatesInsteadOfBeingSwallowed() { + ReflectionTestUtils.setField(schemaService, "dbUrl", "jdbc:postgresql://localhost:1/does-not-exist"); + + assertThatThrownBy(() -> schemaService.generateClusterIdIfNotExist()) + .isInstanceOf(RuntimeException.class) + .hasMessageContaining("Failed to generate Cluster id") + .hasCauseInstanceOf(SQLException.class); + } + + private static List productionClusterDdl() { + String resourceName = "sql/" + SqlEntityDatabaseSchemaService.SCHEMA_ENTITIES_SQL; + List statements = tbClusterStatements(readResource(resourceName)); + assertThat(statements).as("tb_cluster DDL found in %s", resourceName).hasSize(2); + return statements; + } + + private static List readClusterIds() throws SQLException { + List ids = new ArrayList<>(); + try (Connection conn = DriverManager.getConnection(postgres.getJdbcUrl(), postgres.getUsername(), postgres.getPassword()); + Statement statement = conn.createStatement(); + ResultSet rs = statement.executeQuery("SELECT cluster_id FROM tb_cluster ORDER BY cluster_id")) { + while (rs.next()) { + ids.add(rs.getObject("cluster_id", UUID.class)); + } + } + return ids; + } +} diff --git a/application/src/test/java/org/thingsboard/server/service/install/TbClusterDdlDriftTest.java b/application/src/test/java/org/thingsboard/server/service/install/TbClusterDdlDriftTest.java new file mode 100644 index 0000000000..3a035f80d5 --- /dev/null +++ b/application/src/test/java/org/thingsboard/server/service/install/TbClusterDdlDriftTest.java @@ -0,0 +1,39 @@ +// SPDX-FileCopyrightText: Copyright The Thingsboard Authors +// SPDX-License-Identifier: Apache-2.0 +package org.thingsboard.server.service.install; + +import org.junit.jupiter.api.Test; + +import java.nio.file.Paths; +import java.util.List; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.thingsboard.server.service.install.InstallTestSupport.dataDir; +import static org.thingsboard.server.service.install.InstallTestSupport.readFile; +import static org.thingsboard.server.service.install.InstallTestSupport.readResource; +import static org.thingsboard.server.service.install.InstallTestSupport.tbClusterStatements; + +/** + * When {@code tb_cluster} changes, put the {@code ALTER} in a new upgrade script and point this test at it: + * the 4.3.1.6 script is {@code IF NOT EXISTS}, so editing it is a no-op on databases that already ran it. + */ +class TbClusterDdlDriftTest { + + @Test + void testLtsSchemaUpdateTbClusterDdlMatchesSchemaEntities() { + String schemaEntities = "sql/" + SqlEntityDatabaseSchemaService.SCHEMA_ENTITIES_SQL; + List fromSchemaEntities = normalized(tbClusterStatements(readResource(schemaEntities))); + List fromLtsScript = normalized(tbClusterStatements(readFile( + dataDir().resolve(Paths.get("upgrade", "lts", "4.3.1.6", "schema_update.sql"))))); + + assertThat(fromSchemaEntities).as("tb_cluster statements found in %s", schemaEntities).hasSize(2); + assertThat(fromLtsScript) + .as("tb_cluster DDL in the 4.3.1.6 upgrade script matches %s", schemaEntities) + .isEqualTo(fromSchemaEntities); + } + + private static List normalized(List statements) { + return statements.stream().map(statement -> statement.replaceAll("\\s+", " ").trim()).toList(); + } + +} diff --git a/application/src/test/java/org/thingsboard/server/service/install/lts/LtsMigrationIntegrationTest.java b/application/src/test/java/org/thingsboard/server/service/install/lts/LtsMigrationIntegrationTest.java index 771a239e5d..0fe732b355 100644 --- a/application/src/test/java/org/thingsboard/server/service/install/lts/LtsMigrationIntegrationTest.java +++ b/application/src/test/java/org/thingsboard/server/service/install/lts/LtsMigrationIntegrationTest.java @@ -36,10 +36,14 @@ import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; @DaoSqlTest public class LtsMigrationIntegrationTest extends AbstractControllerTest { + private static final Runnable NO_POST_SCHEMA_WORK = () -> { + }; + private static final long V_4_2_2_2 = 4_002_002_002L; private static final long V_4_2_2_3 = 4_002_002_003L; private static final String OBSOLETE_ALIAS = "air_quality"; @@ -62,6 +66,8 @@ public class LtsMigrationIntegrationTest extends AbstractControllerTest { private List migrations; private Long originalSchemaVersion; + private String originalClusterId; + private String originalLicenseClaimToken; private WidgetsBundleId bundleId; private WidgetTypeId widgetTypeId; @@ -75,6 +81,15 @@ public class LtsMigrationIntegrationTest extends AbstractControllerTest { jdbcTemplate.execute("INSERT INTO tb_schema_settings (schema_version, product) VALUES (" + V_4_2_2_2 + ", 'CE')"); } + // The 4.3.1.6 tests drop and re-create tb_cluster, so keep the row the shared test DB already has. + jdbcTemplate.query("SELECT cluster_id, license_claim_token FROM tb_cluster", rs -> { + if (rs.next()) { + originalClusterId = rs.getString("cluster_id"); + originalLicenseClaimToken = rs.getString("license_claim_token"); + } + return null; + }); + // Seed an obsolete system widget bundle with one (non-deprecated) widget type linked to it. WidgetsBundle bundle = new WidgetsBundle(); bundle.setTenantId(TenantId.SYS_TENANT_ID); @@ -103,6 +118,14 @@ public class LtsMigrationIntegrationTest extends AbstractControllerTest { } else { jdbcTemplate.execute("DELETE FROM tb_schema_settings"); } + // Guarded so that a migration that failed to recreate tb_cluster reports its own assertion, not a tear-down error. + if (tableExists("tb_cluster")) { + jdbcTemplate.execute("DELETE FROM tb_cluster"); + if (originalClusterId != null) { + jdbcTemplate.update("INSERT INTO tb_cluster (cluster_id, license_claim_token) VALUES (?::uuid, ?)", + originalClusterId, originalLicenseClaimToken); + } + } if (widgetTypeId != null && widgetTypeService.findWidgetTypeDetailsById(TenantId.SYS_TENANT_ID, widgetTypeId) != null) { widgetTypeService.deleteWidgetType(TenantId.SYS_TENANT_ID, widgetTypeId); } @@ -114,7 +137,11 @@ public class LtsMigrationIntegrationTest extends AbstractControllerTest { @Test public void appliesSqlDeprecatesTypesDeletesBundleAndRecordsVersion() { - ltsMigrationService.applyMigrations("4.2.2.2", "4.2.2.3"); + ltsMigrationService.applyMigrations("4.2.2.2", "4.2.2.3", () -> { + assertTrue(tableExists("iot_hub_installed_item")); + assertEquals(Long.valueOf(V_4_2_2_2), + jdbcTemplate.queryForObject("SELECT schema_version FROM tb_schema_settings", Long.class)); + }); // 1. The version's SQL ran: iot_hub_installed_item table now exists. assertTrue(tableExists("iot_hub_installed_item")); @@ -131,9 +158,9 @@ public class LtsMigrationIntegrationTest extends AbstractControllerTest { @Test public void reRunFromCurrentVersionIsNoOp() { - ltsMigrationService.applyMigrations("4.2.2.2", "4.2.2.3"); + ltsMigrationService.applyMigrations("4.2.2.2", "4.2.2.3", NO_POST_SCHEMA_WORK); // Re-running from the now-current version selects an empty range — nothing changes, nothing throws. - ltsMigrationService.applyMigrations("4.2.2.3", "4.2.2.3"); + ltsMigrationService.applyMigrations("4.2.2.3", "4.2.2.3", NO_POST_SCHEMA_WORK); assertEquals(Long.valueOf(V_4_2_2_3), jdbcTemplate.queryForObject("SELECT schema_version FROM tb_schema_settings", Long.class)); @@ -141,6 +168,30 @@ public class LtsMigrationIntegrationTest extends AbstractControllerTest { assertTrue(widgetTypeService.findWidgetTypeDetailsById(TenantId.SYS_TENANT_ID, widgetTypeId).isDeprecated()); } + @Test + public void postSchemaWorkFailureLeavesTheVersionUnrecordedSoTheNextBootRetries() { + IllegalStateException failure = new IllegalStateException("post-schema work failed"); + try { + ltsMigrationService.applyMigrations("4.2.2.2", "4.2.2.3", () -> { + throw failure; + }); + fail("Expected the post-schema failure to propagate"); + } catch (IllegalStateException e) { + assertEquals(failure, e); + } + + assertTrue(tableExists("iot_hub_installed_item")); + assertNull(widgetsBundleService.findWidgetsBundleByTenantIdAndAlias(TenantId.SYS_TENANT_ID, OBSOLETE_ALIAS)); + assertEquals(Long.valueOf(V_4_2_2_2), + jdbcTemplate.queryForObject("SELECT schema_version FROM tb_schema_settings", Long.class)); + + ltsMigrationService.applyMigrations("4.2.2.2", "4.2.2.3", NO_POST_SCHEMA_WORK); + + assertEquals(Long.valueOf(V_4_2_2_3), + jdbcTemplate.queryForObject("SELECT schema_version FROM tb_schema_settings", Long.class)); + assertTrue(widgetTypeService.findWidgetTypeDetailsById(TenantId.SYS_TENANT_ID, widgetTypeId).isDeprecated()); + } + @Test public void offlinePathRunsSchemaThenDataButRecordsNoVersion() { // Drive the offline major-upgrade path over the real supported range against the real DB. @@ -170,12 +221,36 @@ public class LtsMigrationIntegrationTest extends AbstractControllerTest { assertFalse(columnExists("calculated_field", "additional_info")); // Drive the runner over a range whose target (4.3.1.2) selects only the 4.3.1.2 migration. - ltsMigrationService.applyMigrations("4.3.1.1", "4.3.1.2"); + ltsMigrationService.applyMigrations("4.3.1.1", "4.3.1.2", NO_POST_SCHEMA_WORK); // The 4.3.1.2 schema SQL ran: the column exists again. assertTrue(columnExists("calculated_field", "additional_info")); } + @Test + public void appliesSchemaForV4316CreatesTbClusterAndMintsOneClusterId() { + jdbcTemplate.execute("DROP TABLE IF EXISTS tb_cluster"); + assertFalse(tableExists("tb_cluster")); + + ltsMigrationService.applyMigrations("4.3.1.3", "4.3.1.6", NO_POST_SCHEMA_WORK); + + assertTrue(tableExists("tb_cluster")); + assertEquals(Long.valueOf(1L), jdbcTemplate.queryForObject("SELECT COUNT(*) FROM tb_cluster", Long.class)); + } + + @Test + public void v4316KeepsAnExistingClusterId() { + UUID existing = UUID.randomUUID(); + jdbcTemplate.execute("DROP TABLE IF EXISTS tb_cluster"); + ltsMigrationService.applyMigrations("4.3.1.3", "4.3.1.6", NO_POST_SCHEMA_WORK); + jdbcTemplate.update("UPDATE tb_cluster SET cluster_id = ?::uuid", existing.toString()); + + ltsMigrationService.applyMigrations("4.3.1.3", "4.3.1.6", NO_POST_SCHEMA_WORK); + + assertEquals(List.of(existing.toString()), + jdbcTemplate.queryForList("SELECT cluster_id FROM tb_cluster", String.class)); + } + @Test public void migrationDirectoriesAndBeansStayInSyncBothWays() { Path ltsDir = Paths.get(installScripts.getDataDir(), "upgrade", "lts"); diff --git a/application/src/test/java/org/thingsboard/server/service/install/lts/LtsMigrationServiceTest.java b/application/src/test/java/org/thingsboard/server/service/install/lts/LtsMigrationServiceTest.java index ee03750d6c..c9129131fc 100644 --- a/application/src/test/java/org/thingsboard/server/service/install/lts/LtsMigrationServiceTest.java +++ b/application/src/test/java/org/thingsboard/server/service/install/lts/LtsMigrationServiceTest.java @@ -5,6 +5,7 @@ package org.thingsboard.server.service.install.lts; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.io.TempDir; +import org.mockito.InOrder; import org.mockito.Mockito; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.transaction.PlatformTransactionManager; @@ -23,12 +24,17 @@ import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.doAnswer; +import static org.mockito.Mockito.inOrder; import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; class LtsMigrationServiceTest { + private static final Runnable NO_POST_SCHEMA_WORK = () -> { + }; + private JdbcTemplate jdbcTemplate; private InstallScripts installScripts; private DatabaseSchemaSettingsService schemaSettingsService; @@ -61,6 +67,11 @@ class LtsMigrationServiceTest { }; } + private void recordVersionsInto(List events) { + doAnswer(invocation -> events.add("record:" + invocation.getArgument(0))) + .when(schemaSettingsService).updateSchemaVersion(anyString()); + } + private LtsMigrationService service(List migrations) { return new LtsMigrationService(jdbcTemplate, installScripts, schemaSettingsService, txManager, migrations); } @@ -76,7 +87,7 @@ class LtsMigrationServiceTest { migration("4.2.2.2", applied), migration("4.2.2.3", applied))); - service.applyMigrations("4.2.2.2", "4.2.2.3"); + service.applyMigrations("4.2.2.2", "4.2.2.3", NO_POST_SCHEMA_WORK); // only 4.2.2.3 is in (4.2.2.2, 4.2.2.3] assertEquals(List.of("4.2.2.3"), applied); @@ -93,7 +104,7 @@ class LtsMigrationServiceTest { LtsMigrationService service = service(List.of( migration("4.2.2.3", applied), migration("4.2.2.4", applied))); - service.applyMigrations("4.2.2.2", "4.2.2.4"); + service.applyMigrations("4.2.2.2", "4.2.2.4", NO_POST_SCHEMA_WORK); assertEquals(List.of("4.2.2.3", "4.2.2.4"), applied); verify(jdbcTemplate).execute("SELECT 1;"); @@ -126,7 +137,7 @@ class LtsMigrationServiceTest { migration("4.3.1.2", applied), migration("4.3.1.3", applied))); - service.applyMigrations("4.2.2.2", "4.3.1.3"); + service.applyMigrations("4.2.2.2", "4.3.1.3", NO_POST_SCHEMA_WORK); assertEquals(List.of("4.3.1.2", "4.3.1.3"), applied); verify(schemaSettingsService, never()).updateSchemaVersion("4.2.2.3"); @@ -172,14 +183,57 @@ class LtsMigrationServiceTest { @Test void reRunAtCurrentVersionIsNoOp() throws Exception { List applied = new ArrayList<>(); + List events = new ArrayList<>(); writeSql("4.2.2.3", "SELECT 1;"); LtsMigrationService service = service(List.of(migration("4.2.2.3", applied))); - service.applyMigrations("4.2.2.3", "4.2.2.3"); + service.applyMigrations("4.2.2.3", "4.2.2.3", () -> events.add("afterSchemaPhase")); assertEquals(List.of(), applied); verify(jdbcTemplate, never()).execute(anyString()); verify(schemaSettingsService, never()).updateSchemaVersion(anyString()); + assertEquals(List.of("afterSchemaPhase"), events); + } + + @Test + void recordsNoVersionUntilTheAfterSchemaPhaseHasRun() throws Exception { + List events = new ArrayList<>(); + recordVersionsInto(events); + writeSql("4.2.2.3", "SELECT 1;"); + writeSql("4.2.2.4", "SELECT 2;"); + LtsMigrationService service = service(List.of( + migration("4.2.2.3", events), migration("4.2.2.4", events))); + + service.applyMigrations("4.2.2.2", "4.2.2.4", () -> events.add("afterSchemaPhase")); + + assertEquals(List.of("4.2.2.3", "4.2.2.4", "afterSchemaPhase", "record:4.2.2.3", "record:4.2.2.4"), events); + } + + @Test + void recordsVersionOutsideTheMigrationTransaction() throws Exception { + List applied = new ArrayList<>(); + writeSql("4.2.2.3", "SELECT 1;"); + LtsMigrationService service = service(List.of(migration("4.2.2.3", applied))); + + service.applyMigrations("4.2.2.2", "4.2.2.3", NO_POST_SCHEMA_WORK); + + InOrder inOrder = inOrder(txManager, schemaSettingsService); + inOrder.verify(txManager).commit(any()); + inOrder.verify(schemaSettingsService).updateSchemaVersion("4.2.2.3"); + } + + @Test + void afterSchemaPhaseFailureLeavesEveryVersionUnrecorded() throws Exception { + List applied = new ArrayList<>(); + writeSql("4.2.2.3", "SELECT 1;"); + LtsMigrationService service = service(List.of(migration("4.2.2.3", applied))); + + assertThrows(IllegalStateException.class, () -> service.applyMigrations("4.2.2.2", "4.2.2.3", () -> { + throw new IllegalStateException("post-schema work failed"); + })); + + assertEquals(List.of("4.2.2.3"), applied); + verify(schemaSettingsService, never()).updateSchemaVersion(anyString()); } @Test @@ -213,7 +267,7 @@ class LtsMigrationServiceTest { List applied = new ArrayList<>(); LtsMigrationService service = service(List.of(migration("4.2.2.3", applied))); - service.applyMigrations("4.2.2.2", "4.2.2.3"); + service.applyMigrations("4.2.2.2", "4.2.2.3", NO_POST_SCHEMA_WORK); assertEquals(List.of("4.2.2.3"), applied); verify(jdbcTemplate, never()).execute(anyString()); diff --git a/application/src/test/java/org/thingsboard/server/system/SystemPatchApplierTest.java b/application/src/test/java/org/thingsboard/server/system/SystemPatchApplierTest.java index 32789ba181..9ba676a611 100644 --- a/application/src/test/java/org/thingsboard/server/system/SystemPatchApplierTest.java +++ b/application/src/test/java/org/thingsboard/server/system/SystemPatchApplierTest.java @@ -9,6 +9,7 @@ import org.junit.jupiter.api.io.TempDir; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; +import org.mockito.ArgumentCaptor; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; @@ -51,6 +52,8 @@ import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.ArgumentMatchers.argThat; import static org.mockito.ArgumentMatchers.contains; import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.doAnswer; +import static org.mockito.Mockito.lenient; import static org.mockito.Mockito.never; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; @@ -86,6 +89,13 @@ public class SystemPatchApplierTest { @TempDir Path tempDir; + private void runPostSchemaCallback() { + doAnswer(invocation -> { + invocation.getArgument(2, Runnable.class).run(); + return null; + }).when(ltsMigrationService).applyMigrations(anyString(), anyString(), any()); + } + @Test void whenLockIsNotAcquired_thenAcquiredIsSuccess() { when(jdbcTemplate.queryForObject(anyString(), eq(Boolean.class), anyLong())).thenReturn(true); @@ -449,20 +459,41 @@ public class SystemPatchApplierTest { // --- applyPatchIfNeeded flow tests --- @Test - void whenVersionIncreased_thenAppliesMigrationsBeforeViewsAndWidgets() { + void whenVersionIncreased_thenSystemDataIsSyncedOnlyByTheMigrationCallback() { when(schemaSettingsService.getPackageSchemaVersion()).thenReturn("4.3.1.0"); when(schemaSettingsService.getDbSchemaVersion()).thenReturn("4.3.0.0"); when(jdbcTemplate.queryForObject(contains("pg_try_advisory_lock"), eq(Boolean.class), anyLong())).thenReturn(true); when(jdbcTemplate.queryForObject(contains("pg_advisory_unlock"), eq(Boolean.class), anyLong())).thenReturn(true); - when(installScripts.getWidgetTypesDir()).thenReturn(tempDir.resolve("widget_types")); when(installScripts.getWidgetBundlesDir()).thenReturn(tempDir.resolve("widget_bundles_missing")); when(installScripts.getDataDir()).thenReturn(tempDir.resolve("data").toString()); ReflectionTestUtils.invokeMethod(reconciler, "applyPatchIfNeeded"); - verify(ltsMigrationService).applyMigrations("4.3.0.0", "4.3.1.0"); - verify(schemaSettingsService).updateSchemaVersion(); + ArgumentCaptor postSchemaPhase = ArgumentCaptor.forClass(Runnable.class); + verify(ltsMigrationService).applyMigrations(eq("4.3.0.0"), eq("4.3.1.0"), postSchemaPhase.capture()); + verify(jdbcTemplate, never()).execute(anyString()); + + postSchemaPhase.getValue().run(); + + verify(jdbcTemplate).execute(contains("CREATE OR REPLACE VIEW")); + } + + @Test + void whenMigrationCallbackNotInvoked_thenNothingIsSyncedOutsideIt() { + when(schemaSettingsService.getPackageSchemaVersion()).thenReturn("4.3.1.0"); + when(schemaSettingsService.getDbSchemaVersion()).thenReturn("4.3.0.0"); + when(jdbcTemplate.queryForObject(contains("pg_try_advisory_lock"), eq(Boolean.class), anyLong())).thenReturn(true); + when(jdbcTemplate.queryForObject(contains("pg_advisory_unlock"), eq(Boolean.class), anyLong())).thenReturn(true); + // Lenient: only reached if system data were synced outside the callback. + lenient().when(installScripts.getWidgetTypesDir()).thenReturn(tempDir.resolve("widget_types_missing")); + lenient().when(installScripts.getWidgetBundlesDir()).thenReturn(tempDir.resolve("widget_bundles_missing")); + lenient().when(installScripts.getDataDir()).thenReturn(tempDir.resolve("data_missing").toString()); + + ReflectionTestUtils.invokeMethod(reconciler, "applyPatchIfNeeded"); + + verify(ltsMigrationService).applyMigrations(eq("4.3.0.0"), eq("4.3.1.0"), any()); + verify(jdbcTemplate, never()).execute(anyString()); } @Test @@ -497,6 +528,8 @@ public class SystemPatchApplierTest { when(jdbcTemplate.queryForObject(contains("pg_try_advisory_lock"), eq(Boolean.class), anyLong())).thenReturn(true); when(jdbcTemplate.queryForObject(contains("pg_advisory_unlock"), eq(Boolean.class), anyLong())).thenReturn(true); + runPostSchemaCallback(); + Path widgetTypesDir = tempDir.resolve("widget_types"); Files.createDirectories(widgetTypesDir); when(installScripts.getWidgetTypesDir()).thenReturn(widgetTypesDir); @@ -506,7 +539,7 @@ public class SystemPatchApplierTest { ReflectionTestUtils.invokeMethod(reconciler, "applyPatchIfNeeded"); verify(schemaSettingsService).updateSchemaVersion(); - verify(ltsMigrationService).applyMigrations("4.3.1.0", "4.3.2.0"); + verify(ltsMigrationService).applyMigrations(eq("4.3.1.0"), eq("4.3.2.0"), any()); } @Test @@ -719,6 +752,7 @@ public class SystemPatchApplierTest { when(schemaSettingsService.getDbSchemaVersion()).thenReturn("4.3.0.0"); when(jdbcTemplate.queryForObject(contains("pg_try_advisory_lock"), eq(Boolean.class), anyLong())).thenReturn(true); when(jdbcTemplate.queryForObject(contains("pg_advisory_unlock"), eq(Boolean.class), anyLong())).thenReturn(true); + runPostSchemaCallback(); Path dataDir = tempDir.resolve("data"); Path imagesDir = dataDir.resolve(InstallScripts.RESOURCES_DIR).resolve("images"); diff --git a/application/src/test/resources/community-grant/01-valid.tbicb b/application/src/test/resources/community-grant/01-valid.tbicb new file mode 100644 index 0000000000000000000000000000000000000000..dc454a0e47520fe621efb651008c48bc50932454 GIT binary patch literal 575 zcmWG>@^p4`@iAm%U|?Lrz`)=T0u%`LbT?#VwA!@(h`IXb>d75}+&O&QwUfAt``&(u zS{InPs&@M7$KTDT?PM2g?0Aq7nzsAQ!9b?dxtn02V{r&h8h-RB)VG~r9}q&WEbS77nqqDmiY#F8>D2V znU)$GXqS81g58mrlard4o(j|&X_S$Xk)nTer+k*P7*+Xe4nd<3Ag(h_sTXfw`TlPjFOXMt)gs OOZTLi3zo0jx(5J$k;0(> literal 0 HcmV?d00001 diff --git a/application/src/test/resources/community-grant/02-too-short.tbicb b/application/src/test/resources/community-grant/02-too-short.tbicb new file mode 100644 index 0000000000000000000000000000000000000000..38922346a203e83415b07b363270fb2c969da1aa GIT binary patch literal 90 zcmV-g0Hyy_LP(;gzglbYtI%Rz<8%6F8}}l literal 0 HcmV?d00001 diff --git a/application/src/test/resources/community-grant/03-bad-magic.tbicb b/application/src/test/resources/community-grant/03-bad-magic.tbicb new file mode 100644 index 0000000000000000000000000000000000000000..dca067eed8dd456a68bac76583021f816a1876ee GIT binary patch literal 575 zcma!W@^p4`@iAm%U|?Lrz`)=T0u%`LbT?#VwA!@(h`IXb>d75}+&O&QwUfAt``&(u zS{InPs&@M7$KTDT?PM2g?0Aq7nzsAQ!9b?dxtn02V{r&h8h-RB)VG~r9}q&WEbS77nqqDmiY#F8>D2V znU)$GXqS81g58mrlard4o(j|&X_S$Xk)nTer+k*P7*+Xe4nd<3Ag(h_sTXfw`TlPjFOXMt)gs OOZTLi3zo0jx(5J literal 0 HcmV?d00001 diff --git a/application/src/test/resources/community-grant/04-unknown-version.tbicb b/application/src/test/resources/community-grant/04-unknown-version.tbicb new file mode 100644 index 0000000000000000000000000000000000000000..dd8b5d671665689acf0400ae1749da78aeae0b28 GIT binary patch literal 575 zcmWG>@^p4`@iAm#U|?Lrz`)=T0u%`LbT?#VwA!@(h`IXb>d75}+&O&QwUfAt``&(u zS{InPs&@M7$KTDT?PM2g?0Aq7nzsAQ!9b?dxtn02V{r&h8h-RB)VG~r9}q&WEbS77nqqDmiY#F8>D2V znU)$GXqS81g58mrlard4o(j|&X_S$Xk)nTer+k*P7*+Xe4nd<3Ag(h_sTXfw`TlPjFOXMt)gs OOZTLi3zo0jx(5J&$ikuk literal 0 HcmV?d00001 diff --git a/application/src/test/resources/community-grant/05-manifest-len-zero.tbicb b/application/src/test/resources/community-grant/05-manifest-len-zero.tbicb new file mode 100644 index 0000000000000000000000000000000000000000..21ea898826888de42a50073f9e32504f535d53ef GIT binary patch literal 575 zcmWG>@^p4`@iAm%fB=UOpg^#vyCEZ^)u#1F%+)_vPwoih&f(*(oy1k#_x4NFy1>j; zwbNHW{%$^PC%af<$AgT}wB6q)t>Y};cDSMFS<5?-x!LE%ZgNg(aY<^CX9`fvIL#>0FxkXJ z*D}pGN!QRYHC5Ll+0sDQz{tcXG1<__z`(!=q$MLYIUA@Yub{L<$*P(hBeGK~K{f*2 zR#2LhlbP(DS_!n@JH*jAAUn)A)UY5U(cRK0Ei%|AyC65cz|73B%s0T>ASEl!wA9!@ zyWG{)j5XW-gV8hJRh@hP0a$AtnqSUn1qSU

    @^p4`@iAm%U{C;J28R%!K(ME~AtR&Jru9e6)jwBH?g-@0;p48I#8uq)_Dj^d zz|2*((^o(KZa!@%yI5n#gN)F$-QOpz<1F8HxS{A-%R7;|+2_UN53p1#C6(r-L}$GD_JS!WagDtDCsCA7A0o@xrwb1$iyfy+0e+qz`zKkB_lOC8>l6(ptMBEs+t@lvQsNT zHUiyNP@0sJne3ff3AEok#L+k)JIpuKuplGR-O?y6GT0}(AUD0h%*?RNH^AEMdt)V%ampw>vEjEp4rikzg}lpLQB$8z6b!_3r(pq%7#TaePC)U?#1 z)V$EgTUb~Cy<}ie3-S}xEZ2&H%%ap{N1)G43=ND-jlteFFwjxT zEG{lhO@T?6n3zB`!^6WZGbhzAF&E^Tk|f>CyyB8XpoO~N(256#emo@5YnizOCFIp~ zO{|?f1H$7{bBe1PJNl>1U9x)9&I8BKUA^=8)yE(I*?2{yl{5{^?Oc6=qY^Xn%W7M? MC(T^2eBIVP09;kV9RL6T literal 0 HcmV?d00001 diff --git a/application/src/test/resources/community-grant/07-checker-len-zero.tbicb b/application/src/test/resources/community-grant/07-checker-len-zero.tbicb new file mode 100644 index 0000000000000000000000000000000000000000..9a520a592f87965c49f96286f3ca555f94db29ce GIT binary patch literal 575 zcmWG>@^p4`@iAm%U|?Lr00bdGfnZN}Lq}ne-F(_kcCp5e2N|JhyT4Cb$63DZa6{3vmUkj^v(JmkA7H6gN-E7u$w>`M zEh^5;&r`B8)KSVWROQP|{IKEK1G*auah?%uImX`avZ0ZIfq@Z7OGavPHc(4mL1~GSRW&(AWT#ew zYy`Tkpfo8bGub<}5@^47h@){pc9?IdVL?WsyQNWDWUx-X_ zsj-1}xu-4I9f>(Psd?$CK&_ER85v3L6*)<{DLFnNj^)0=hMB1mK{?6gwjiZNscET2 zsd>q%zL_~WnZV#MG`BD}x3I7Pdda|`7UUA*D`YnO316} znpit|2873@<`h>ocJxo1yJYpIod=GeyL#vGtB*hav+;^ZD`^^-+qwD#M@^p4`@iAm%U|?Lrz`)=T0u%`LbT?#VwA!@(h`IXb>d75}+&O&QwUfAt``&(u zS{InPs&@M7$KTDT?PM2g?0Aq7nzsAQ!9b?dxtn02V{r&h8h-RB)VG~r9}q&WETJc7rtXZ literal 0 HcmV?d00001 diff --git a/application/src/test/resources/community-grant/09-truncated-mid-checker.tbicb b/application/src/test/resources/community-grant/09-truncated-mid-checker.tbicb new file mode 100644 index 0000000000000000000000000000000000000000..d7479bc64dbb5c83bb7450c4b6b48049cdd4fe68 GIT binary patch literal 543 zcmWG>@^p4`@iAm%U|?Lrz`)=T0u%`LbT?#VwA!@(h`IXb>d75}+&O&QwUfAt``&(u zS{InPs&@M7$KTDT?PM2g?0Aq7nzsAQ!9b?dxtn02V{r&h8h-RB)VG~r9}q&WEbS77nqqDmiY#F8>D2V znU)$GXqS81g58mrlard4o(j|&X_S$Xk)nTer+k*P7*+Xeb%7 literal 0 HcmV?d00001 diff --git a/application/src/test/resources/community-grant/10-trailing-byte.tbicb b/application/src/test/resources/community-grant/10-trailing-byte.tbicb new file mode 100644 index 0000000000000000000000000000000000000000..ac01341853daeeab7a896c876056bee4d9a652e7 GIT binary patch literal 576 zcmWG>@^p4`@iAm%U|?Lrz`)=T0u%`LbT?#VwA!@(h`IXb>d75}+&O&QwUfAt``&(u zS{InPs&@M7$KTDT?PM2g?0Aq7nzsAQ!9b?dxtn02V{r&h8h-RB)VG~r9}q&WEbS77nqqDmiY#F8>D2V znU)$GXqS81g58mrlard4o(j|&X_S$Xk)nTer+k*P7*+Xe4nd<3Ag(h_sTXfw`TlPjFOXMt)gs POZTLi3zo0jx`zP(K|#Wy literal 0 HcmV?d00001 diff --git a/application/src/test/resources/community-grant/11-manifest-not-utf8.tbicb b/application/src/test/resources/community-grant/11-manifest-not-utf8.tbicb new file mode 100644 index 0000000000000000000000000000000000000000..659958014799d20e3e1fb3edb7bac4acdf7cac4c GIT binary patch literal 575 zcmWG>@^p4`@iAm%U|?Lrz`)=T0u%`LbT?#VwA!@(h`IXb>d75}+&O&QwUfAt``&(u zS{InPs&@M7$KTDT?PM2g?0Aq7nzsA@^p4`@iAm%U|?Lrz`)=T0u%`LbT?#VwA!@(h`IXb>d75}+&O&QwUfAt``&(u zS{InPs&@M7$KTDT?PM2g?0Aq7nzsA+Ef7;w7t2gaDaQxiWJC9#|{PCZS fS43J#)4<%$)h9SAF(bdMwxxU0%mvHWZQTO^B;|S> literal 0 HcmV?d00001 diff --git a/application/src/test/resources/community-grant/13-manifest-missing-field.tbicb b/application/src/test/resources/community-grant/13-manifest-missing-field.tbicb new file mode 100644 index 0000000000000000000000000000000000000000..7e124c51a3e5cf916b687d430382dc310233844f GIT binary patch literal 524 zcmWG>@^p4`@iAm%U|=j{U|?_v0SW|rx*IYwT5Vc?#9aMz_2iB~?i@bu+DTl+eQ&=+ ztqaUtRXct4dFBYJI9lL_>jp}B>*xrK!V&^-nQwIDx1&2p_M$Sg`Nb_Dv&#L&RV)EMk$0|OnU z%;MtG)D)P6iHQkBGdw)pGILV>5_3VWDM`}J%quQQ1X`#I4y|}_P{u<-u$GxiP(of! z*TmY%Gax)JHK(|$v7>+5+$F0w?L2V&+|@geUw!=XpN&^UT1nHu+|Jb}I4UtCzpS>U Nd(zAW%hzq)0|3LcwBP^$ literal 0 HcmV?d00001 diff --git a/application/src/test/resources/community-grant/14-expired-challenge.tbicb b/application/src/test/resources/community-grant/14-expired-challenge.tbicb new file mode 100644 index 0000000000000000000000000000000000000000..c1865ef41e2e214b0a19279b9e06bfd6b22dffe2 GIT binary patch literal 575 zcmWG>@^p4`@iAm%U|?Lrz`)=T0u%`LbT?#VwA!@(h`IXb>d75}+&O&QwUfAt``&(u zS{InPs&@M7$KTDT?PM2g?0Aq7nzsAQ!9b?dxtn02V{r&h8h-RB)VG~r9}q&WEbS77nqqDmiY#F8>D2V znU)$GXqS81g58mrlard4o(j|&X_S$Xk)nW341rKyRj8CZ>u zQf6^+X=(~g!o<`P6dnc!@bGZU%t`f2%muloBuO_juec-;XrV4RwBo^`9}fxiT4pXm z33)YL6Kf~Wfbh7~oZ_m+j{a$Lm#p5j^T6?QSMNN2_3_7lHeL~FB~1f!J6E6JsKku? Qvf7sJNi!ELU$=D+0F7@^p4`@iAm%U|?Lrz`)?Z02B!JbT?#VwA!@(h`IXb>d75}+&O&QwUfAt``&(u zS{InPs&@M7$KTDT?PM2g?0Aq7nzsAQ!9b?dxtn02V{r&h8h-RB)VG~r9}q&WEbS77nqqDmiY#F8>D2V znU)$GXqS81g58mrlard4o(j|&X_S$Xk)nTer+k*P7*+Xe4nd<3Ag(h_sTXfw`TlPjFOXMt)gs OOZTLi3zo0jx(5KqYQjwb literal 0 HcmV?d00001 diff --git a/application/src/test/resources/community-grant/vectors.json b/application/src/test/resources/community-grant/vectors.json new file mode 100644 index 0000000000..83d20712a3 --- /dev/null +++ b/application/src/test/resources/community-grant/vectors.json @@ -0,0 +1,142 @@ +{ + "format": "TBICBDL1", + "formatVersion": 1, + "fixtureMaterial": { + "releaseSigningPublicKeyBase64": "Nqbrd0SVV4w9yZWl0cgu9I7G/URhdL3PN8mWRwnWDzE=", + "releaseSigningKeyId": 1, + "communityGrantCheckerReleasePublicKeysProperty": "1:Nqbrd0SVV4w9yZWl0cgu9I7G/URhdL3PN8mWRwnWDzE=", + "checkerStandInRule": "64 bytes; checker[i] = (i * 7 + 3) mod 256", + "checkerStandInSha256": "39e3d7b6b5d075d37d053ad89b24b41bef4f3c29760c84447cab3f3be1882241", + "checkerStandInHex": "030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8ff060d141b222930373e454c535a61686f767d848b9299a0a7aeb5bc", + "portalPublicKeyRule": "32 bytes; key[i] = (i * 7 + 0x29) mod 256", + "portalPublicKeyBase64": "KTA3PkVMU1phaG92fYSLkpmgp661vMPK0djf5u30+wI=", + "clusterId": "3f2a1c44-9f3b-11ee-8c90-0242ac120002", + "challenge": "Y2hhbGxlbmdlLTAwMS1ieXRlcw==", + "referenceMillis": 1787788800000, + "validManifestBytes": 420, + "validManifestJson": "{\"bundleVersion\":1,\"os\":\"linux\",\"arch\":\"amd64\",\"clusterId\":\"3f2a1c44-9f3b-11ee-8c90-0242ac120002\",\"checkerInput\":{\"clusterId\":\"3f2a1c44-9f3b-11ee-8c90-0242ac120002\",\"keyId\":1,\"publicKey\":\"KTA3PkVMU1phaG92fYSLkpmgp661vMPK0djf5u30+wI=\",\"challenge\":\"Y2hhbGxlbmdlLTAwMS1ieXRlcw==\",\"referenceMillis\":1787788800000},\"challengeExpiresAt\":4102531200000,\"issuedAt\":4102444800000,\"checkerFileName\":\"tb-instance-check_linux_amd64\"}", + "validRelsigHex": "544249435349473101013ab2afc43727f37b9388510b6c0e0b7d920a738eedf45aae5169aa7d97abe3f73796b907168188e0685566bbf792ae0977b6c38072e684ee149d6bcf161fc004" + }, + "fixtures": [ + { + "file": "01-valid.tbicb", + "sizeBytes": 575, + "sha256": "3e747e7bef600c7a7026558592ac91593922f74c360b0a1746ea3f22e7405dad", + "expectedOutcome": "ACCEPT", + "expectedReason": null, + "note": "The reference bundle; the release signature verifies over the 64-byte checker and the challenge expires in 2100." + }, + { + "file": "02-too-short.tbicb", + "sizeBytes": 90, + "sha256": "38d08ef0ee6f0013b1702ed46f7e6452124f73ae5f19c038b301f17a55e5ba9a", + "expectedOutcome": "REJECT", + "expectedReason": "E_TOO_SHORT", + "note": "90 bytes, one short of the fixed header, although the magic present is correct." + }, + { + "file": "03-bad-magic.tbicb", + "sizeBytes": 575, + "sha256": "464d3034a07911c75062ba54e2bc1e5cc2da04e146d4c5671bd012a1419809b9", + "expectedOutcome": "REJECT", + "expectedReason": "E_BAD_MAGIC", + "note": "Byte 0 changed from 'T' to 'X'; everything else is valid." + }, + { + "file": "04-unknown-version.tbicb", + "sizeBytes": 575, + "sha256": "57f64567e6a50273e3ae26f2e5f32a964f95b7c0d8e878a062654636760c9ad4", + "expectedOutcome": "REJECT", + "expectedReason": "E_UNSUPPORTED_VERSION", + "note": "VERSION = 0x02; the reason names both the declared and the supported version." + }, + { + "file": "05-manifest-len-zero.tbicb", + "sizeBytes": 575, + "sha256": "6bfe256e9d96c801ae56c76c3ed56df50e099551a1ff383792e7312697de1412", + "expectedOutcome": "REJECT", + "expectedReason": "E_MANIFEST_LEN_RANGE", + "note": "MANIFEST_LEN = 0 with the body intact, so the length range check fires before the total length check." + }, + { + "file": "06-manifest-len-too-large.tbicb", + "sizeBytes": 575, + "sha256": "be383e132528933d6a7468e02fb920621dd33502696631678056f028e0ba4de3", + "expectedOutcome": "REJECT", + "expectedReason": "E_MANIFEST_LEN_RANGE", + "note": "MANIFEST_LEN = 8193, one past the ceiling, with the body intact." + }, + { + "file": "07-checker-len-zero.tbicb", + "sizeBytes": 575, + "sha256": "e998d83843ecd4c2c14deb240cc2dbf037ff466a7537c1a0e9a27049cfc62051", + "expectedOutcome": "REJECT", + "expectedReason": "E_CHECKER_LEN_RANGE", + "note": "CHECKER_LEN = 0 with the body intact, so the range check fires before the total length check." + }, + { + "file": "08-truncated-mid-manifest.tbicb", + "sizeBytes": 301, + "sha256": "68c0c107ebdcb7c2299638a6a218e8bccb5a2adf641c5ad6659e68138e878087", + "expectedOutcome": "REJECT", + "expectedReason": "E_LENGTH_MISMATCH", + "note": "Truncated inside the manifest; both declared lengths describe the missing bytes." + }, + { + "file": "09-truncated-mid-checker.tbicb", + "sizeBytes": 543, + "sha256": "8ef37a7f629b547db387326f27248df6b2dae4d3eef09c87ef0746e1d479e362", + "expectedOutcome": "REJECT", + "expectedReason": "E_LENGTH_MISMATCH", + "note": "Truncated inside the checker; the manifest is complete and parseable." + }, + { + "file": "10-trailing-byte.tbicb", + "sizeBytes": 576, + "sha256": "a0c5440286f7e1949333036f4329956b0771ff411ea77150bb1b3f9ca9012600", + "expectedOutcome": "REJECT", + "expectedReason": "E_LENGTH_MISMATCH", + "note": "One 0x00 appended after the checker." + }, + { + "file": "11-manifest-not-utf8.tbicb", + "sizeBytes": 575, + "sha256": "d333b7dfdb4f5434944aaa56c70eb54ec6af84c68ce6a4ec329f6290f48a863b", + "expectedOutcome": "REJECT", + "expectedReason": "E_MANIFEST_NOT_UTF8", + "note": "The manifest region is 0xFF repeated, which is not valid UTF-8 at any offset." + }, + { + "file": "12-manifest-not-json.tbicb", + "sizeBytes": 575, + "sha256": "b18a78cb214fe5c6bd2c37ecdb7c662b525ae09c33ff7ac2fc900f41b574d7a3", + "expectedOutcome": "REJECT", + "expectedReason": "E_MANIFEST_NOT_JSON", + "note": "Valid UTF-8 of the right length that is not a JSON object." + }, + { + "file": "13-manifest-missing-field.tbicb", + "sizeBytes": 524, + "sha256": "fc4078744b432e9aae55617709237b6b5c3914bf42c6233185cdc5ee1d4e4c06", + "expectedOutcome": "REJECT", + "expectedReason": "E_MANIFEST_FIELD", + "note": "clusterId removed with every declared length recomputed; the reason names the missing field." + }, + { + "file": "14-expired-challenge.tbicb", + "sizeBytes": 575, + "sha256": "0389de376b9043f38cf383ef0a1282ce44d1dfb35d227ce1a0dc719758078289", + "expectedOutcome": "ACCEPT_WITH_WARNING", + "expectedReason": "W_CHALLENGE_EXPIRED", + "note": "A well-formed bundle whose challenge expired on 2021-01-02; expiry is a warning, not a rejection." + }, + { + "file": "15-relsig-not-tbicsig1.tbicb", + "sizeBytes": 575, + "sha256": "626c7a570eade192fc048cadf134d738fd1b853d42a33ad4ef8dd1624aa36dff", + "expectedOutcome": "ACCEPT", + "expectedReason": null, + "note": "RELSIG's magic is corrupted; the parser passes RELSIG through unchecked and the release-signature verifier refuses it." + } + ] +} diff --git a/application/src/test/resources/install/pre-upgrade-schema-entities.sql b/application/src/test/resources/install/pre-upgrade-schema-entities.sql new file mode 100644 index 0000000000..7784bd87c4 --- /dev/null +++ b/application/src/test/resources/install/pre-upgrade-schema-entities.sql @@ -0,0 +1,997 @@ +-- +-- Copyright © 2016-2026 The Thingsboard Authors +-- +-- Licensed under the Apache License, Version 2.0 (the "License"); +-- you may not use this file except in compliance with the License. +-- You may obtain a copy of the License at +-- +-- http://www.apache.org/licenses/LICENSE-2.0 +-- +-- Unless required by applicable law or agreed to in writing, software +-- distributed under the License is distributed on an "AS IS" BASIS, +-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +-- See the License for the specific language governing permissions and +-- limitations under the License. +-- + +-- schema-entities.sql as it was before tb_cluster was added. Never update it: SchemaUpdateSqlUpgradeOrderTest +-- relies on tb_cluster being absent. + + +CREATE TABLE IF NOT EXISTS tb_schema_settings +( + schema_version bigint NOT NULL, + product varchar(2) NOT NULL, + CONSTRAINT tb_schema_settings_pkey PRIMARY KEY (schema_version) +); + +CREATE TABLE IF NOT EXISTS admin_settings ( + id uuid NOT NULL CONSTRAINT admin_settings_pkey PRIMARY KEY, + tenant_id uuid NOT NULL, + created_time bigint NOT NULL, + json_value varchar, + key varchar(255) +); + +CREATE TABLE IF NOT EXISTS alarm ( + id uuid NOT NULL CONSTRAINT alarm_pkey PRIMARY KEY, + created_time bigint NOT NULL, + ack_ts bigint, + clear_ts bigint, + additional_info varchar, + end_ts bigint, + originator_id uuid, + originator_type integer, + propagate boolean, + severity varchar(255), + start_ts bigint, + assign_ts bigint DEFAULT 0, + assignee_id uuid, + tenant_id uuid, + customer_id uuid, + propagate_relation_types varchar, + type varchar(255), + propagate_to_owner boolean, + propagate_to_tenant boolean, + acknowledged boolean, + cleared boolean +); + +CREATE TABLE IF NOT EXISTS alarm_comment ( + id uuid NOT NULL, + created_time bigint NOT NULL, + alarm_id uuid NOT NULL, + user_id uuid, + type varchar(255) NOT NULL, + comment varchar(10000), + CONSTRAINT fk_alarm_comment_alarm_id FOREIGN KEY (alarm_id) REFERENCES alarm(id) ON DELETE CASCADE +) PARTITION BY RANGE (created_time); + +CREATE TABLE IF NOT EXISTS entity_alarm ( + tenant_id uuid NOT NULL, + entity_type varchar(32), + entity_id uuid NOT NULL, + created_time bigint NOT NULL, + alarm_type varchar(255) NOT NULL, + customer_id uuid, + alarm_id uuid, + CONSTRAINT entity_alarm_pkey PRIMARY KEY (entity_id, alarm_id), + CONSTRAINT fk_entity_alarm_id FOREIGN KEY (alarm_id) REFERENCES alarm(id) ON DELETE CASCADE +); + +CREATE TABLE IF NOT EXISTS audit_log ( + id uuid NOT NULL, + created_time bigint NOT NULL, + tenant_id uuid, + customer_id uuid, + entity_id uuid, + entity_type varchar(255), + entity_name varchar(255), + user_id uuid, + user_name varchar(255), + action_type varchar(255), + action_data varchar(1000000), + action_status varchar(255), + action_failure_details varchar(1000000) +) PARTITION BY RANGE (created_time); + +CREATE SEQUENCE IF NOT EXISTS attribute_kv_version_seq cache 1; + +CREATE TABLE IF NOT EXISTS attribute_kv ( + entity_id uuid, + attribute_type int, + attribute_key int, + bool_v boolean, + str_v varchar(10000000), + long_v bigint, + dbl_v double precision, + json_v json, + last_update_ts bigint, + version bigint default 0, + CONSTRAINT attribute_kv_pkey PRIMARY KEY (entity_id, attribute_type, attribute_key) +); + +CREATE TABLE IF NOT EXISTS component_descriptor ( + id uuid NOT NULL CONSTRAINT component_descriptor_pkey PRIMARY KEY, + created_time bigint NOT NULL, + actions varchar(255), + clazz varchar UNIQUE, + configuration_descriptor varchar, + configuration_version int DEFAULT 0, + name varchar(255), + scope varchar(255), + type varchar(255), + clustering_mode varchar(255), + has_queue_name boolean DEFAULT false +); + +CREATE TABLE IF NOT EXISTS customer ( + id uuid NOT NULL CONSTRAINT customer_pkey PRIMARY KEY, + created_time bigint NOT NULL, + additional_info varchar, + address varchar, + address2 varchar, + city varchar(255), + country varchar(255), + email varchar(255), + phone varchar(255), + state varchar(255), + tenant_id uuid, + title varchar(255), + zip varchar(255), + external_id uuid, + is_public boolean, + version BIGINT DEFAULT 1, + CONSTRAINT customer_title_unq_key UNIQUE (tenant_id, title), + CONSTRAINT customer_external_id_unq_key UNIQUE (tenant_id, external_id) +); + +CREATE TABLE IF NOT EXISTS dashboard ( + id uuid NOT NULL CONSTRAINT dashboard_pkey PRIMARY KEY, + created_time bigint NOT NULL, + configuration varchar, + assigned_customers varchar(1000000), + tenant_id uuid, + title varchar(255), + mobile_hide boolean DEFAULT false, + mobile_order int, + image varchar(1000000), + external_id uuid, + version BIGINT DEFAULT 1, + CONSTRAINT dashboard_external_id_unq_key UNIQUE (tenant_id, external_id) +); + +CREATE TABLE IF NOT EXISTS rule_chain ( + id uuid NOT NULL CONSTRAINT rule_chain_pkey PRIMARY KEY, + created_time bigint NOT NULL, + additional_info varchar, + configuration varchar(10000000), + name varchar(255), + type varchar(255), + first_rule_node_id uuid, + root boolean, + debug_mode boolean, + tenant_id uuid, + external_id uuid, + version BIGINT DEFAULT 1, + CONSTRAINT rule_chain_external_id_unq_key UNIQUE (tenant_id, external_id) +); + +CREATE TABLE IF NOT EXISTS rule_node ( + id uuid NOT NULL CONSTRAINT rule_node_pkey PRIMARY KEY, + created_time bigint NOT NULL, + rule_chain_id uuid, + additional_info varchar, + configuration_version int DEFAULT 0, + configuration varchar(10000000), + type varchar(255), + name varchar(255), + debug_settings varchar(1024), + singleton_mode boolean, + queue_name varchar(255), + external_id uuid +); + +CREATE TABLE IF NOT EXISTS rule_node_state ( + id uuid NOT NULL CONSTRAINT rule_node_state_pkey PRIMARY KEY, + created_time bigint NOT NULL, + rule_node_id uuid NOT NULL, + entity_type varchar(32) NOT NULL, + entity_id uuid NOT NULL, + state_data varchar(16384) NOT NULL, + CONSTRAINT rule_node_state_unq_key UNIQUE (rule_node_id, entity_id), + CONSTRAINT fk_rule_node_state_node_id FOREIGN KEY (rule_node_id) REFERENCES rule_node(id) ON DELETE CASCADE +); + +CREATE TABLE IF NOT EXISTS ota_package ( + id uuid NOT NULL CONSTRAINT ota_package_pkey PRIMARY KEY, + created_time bigint NOT NULL, + tenant_id uuid NOT NULL, + device_profile_id uuid , + type varchar(32) NOT NULL, + title varchar(255) NOT NULL, + version varchar(255) NOT NULL, + tag varchar(255), + url varchar(255), + file_name varchar(255), + content_type varchar(255), + checksum_algorithm varchar(32), + checksum varchar(1020), + data oid, + data_size bigint, + additional_info varchar, + external_id uuid, + CONSTRAINT ota_package_tenant_title_version_unq_key UNIQUE (tenant_id, title, version), + CONSTRAINT ota_package_external_id_unq_key UNIQUE (tenant_id, external_id) +); + +CREATE TABLE IF NOT EXISTS queue ( + id uuid NOT NULL CONSTRAINT queue_pkey PRIMARY KEY, + created_time bigint NOT NULL, + tenant_id uuid, + name varchar(255), + topic varchar(255), + poll_interval int, + partitions int, + consumer_per_partition boolean, + pack_processing_timeout bigint, + submit_strategy varchar(255), + processing_strategy varchar(255), + additional_info varchar +); + +CREATE TABLE IF NOT EXISTS asset_profile ( + id uuid NOT NULL CONSTRAINT asset_profile_pkey PRIMARY KEY, + created_time bigint NOT NULL, + name varchar(255), + image varchar(1000000), + description varchar, + is_default boolean, + tenant_id uuid, + default_rule_chain_id uuid, + default_dashboard_id uuid, + default_queue_name varchar(255), + default_edge_rule_chain_id uuid, + external_id uuid, + version BIGINT DEFAULT 1, + CONSTRAINT asset_profile_name_unq_key UNIQUE (tenant_id, name), + CONSTRAINT asset_profile_external_id_unq_key UNIQUE (tenant_id, external_id), + CONSTRAINT fk_default_rule_chain_asset_profile FOREIGN KEY (default_rule_chain_id) REFERENCES rule_chain(id), + CONSTRAINT fk_default_dashboard_asset_profile FOREIGN KEY (default_dashboard_id) REFERENCES dashboard(id), + CONSTRAINT fk_default_edge_rule_chain_asset_profile FOREIGN KEY (default_edge_rule_chain_id) REFERENCES rule_chain(id) + ); + +CREATE TABLE IF NOT EXISTS asset ( + id uuid NOT NULL CONSTRAINT asset_pkey PRIMARY KEY, + created_time bigint NOT NULL, + additional_info varchar, + customer_id uuid, + asset_profile_id uuid NOT NULL, + name varchar(255), + label varchar(255), + tenant_id uuid, + type varchar(255), + external_id uuid, + version BIGINT DEFAULT 1, + CONSTRAINT asset_name_unq_key UNIQUE (tenant_id, name), + CONSTRAINT asset_external_id_unq_key UNIQUE (tenant_id, external_id), + CONSTRAINT fk_asset_profile FOREIGN KEY (asset_profile_id) REFERENCES asset_profile(id) +); + +CREATE TABLE IF NOT EXISTS device_profile ( + id uuid NOT NULL CONSTRAINT device_profile_pkey PRIMARY KEY, + created_time bigint NOT NULL, + name varchar(255), + type varchar(255), + image varchar(1000000), + transport_type varchar(255), + provision_type varchar(255), + profile_data jsonb, + description varchar, + is_default boolean, + tenant_id uuid, + firmware_id uuid, + software_id uuid, + default_rule_chain_id uuid, + default_dashboard_id uuid, + default_queue_name varchar(255), + provision_device_key varchar, + default_edge_rule_chain_id uuid, + external_id uuid, + version BIGINT DEFAULT 1, + CONSTRAINT device_profile_name_unq_key UNIQUE (tenant_id, name), + CONSTRAINT device_provision_key_unq_key UNIQUE (provision_device_key), + CONSTRAINT device_profile_external_id_unq_key UNIQUE (tenant_id, external_id), + CONSTRAINT fk_default_rule_chain_device_profile FOREIGN KEY (default_rule_chain_id) REFERENCES rule_chain(id), + CONSTRAINT fk_default_dashboard_device_profile FOREIGN KEY (default_dashboard_id) REFERENCES dashboard(id), + CONSTRAINT fk_firmware_device_profile FOREIGN KEY (firmware_id) REFERENCES ota_package(id), + CONSTRAINT fk_software_device_profile FOREIGN KEY (software_id) REFERENCES ota_package(id), + CONSTRAINT fk_default_edge_rule_chain_device_profile FOREIGN KEY (default_edge_rule_chain_id) REFERENCES rule_chain(id) +); + +DO +$$ + BEGIN + IF NOT EXISTS(SELECT 1 FROM pg_constraint WHERE conname = 'fk_device_profile_ota_package') THEN + ALTER TABLE ota_package + ADD CONSTRAINT fk_device_profile_ota_package + FOREIGN KEY (device_profile_id) REFERENCES device_profile (id) + ON DELETE CASCADE; + END IF; + END; +$$; + +-- We will use one-to-many relation in the first release and extend this feature in case of user requests +-- CREATE TABLE IF NOT EXISTS device_profile_firmware ( +-- device_profile_id uuid NOT NULL, +-- firmware_id uuid NOT NULL, +-- CONSTRAINT device_profile_firmware_unq_key UNIQUE (device_profile_id, firmware_id), +-- CONSTRAINT fk_device_profile_firmware_device_profile FOREIGN KEY (device_profile_id) REFERENCES device_profile(id) ON DELETE CASCADE, +-- CONSTRAINT fk_device_profile_firmware_firmware FOREIGN KEY (firmware_id) REFERENCES firmware(id) ON DELETE CASCADE, +-- ); + +CREATE TABLE IF NOT EXISTS device ( + id uuid NOT NULL CONSTRAINT device_pkey PRIMARY KEY, + created_time bigint NOT NULL, + additional_info varchar, + customer_id uuid, + device_profile_id uuid NOT NULL, + device_data jsonb, + type varchar(255), + name varchar(255), + label varchar(255), + tenant_id uuid, + firmware_id uuid, + software_id uuid, + external_id uuid, + version BIGINT DEFAULT 1, + CONSTRAINT device_name_unq_key UNIQUE (tenant_id, name), + CONSTRAINT device_external_id_unq_key UNIQUE (tenant_id, external_id), + CONSTRAINT fk_device_profile FOREIGN KEY (device_profile_id) REFERENCES device_profile(id), + CONSTRAINT fk_firmware_device FOREIGN KEY (firmware_id) REFERENCES ota_package(id), + CONSTRAINT fk_software_device FOREIGN KEY (software_id) REFERENCES ota_package(id) +); + +CREATE TABLE IF NOT EXISTS device_credentials ( + id uuid NOT NULL CONSTRAINT device_credentials_pkey PRIMARY KEY, + created_time bigint NOT NULL, + credentials_id varchar, + credentials_type varchar(255), + credentials_value varchar, + device_id uuid, + version BIGINT DEFAULT 1, + CONSTRAINT device_credentials_id_unq_key UNIQUE (credentials_id), + CONSTRAINT device_credentials_device_id_unq_key UNIQUE (device_id) +); + +CREATE TABLE IF NOT EXISTS rule_node_debug_event ( + id uuid NOT NULL, + tenant_id uuid NOT NULL , + ts bigint NOT NULL, + entity_id uuid NOT NULL, + service_id varchar, + e_type varchar, + e_entity_id uuid, + e_entity_type varchar, + e_msg_id uuid, + e_msg_type varchar, + e_data_type varchar, + e_relation_type varchar, + e_data varchar, + e_metadata varchar, + e_error varchar +) PARTITION BY RANGE (ts); + +CREATE TABLE IF NOT EXISTS rule_chain_debug_event ( + id uuid NOT NULL, + tenant_id uuid NOT NULL, + ts bigint NOT NULL, + entity_id uuid NOT NULL, + service_id varchar NOT NULL, + e_message varchar, + e_error varchar +) PARTITION BY RANGE (ts); + +CREATE TABLE IF NOT EXISTS stats_event ( + id uuid NOT NULL, + tenant_id uuid NOT NULL, + ts bigint NOT NULL, + entity_id uuid NOT NULL, + service_id varchar NOT NULL, + e_messages_processed bigint NOT NULL, + e_errors_occurred bigint NOT NULL +) PARTITION BY RANGE (ts); + +CREATE TABLE IF NOT EXISTS lc_event ( + id uuid NOT NULL, + tenant_id uuid NOT NULL, + ts bigint NOT NULL, + entity_id uuid NOT NULL, + service_id varchar NOT NULL, + e_type varchar NOT NULL, + e_success boolean NOT NULL, + e_error varchar +) PARTITION BY RANGE (ts); + +CREATE TABLE IF NOT EXISTS error_event ( + id uuid NOT NULL, + tenant_id uuid NOT NULL, + ts bigint NOT NULL, + entity_id uuid NOT NULL, + service_id varchar NOT NULL, + e_method varchar NOT NULL, + e_error varchar +) PARTITION BY RANGE (ts); + +CREATE SEQUENCE IF NOT EXISTS relation_version_seq cache 1; + +CREATE TABLE IF NOT EXISTS relation ( + from_id uuid, + from_type varchar(255), + to_id uuid, + to_type varchar(255), + relation_type_group varchar(255), + relation_type varchar(255), + additional_info varchar, + version bigint default 0, + CONSTRAINT relation_pkey PRIMARY KEY (from_id, from_type, relation_type_group, relation_type, to_id, to_type) +); + +CREATE TABLE IF NOT EXISTS tb_user ( + id uuid NOT NULL CONSTRAINT tb_user_pkey PRIMARY KEY, + created_time bigint NOT NULL, + additional_info varchar, + authority varchar(255), + customer_id uuid, + email varchar(255) UNIQUE, + first_name varchar(255), + last_name varchar(255), + phone varchar(255), + tenant_id uuid, + version BIGINT DEFAULT 1 +); + +CREATE TABLE IF NOT EXISTS tenant_profile ( + id uuid NOT NULL CONSTRAINT tenant_profile_pkey PRIMARY KEY, + created_time bigint NOT NULL, + name varchar(255), + profile_data jsonb, + description varchar, + is_default boolean, + isolated_tb_core boolean, + isolated_tb_rule_engine boolean, + CONSTRAINT tenant_profile_name_unq_key UNIQUE (name) +); + +CREATE TABLE IF NOT EXISTS tenant ( + id uuid NOT NULL CONSTRAINT tenant_pkey PRIMARY KEY, + created_time bigint NOT NULL, + additional_info varchar, + tenant_profile_id uuid NOT NULL, + address varchar, + address2 varchar, + city varchar(255), + country varchar(255), + email varchar(255), + phone varchar(255), + region varchar(255), + state varchar(255), + title varchar(255), + zip varchar(255), + version BIGINT DEFAULT 1, + CONSTRAINT fk_tenant_profile FOREIGN KEY (tenant_profile_id) REFERENCES tenant_profile(id) +); + +CREATE TABLE IF NOT EXISTS user_credentials ( + id uuid NOT NULL CONSTRAINT user_credentials_pkey PRIMARY KEY, + created_time bigint NOT NULL, + activate_token varchar(255) UNIQUE, + activate_token_exp_time BIGINT, + enabled boolean, + password varchar(255), + reset_token varchar(255) UNIQUE, + reset_token_exp_time BIGINT, + user_id uuid UNIQUE, + additional_info varchar DEFAULT '{}', + last_login_ts BIGINT, + failed_login_attempts INT +); + +CREATE TABLE IF NOT EXISTS widget_type ( + id uuid NOT NULL CONSTRAINT widget_type_pkey PRIMARY KEY, + created_time bigint NOT NULL, + fqn varchar(512), + descriptor varchar(1000000), + name varchar(255), + tenant_id uuid, + image varchar(1000000), + scada boolean NOT NULL DEFAULT false, + deprecated boolean NOT NULL DEFAULT false, + description varchar(1024), + tags text[], + external_id uuid, + version BIGINT DEFAULT 1, + CONSTRAINT uq_widget_type_fqn UNIQUE (tenant_id, fqn), + CONSTRAINT widget_type_external_id_unq_key UNIQUE (tenant_id, external_id) +); + +CREATE TABLE IF NOT EXISTS widgets_bundle ( + id uuid NOT NULL CONSTRAINT widgets_bundle_pkey PRIMARY KEY, + created_time bigint NOT NULL, + alias varchar(255), + tenant_id uuid, + title varchar(255), + image varchar(1000000), + scada boolean NOT NULL DEFAULT false, + description varchar(1024), + widgets_bundle_order int, + external_id uuid, + version BIGINT DEFAULT 1, + CONSTRAINT uq_widgets_bundle_alias UNIQUE (tenant_id, alias), + CONSTRAINT widgets_bundle_external_id_unq_key UNIQUE (tenant_id, external_id) +); + +CREATE TABLE IF NOT EXISTS widgets_bundle_widget ( + widgets_bundle_id uuid NOT NULL, + widget_type_id uuid NOT NULL, + widget_type_order int NOT NULL DEFAULT 0, + CONSTRAINT widgets_bundle_widget_pkey PRIMARY KEY (widgets_bundle_id, widget_type_id), + CONSTRAINT fk_widgets_bundle FOREIGN KEY (widgets_bundle_id) REFERENCES widgets_bundle(id) ON DELETE CASCADE, + CONSTRAINT fk_widget_type FOREIGN KEY (widget_type_id) REFERENCES widget_type(id) ON DELETE CASCADE +); + +CREATE TABLE IF NOT EXISTS entity_view ( + id uuid NOT NULL CONSTRAINT entity_view_pkey PRIMARY KEY, + created_time bigint NOT NULL, + entity_id uuid, + entity_type varchar(255), + tenant_id uuid, + customer_id uuid, + type varchar(255), + name varchar(255), + keys varchar(10000000), + start_ts bigint, + end_ts bigint, + additional_info varchar, + external_id uuid, + version BIGINT DEFAULT 1, + CONSTRAINT entity_view_external_id_unq_key UNIQUE (tenant_id, external_id) +); + +CREATE SEQUENCE IF NOT EXISTS ts_kv_latest_version_seq cache 1; + +CREATE TABLE IF NOT EXISTS ts_kv_latest +( + entity_id uuid NOT NULL, + key int NOT NULL, + ts bigint NOT NULL, + bool_v boolean, + str_v varchar(10000000), + long_v bigint, + dbl_v double precision, + json_v json, + version bigint default 0, + CONSTRAINT ts_kv_latest_pkey PRIMARY KEY (entity_id, key) +); + +CREATE TABLE IF NOT EXISTS key_dictionary +( + key varchar(255) NOT NULL, + key_id serial UNIQUE, + CONSTRAINT key_dictionary_id_pkey PRIMARY KEY (key) +); + +CREATE TABLE IF NOT EXISTS oauth2_client ( + id uuid NOT NULL CONSTRAINT oauth2_client_pkey PRIMARY KEY, + created_time bigint NOT NULL, + tenant_id uuid NOT NULL, + title varchar(100) NOT NULL, + additional_info varchar, + client_id varchar(255), + client_secret varchar(2048), + authorization_uri varchar(255), + token_uri varchar(255), + scope varchar(255), + platforms varchar(255), + user_info_uri varchar(255), + user_name_attribute_name varchar(255), + jwk_set_uri varchar(255), + client_authentication_method varchar(255), + login_button_label varchar(255), + login_button_icon varchar(255), + allow_user_creation boolean, + activate_user boolean, + type varchar(31), + basic_email_attribute_key varchar(31), + basic_first_name_attribute_key varchar(31), + basic_last_name_attribute_key varchar(31), + basic_tenant_name_strategy varchar(31), + basic_tenant_name_pattern varchar(255), + basic_customer_name_pattern varchar(255), + basic_default_dashboard_name varchar(255), + basic_always_full_screen boolean, + custom_url varchar(255), + custom_username varchar(255), + custom_password varchar(255), + custom_send_token boolean +); + +CREATE TABLE IF NOT EXISTS domain ( + id uuid NOT NULL CONSTRAINT domain_pkey PRIMARY KEY, + created_time bigint NOT NULL, + tenant_id uuid NOT NULL, + name varchar(255) UNIQUE, + oauth2_enabled boolean, + edge_enabled boolean +); + +CREATE TABLE IF NOT EXISTS mobile_app ( + id uuid NOT NULL CONSTRAINT mobile_app_pkey PRIMARY KEY, + created_time bigint NOT NULL, + tenant_id uuid, + pkg_name varchar(255), + title varchar(255), + app_secret varchar(2048), + platform_type varchar(32), + status varchar(32), + version_info varchar(100000), + store_info varchar(16384), + CONSTRAINT mobile_app_pkg_name_platform_unq_key UNIQUE (pkg_name, platform_type) +); + +CREATE TABLE IF NOT EXISTS mobile_app_bundle ( + id uuid NOT NULL CONSTRAINT mobile_app_bundle_pkey PRIMARY KEY, + created_time bigint NOT NULL, + tenant_id uuid, + title varchar(255), + description varchar(1024), + android_app_id uuid UNIQUE, + ios_app_id uuid UNIQUE, + layout_config varchar(16384), + oauth2_enabled boolean, + CONSTRAINT fk_android_app_id FOREIGN KEY (android_app_id) REFERENCES mobile_app(id) ON DELETE SET NULL, + CONSTRAINT fk_ios_app_id FOREIGN KEY (ios_app_id) REFERENCES mobile_app(id) ON DELETE SET NULL +); + +CREATE TABLE IF NOT EXISTS domain_oauth2_client ( + domain_id uuid NOT NULL, + oauth2_client_id uuid NOT NULL, + CONSTRAINT fk_domain FOREIGN KEY (domain_id) REFERENCES domain(id) ON DELETE CASCADE, + CONSTRAINT fk_oauth2_client FOREIGN KEY (oauth2_client_id) REFERENCES oauth2_client(id) ON DELETE CASCADE +); + +CREATE TABLE IF NOT EXISTS mobile_app_bundle_oauth2_client ( + mobile_app_bundle_id uuid NOT NULL, + oauth2_client_id uuid NOT NULL, + CONSTRAINT fk_domain FOREIGN KEY (mobile_app_bundle_id) REFERENCES mobile_app_bundle(id) ON DELETE CASCADE, + CONSTRAINT fk_oauth2_client FOREIGN KEY (oauth2_client_id) REFERENCES oauth2_client(id) ON DELETE CASCADE +); + +CREATE TABLE IF NOT EXISTS oauth2_client_registration_template ( + id uuid NOT NULL CONSTRAINT oauth2_client_registration_template_pkey PRIMARY KEY, + created_time bigint NOT NULL, + additional_info varchar, + provider_id varchar(255), + authorization_uri varchar(255), + token_uri varchar(255), + scope varchar(255), + user_info_uri varchar(255), + user_name_attribute_name varchar(255), + jwk_set_uri varchar(255), + client_authentication_method varchar(255), + type varchar(31), + basic_email_attribute_key varchar(31), + basic_first_name_attribute_key varchar(31), + basic_last_name_attribute_key varchar(31), + basic_tenant_name_strategy varchar(31), + basic_tenant_name_pattern varchar(255), + basic_customer_name_pattern varchar(255), + basic_default_dashboard_name varchar(255), + basic_always_full_screen boolean, + comment varchar, + login_button_icon varchar(255), + login_button_label varchar(255), + help_link varchar(255), + CONSTRAINT oauth2_template_provider_id_unq_key UNIQUE (provider_id) +); + +CREATE TABLE IF NOT EXISTS api_usage_state ( + id uuid NOT NULL CONSTRAINT usage_record_pkey PRIMARY KEY, + created_time bigint NOT NULL, + tenant_id uuid, + entity_type varchar(32), + entity_id uuid, + transport varchar(32), + db_storage varchar(32), + re_exec varchar(32), + js_exec varchar(32), + tbel_exec varchar(32), + email_exec varchar(32), + sms_exec varchar(32), + alarm_exec varchar(32), + version BIGINT DEFAULT 1, + CONSTRAINT api_usage_state_unq_key UNIQUE (tenant_id, entity_id) +); + +CREATE TABLE IF NOT EXISTS api_key ( + id uuid NOT NULL CONSTRAINT api_key_pkey PRIMARY KEY, + created_time bigint NOT NULL, + tenant_id uuid, + user_id uuid, + value varchar(512), + enabled boolean NOT NULL DEFAULT TRUE, + expiration_time bigint DEFAULT 0, + description varchar(255), + CONSTRAINT api_key_value_unq_key UNIQUE (value) +); + +CREATE TABLE IF NOT EXISTS resource ( + id uuid NOT NULL CONSTRAINT resource_pkey PRIMARY KEY, + created_time bigint NOT NULL, + tenant_id uuid NOT NULL, + title varchar(255) NOT NULL, + resource_type varchar(32) NOT NULL, + resource_sub_type varchar(32), + resource_key varchar(255) NOT NULL, + search_text varchar(255), + file_name varchar(255) NOT NULL, + data bytea, + etag varchar, + descriptor varchar, + preview bytea, + is_public boolean default true, + public_resource_key varchar(32) unique, + external_id uuid, + CONSTRAINT resource_unq_key UNIQUE (tenant_id, resource_type, resource_key) +); + +CREATE TABLE IF NOT EXISTS edge ( + id uuid NOT NULL CONSTRAINT edge_pkey PRIMARY KEY, + created_time bigint NOT NULL, + additional_info varchar, + customer_id uuid, + root_rule_chain_id uuid, + type varchar(255), + name varchar(255), + label varchar(255), + routing_key varchar(255), + secret varchar(255), + tenant_id uuid, + version BIGINT DEFAULT 1, + CONSTRAINT edge_name_unq_key UNIQUE (tenant_id, name), + CONSTRAINT edge_routing_key_unq_key UNIQUE (routing_key) +); + +CREATE TABLE IF NOT EXISTS edge_event ( + seq_id INT GENERATED ALWAYS AS IDENTITY, + id uuid NOT NULL, + created_time bigint NOT NULL, + edge_id uuid, + edge_event_type varchar(255), + edge_event_uid varchar(255), + entity_id uuid, + edge_event_action varchar(255), + body varchar(10000000), + tenant_id uuid, + ts bigint NOT NULL +) PARTITION BY RANGE(created_time); +ALTER TABLE IF EXISTS edge_event ALTER COLUMN seq_id SET CYCLE; + +CREATE TABLE IF NOT EXISTS rpc ( + id uuid NOT NULL CONSTRAINT rpc_pkey PRIMARY KEY, + created_time bigint NOT NULL, + tenant_id uuid NOT NULL, + device_id uuid NOT NULL, + expiration_time bigint NOT NULL, + request varchar(10000000) NOT NULL, + response varchar(10000000), + additional_info varchar(10000000), + status varchar(255) NOT NULL +); + +CREATE OR REPLACE FUNCTION to_uuid(IN entity_id varchar, OUT uuid_id uuid) AS +$$ +BEGIN + uuid_id := substring(entity_id, 8, 8) || '-' || substring(entity_id, 4, 4) || '-1' || substring(entity_id, 1, 3) || + '-' || substring(entity_id, 16, 4) || '-' || substring(entity_id, 20, 12); +END; +$$ LANGUAGE plpgsql; + + +CREATE OR REPLACE PROCEDURE cleanup_edge_events_by_ttl(IN ttl bigint, INOUT deleted bigint) + LANGUAGE plpgsql AS +$$ +DECLARE + ttl_ts bigint; + ttl_deleted_count bigint DEFAULT 0; +BEGIN + IF ttl > 0 THEN + ttl_ts := (EXTRACT(EPOCH FROM current_timestamp) * 1000 - ttl::bigint * 1000)::bigint; + EXECUTE format( + 'WITH deleted AS (DELETE FROM edge_event WHERE ts < %L::bigint RETURNING *) SELECT count(*) FROM deleted', ttl_ts) into ttl_deleted_count; + END IF; + RAISE NOTICE 'Edge events removed by ttl: %', ttl_deleted_count; + deleted := ttl_deleted_count; +END +$$; + + +CREATE TABLE IF NOT EXISTS user_auth_settings ( + id uuid NOT NULL CONSTRAINT user_auth_settings_pkey PRIMARY KEY, + created_time bigint NOT NULL, + user_id uuid UNIQUE NOT NULL CONSTRAINT fk_user_auth_settings_user_id REFERENCES tb_user(id), + two_fa_settings varchar +); + +CREATE TABLE IF NOT EXISTS notification_target ( + id UUID NOT NULL CONSTRAINT notification_target_pkey PRIMARY KEY, + created_time BIGINT NOT NULL, + tenant_id UUID NOT NULL, + name VARCHAR(255) NOT NULL, + configuration VARCHAR(10000) NOT NULL, + external_id UUID, + CONSTRAINT uq_notification_target_name UNIQUE (tenant_id, name), + CONSTRAINT uq_notification_target_external_id UNIQUE (tenant_id, external_id) +); + +CREATE TABLE IF NOT EXISTS notification_template ( + id UUID NOT NULL CONSTRAINT notification_template_pkey PRIMARY KEY, + created_time BIGINT NOT NULL, + tenant_id UUID NOT NULL, + name VARCHAR(255) NOT NULL, + notification_type VARCHAR(50) NOT NULL, + configuration VARCHAR(10000000) NOT NULL, + external_id UUID, + CONSTRAINT uq_notification_template_name UNIQUE (tenant_id, name), + CONSTRAINT uq_notification_template_external_id UNIQUE (tenant_id, external_id) +); + +CREATE TABLE IF NOT EXISTS notification_rule ( + id UUID NOT NULL CONSTRAINT notification_rule_pkey PRIMARY KEY, + created_time BIGINT NOT NULL, + tenant_id UUID NOT NULL, + name VARCHAR(255) NOT NULL, + enabled BOOLEAN NOT NULL DEFAULT true, + template_id UUID NOT NULL CONSTRAINT fk_notification_rule_template_id REFERENCES notification_template(id), + trigger_type VARCHAR(50) NOT NULL, + trigger_config VARCHAR(1000) NOT NULL, + recipients_config VARCHAR(10000) NOT NULL, + additional_config VARCHAR(255), + external_id UUID, + CONSTRAINT uq_notification_rule_name UNIQUE (tenant_id, name), + CONSTRAINT uq_notification_rule_external_id UNIQUE (tenant_id, external_id) +); + +CREATE TABLE IF NOT EXISTS notification_request ( + id UUID NOT NULL CONSTRAINT notification_request_pkey PRIMARY KEY, + created_time BIGINT NOT NULL, + tenant_id UUID NOT NULL, + targets VARCHAR(10000) NOT NULL, + template_id UUID, + template VARCHAR(10000000), + info VARCHAR(1000000), + additional_config VARCHAR(1000), + originator_entity_id UUID, + originator_entity_type VARCHAR(32), + rule_id UUID NULL, + status VARCHAR(32), + stats VARCHAR(10000) +); + +CREATE TABLE IF NOT EXISTS notification ( + id UUID NOT NULL, + created_time BIGINT NOT NULL, + request_id UUID, + recipient_id UUID NOT NULL, + type VARCHAR(50) NOT NULL, + delivery_method VARCHAR(50) NOT NULL, + subject VARCHAR(255), + body VARCHAR(1000) NOT NULL, + additional_config VARCHAR(1000), + status VARCHAR(32) +) PARTITION BY RANGE (created_time); + +CREATE TABLE IF NOT EXISTS user_settings ( + user_id uuid NOT NULL, + type VARCHAR(50) NOT NULL, + settings jsonb, + CONSTRAINT fk_user_id FOREIGN KEY (user_id) REFERENCES tb_user(id) ON DELETE CASCADE, + CONSTRAINT user_settings_pkey PRIMARY KEY (user_id, type) +); + +CREATE TABLE IF NOT EXISTS alarm_types ( + tenant_id uuid NOT NULL, + type varchar(255) NOT NULL, + CONSTRAINT tenant_id_type_unq_key UNIQUE (tenant_id, type), + CONSTRAINT fk_entity_tenant_id FOREIGN KEY (tenant_id) REFERENCES tenant(id) ON DELETE CASCADE +); + +CREATE TABLE IF NOT EXISTS queue_stats ( + id uuid NOT NULL CONSTRAINT queue_stats_pkey PRIMARY KEY, + created_time bigint NOT NULL, + tenant_id uuid NOT NULL, + queue_name varchar(255) NOT NULL, + service_id varchar(255) NOT NULL, + CONSTRAINT queue_stats_name_unq_key UNIQUE (tenant_id, queue_name, service_id) +); + +CREATE TABLE IF NOT EXISTS qr_code_settings ( + id uuid NOT NULL CONSTRAINT qr_code_settings_pkey PRIMARY KEY, + created_time bigint NOT NULL, + tenant_id uuid NOT NULL, + use_default_app boolean, + android_enabled boolean, + ios_enabled boolean, + mobile_app_bundle_id uuid, + qr_code_config VARCHAR(100000), + CONSTRAINT qr_code_settings_tenant_id_unq_key UNIQUE (tenant_id) +); + +CREATE TABLE IF NOT EXISTS calculated_field ( + id uuid NOT NULL CONSTRAINT calculated_field_pkey PRIMARY KEY, + created_time bigint NOT NULL, + tenant_id uuid NOT NULL, + entity_type VARCHAR(32), + entity_id uuid NOT NULL, + type varchar(32) NOT NULL, + name varchar(255) NOT NULL, + configuration_version int DEFAULT 0, + configuration varchar(1000000), + version BIGINT DEFAULT 1, + debug_settings varchar(1024), + additional_info varchar, + CONSTRAINT calculated_field_unq_key UNIQUE (entity_id, type, name) +); + +CREATE TABLE IF NOT EXISTS cf_debug_event ( + id uuid NOT NULL, + tenant_id uuid NOT NULL , + ts bigint NOT NULL, + entity_id uuid NOT NULL, -- calculated field id + service_id varchar, + cf_id uuid NOT NULL, + e_entity_id uuid, -- target entity id + e_entity_type varchar, + e_msg_id uuid, + e_msg_type varchar, + e_args varchar, + e_result varchar, + e_error varchar +) PARTITION BY RANGE (ts); + +CREATE TABLE IF NOT EXISTS job ( + id uuid NOT NULL CONSTRAINT job_pkey PRIMARY KEY, + created_time bigint NOT NULL, + tenant_id uuid NOT NULL, + type varchar NOT NULL, + key varchar NOT NULL, + entity_id uuid NOT NULL, + entity_type varchar NOT NULL, + status varchar NOT NULL, + configuration varchar NOT NULL, + result varchar +); + +CREATE TABLE IF NOT EXISTS ai_model ( + id UUID NOT NULL PRIMARY KEY, + external_id UUID, + created_time BIGINT NOT NULL, + tenant_id UUID NOT NULL, + version BIGINT NOT NULL DEFAULT 1, + name VARCHAR(255) NOT NULL, + configuration JSONB NOT NULL, + CONSTRAINT ai_model_name_unq_key UNIQUE (tenant_id, name), + CONSTRAINT ai_model_external_id_unq_key UNIQUE (tenant_id, external_id) +); + +CREATE TABLE IF NOT EXISTS iot_hub_installed_item ( + id UUID NOT NULL PRIMARY KEY, + created_time BIGINT NOT NULL, + tenant_id UUID NOT NULL, + item_id UUID NOT NULL, + item_version_id UUID NOT NULL, + item_name VARCHAR NOT NULL, + item_type VARCHAR NOT NULL, + version VARCHAR NOT NULL, + descriptor JSONB NOT NULL +); diff --git a/common/data/src/main/java/org/thingsboard/server/common/data/audit/ActionType.java b/common/data/src/main/java/org/thingsboard/server/common/data/audit/ActionType.java index 712c5b72a1..ca5df45181 100644 --- a/common/data/src/main/java/org/thingsboard/server/common/data/audit/ActionType.java +++ b/common/data/src/main/java/org/thingsboard/server/common/data/audit/ActionType.java @@ -206,7 +206,19 @@ public enum ActionType { /** * SMS sent. Does not push to rule engine. */ - SMS_SENT; + SMS_SENT, + /** + * Community Grant instance checker run from an uploaded bundle. Does not push to rule engine. + */ + COMMUNITY_GRANT_OFFLINE_CHECKER_RUN, + /** + * Community Grant access request to the registered owner. Does not push to rule engine. + */ + COMMUNITY_GRANT_REQUEST_ACCESS, + /** + * Community Grant enrollment started or its report declared handed over. Does not push to rule engine. + */ + COMMUNITY_GRANT_ENROLLMENT; @Getter private final boolean read; diff --git a/common/data/src/main/java/org/thingsboard/server/common/data/community_grant/CommunityGrantFlowState.java b/common/data/src/main/java/org/thingsboard/server/common/data/community_grant/CommunityGrantFlowState.java new file mode 100644 index 0000000000..6c0edeeaae --- /dev/null +++ b/common/data/src/main/java/org/thingsboard/server/common/data/community_grant/CommunityGrantFlowState.java @@ -0,0 +1,54 @@ +// SPDX-FileCopyrightText: Copyright The Thingsboard Authors +// SPDX-License-Identifier: Apache-2.0 +package org.thingsboard.server.common.data.community_grant; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import lombok.Data; +import lombok.NoArgsConstructor; + +import java.io.Serializable; + +/** + * The persisted community grant state, stored as a single JSON document in {@code admin_settings}. The claim + * token lives in {@code tb_cluster}, though the sign-up URL stored here quotes it. + */ +@Data +@NoArgsConstructor +@JsonIgnoreProperties(ignoreUnknown = true) +public class CommunityGrantFlowState implements Serializable { + + private static final long serialVersionUID = 1L; + + private CommunityGrantMode mode; + private CommunityGrantState state; + private String signUpUrl; + /** When {@code start()} minted the current token; bounds how long an abandoned sign-up is polled. */ + private Long startedAt; + private Long lastPolledAt; + private Long lastOfflineCheckAt; + /** When {@code requestAccess()} last attempted to reach the portal, successful or not; the cooldown's base. */ + private Long lastRequestAccessAt; + + /** + * Set on {@code RESUME} only. Outside {@link #clearClaim()}: it is written by the same update that sets + * {@code RESUME}. + */ + private CommunityGrantParkReason parkReason; + + /** The last by-hand checker run that is running or failed. */ + private CommunityGrantOfflineRun offlineRun; + + /** Drops everything scoped to the current claim token. */ + public void clearClaim() { + signUpUrl = null; + startedAt = null; + } + + public static CommunityGrantFlowState initial() { + CommunityGrantFlowState flowState = new CommunityGrantFlowState(); + flowState.setMode(CommunityGrantMode.ONLINE); + flowState.setState(CommunityGrantState.NOT_STARTED); + return flowState; + } + +} diff --git a/common/data/src/main/java/org/thingsboard/server/common/data/community_grant/CommunityGrantMode.java b/common/data/src/main/java/org/thingsboard/server/common/data/community_grant/CommunityGrantMode.java new file mode 100644 index 0000000000..faa142e4eb --- /dev/null +++ b/common/data/src/main/java/org/thingsboard/server/common/data/community_grant/CommunityGrantMode.java @@ -0,0 +1,13 @@ +// SPDX-FileCopyrightText: Copyright The Thingsboard Authors +// SPDX-License-Identifier: Apache-2.0 +package org.thingsboard.server.common.data.community_grant; + +/** + * How this deployment runs the community grant flow, chosen by the server from a reachability probe. + */ +public enum CommunityGrantMode { + + ONLINE, + OFFLINE + +} diff --git a/common/data/src/main/java/org/thingsboard/server/common/data/community_grant/CommunityGrantOfflineRun.java b/common/data/src/main/java/org/thingsboard/server/common/data/community_grant/CommunityGrantOfflineRun.java new file mode 100644 index 0000000000..afd1dd08e1 --- /dev/null +++ b/common/data/src/main/java/org/thingsboard/server/common/data/community_grant/CommunityGrantOfflineRun.java @@ -0,0 +1,41 @@ +// SPDX-FileCopyrightText: Copyright The Thingsboard Authors +// SPDX-License-Identifier: Apache-2.0 +package org.thingsboard.server.common.data.community_grant; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import lombok.Data; +import lombok.NoArgsConstructor; + +import java.io.Serializable; +import java.util.UUID; + +/** + * A by-hand checker run, recorded on the flow state so every node can report a run executing on one of them. + */ +@Data +@NoArgsConstructor +@JsonIgnoreProperties(ignoreUnknown = true) +public class CommunityGrantOfflineRun implements Serializable { + + private static final long serialVersionUID = 1L; + + /** A completion updates the record only while it still carries its own id. */ + private UUID runId; + private CommunityGrantOfflineRunStatus status; + private Long startedAt; + /** Why the run failed, safe to show to the operator. Set only on {@code FAILED}. */ + private String error; + + public static CommunityGrantOfflineRun running(UUID runId, long startedAt) { + CommunityGrantOfflineRun run = new CommunityGrantOfflineRun(); + run.setRunId(runId); + run.setStatus(CommunityGrantOfflineRunStatus.RUNNING); + run.setStartedAt(startedAt); + return run; + } + + public boolean isOwnedBy(UUID runId) { + return this.runId != null && this.runId.equals(runId); + } + +} diff --git a/common/data/src/main/java/org/thingsboard/server/common/data/community_grant/CommunityGrantOfflineRunStatus.java b/common/data/src/main/java/org/thingsboard/server/common/data/community_grant/CommunityGrantOfflineRunStatus.java new file mode 100644 index 0000000000..10eeafbac6 --- /dev/null +++ b/common/data/src/main/java/org/thingsboard/server/common/data/community_grant/CommunityGrantOfflineRunStatus.java @@ -0,0 +1,13 @@ +// SPDX-FileCopyrightText: Copyright The Thingsboard Authors +// SPDX-License-Identifier: Apache-2.0 +package org.thingsboard.server.common.data.community_grant; + +/** + * There is no success value: a run that succeeds is cleared from the flow state. + */ +public enum CommunityGrantOfflineRunStatus { + + RUNNING, + FAILED + +} diff --git a/common/data/src/main/java/org/thingsboard/server/common/data/community_grant/CommunityGrantParkReason.java b/common/data/src/main/java/org/thingsboard/server/common/data/community_grant/CommunityGrantParkReason.java new file mode 100644 index 0000000000..46bdb63943 --- /dev/null +++ b/common/data/src/main/java/org/thingsboard/server/common/data/community_grant/CommunityGrantParkReason.java @@ -0,0 +1,21 @@ +// SPDX-FileCopyrightText: Copyright The Thingsboard Authors +// SPDX-License-Identifier: Apache-2.0 +package org.thingsboard.server.common.data.community_grant; + +/** + * Why a flow parked at {@link CommunityGrantState#RESUME}. + */ +public enum CommunityGrantParkReason { + + /** The portal says the claim token expired. */ + LINK_EXPIRED, + /** + * The sign-up form was never completed within this deployment's own deadline, which also ends an + * enrollment whose portal was never reachable. + */ + SIGNUP_ABANDONED, + /** The instance checker failed its whole retry budget. Retryable. */ + CHECK_FAILED, + /** The portal stopped answering for the whole failure budget after sign-up. Retryable. */ + PORTAL_UNREACHABLE +} diff --git a/common/data/src/main/java/org/thingsboard/server/common/data/community_grant/CommunityGrantState.java b/common/data/src/main/java/org/thingsboard/server/common/data/community_grant/CommunityGrantState.java new file mode 100644 index 0000000000..bb57f02d2f --- /dev/null +++ b/common/data/src/main/java/org/thingsboard/server/common/data/community_grant/CommunityGrantState.java @@ -0,0 +1,46 @@ +// SPDX-FileCopyrightText: Copyright The Thingsboard Authors +// SPDX-License-Identifier: Apache-2.0 +package org.thingsboard.server.common.data.community_grant; + +/** + * The instance-local view of the community grant flow, largely a projection of the portal's answer. + */ +public enum CommunityGrantState { + + NOT_STARTED, + AWAITING_SIGNUP, + COLLECTING, + VALIDATING, + /** + * The operator handed a by-hand report to the portal. A wait, not an ending: where the portal is + * reachable a later poll resolves it; offline, the answer is read at the portal. + */ + REPORT_HANDED_OVER, + REGISTERED, + UNDER_REVIEW, + /** This cluster id is already enrolled by somebody else, found by the probe before any token is minted. */ + ALREADY_REGISTERED, + /** The polled claim token is bound to a different installation; this one is not registered at all. */ + WRONG_INSTALLATION, + RESUME; + + /** A state the flow never leaves on its own. Nothing polls from here and no token is held past it. */ + public boolean isTerminal() { + return this == REGISTERED || this == ALREADY_REGISTERED || this == WRONG_INSTALLATION; + } + + /** A state from which the portal is worth asking again. {@link #RESUME}'s token is already gone. */ + public boolean isPollable() { + return this == AWAITING_SIGNUP || this == COLLECTING || this == VALIDATING || this == UNDER_REVIEW + || this == REPORT_HANDED_OVER; + } + + /** + * A state no local action may move the flow out of: the portal has decided, or still owes a decision on a + * registration or report it already has. + */ + public boolean isAwaitingOrPastDecision() { + return isTerminal() || this == UNDER_REVIEW || this == REPORT_HANDED_OVER; + } + +} diff --git a/common/data/src/main/java/org/thingsboard/server/common/data/community_grant/CommunityGrantStateInfo.java b/common/data/src/main/java/org/thingsboard/server/common/data/community_grant/CommunityGrantStateInfo.java new file mode 100644 index 0000000000..bc5354451e --- /dev/null +++ b/common/data/src/main/java/org/thingsboard/server/common/data/community_grant/CommunityGrantStateInfo.java @@ -0,0 +1,38 @@ +// SPDX-FileCopyrightText: Copyright The Thingsboard Authors +// SPDX-License-Identifier: Apache-2.0 +package org.thingsboard.server.common.data.community_grant; + +/** + * Everything the widget is allowed to know: never a license key, an owner identity or a policy detail. Keep + * the TypeScript mirror in {@code community-grant.models.ts} in step. + */ +public record CommunityGrantStateInfo(CommunityGrantMode mode, + CommunityGrantState state, + String signUpUrl, + Long lastPolledAt, + CommunityGrantParkReason parkReason, + String portalUrl, + String offlineReport, + boolean offlineRunInProgress, + String offlineRunError) { + + public static CommunityGrantStateInfo of(CommunityGrantFlowState flowState, String portalUrl) { + return of(flowState, portalUrl, null, false, null); + } + + public static CommunityGrantStateInfo of(CommunityGrantFlowState flowState, String portalUrl, + String offlineReport, boolean offlineRunInProgress, + String offlineRunError) { + return new CommunityGrantStateInfo(flowState.getMode(), flowState.getState(), + flowState.getSignUpUrl(), flowState.getLastPolledAt(), flowState.getParkReason(), + portalUrl, offlineReport, offlineRunInProgress, offlineRunError); + } + + /** Only the report and hand-off screens show the report, and only once a run has been recorded. */ + public static boolean carriesOfflineReport(CommunityGrantFlowState flowState) { + CommunityGrantState state = flowState.getState(); + return (state == CommunityGrantState.VALIDATING || state == CommunityGrantState.REPORT_HANDED_OVER) + && flowState.getLastOfflineCheckAt() != null; + } + +} diff --git a/dao/src/main/java/org/thingsboard/server/dao/subscription/TbClusterStore.java b/dao/src/main/java/org/thingsboard/server/dao/subscription/TbClusterStore.java new file mode 100644 index 0000000000..44c26e57e9 --- /dev/null +++ b/dao/src/main/java/org/thingsboard/server/dao/subscription/TbClusterStore.java @@ -0,0 +1,67 @@ +// SPDX-FileCopyrightText: Copyright The Thingsboard Authors +// SPDX-License-Identifier: Apache-2.0 +package org.thingsboard.server.dao.subscription; + +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.context.annotation.Profile; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.stereotype.Component; + +import java.util.Optional; +import java.util.UUID; + +/** Accessor for the single {@code tb_cluster} row: the cluster id and the license portal claim token. */ +@Component +@Profile("!install") +@RequiredArgsConstructor +@Slf4j +public class TbClusterStore { + + private final JdbcTemplate jdbcTemplate; + + public Optional getClusterId() { + return jdbcTemplate.query("SELECT cluster_id FROM tb_cluster ORDER BY cluster_id LIMIT 1", + rs -> rs.next() ? Optional.ofNullable(rs.getObject("cluster_id", UUID.class)) : Optional.empty()); + } + + public Optional getLicenseClaimToken() { + return getColumn("license_claim_token"); + } + + public void saveLicenseClaimToken(String claimToken) { + updateColumn("license_claim_token", claimToken, "license claim token"); + } + + public void forceClearLicenseClaimToken() { + try { + jdbcTemplate.update("UPDATE tb_cluster SET license_claim_token = NULL"); + } catch (Exception e) { + log.warn("Failed to clear the license claim token", e); + } + } + + public void clearLicenseClaimToken(String expectedClaimToken) { + try { + jdbcTemplate.update("UPDATE tb_cluster SET license_claim_token = NULL WHERE license_claim_token = ?", + expectedClaimToken); + } catch (Exception e) { + log.warn("Failed to clear the license claim token", e); + } + } + + // The column name is concatenated into the statement: pass only compile-time constants. + private Optional getColumn(String column) { + return jdbcTemplate.query("SELECT " + column + " FROM tb_cluster ORDER BY cluster_id LIMIT 1", + rs -> rs.next() ? Optional.ofNullable(rs.getString(column)) : Optional.empty()); + } + + private void updateColumn(String column, String value, String description) { + int updatedRows = jdbcTemplate.update("UPDATE tb_cluster SET " + column + " = ?", value); + if (updatedRows == 0) { + log.error("Failed to store the {}: table tb_cluster is empty; the install or upgrade that creates " + + "its row has not completed", description); + throw new IllegalStateException("Failed to store the " + description + ": table tb_cluster is empty"); + } + } +} diff --git a/dao/src/main/resources/sql/schema-entities.sql b/dao/src/main/resources/sql/schema-entities.sql index b2af919cae..711eca9c53 100644 --- a/dao/src/main/resources/sql/schema-entities.sql +++ b/dao/src/main/resources/sql/schema-entities.sql @@ -3,6 +3,17 @@ -- SPDX-License-Identifier: Apache-2.0 -- +-- Also created by upgrade/lts/4.3.1.6/schema_update.sql; keep the two in sync. +CREATE TABLE IF NOT EXISTS tb_cluster ( + cluster_id uuid NOT NULL, + license_claim_token varchar, + CONSTRAINT tb_cluster_pkey PRIMARY KEY (cluster_id) +); + +-- Backstop against two concurrent install jobs both minting an id: a unique index on a constant +-- expression allows at most one row in the table, no matter how many rows race to insert. +CREATE UNIQUE INDEX IF NOT EXISTS tb_cluster_single_row ON tb_cluster ((true)); + CREATE TABLE IF NOT EXISTS tb_schema_settings ( schema_version bigint NOT NULL, diff --git a/dao/src/test/java/org/thingsboard/server/dao/subscription/TbClusterStoreTest.java b/dao/src/test/java/org/thingsboard/server/dao/subscription/TbClusterStoreTest.java new file mode 100644 index 0000000000..a2002079c8 --- /dev/null +++ b/dao/src/test/java/org/thingsboard/server/dao/subscription/TbClusterStoreTest.java @@ -0,0 +1,118 @@ +// SPDX-FileCopyrightText: Copyright The Thingsboard Authors +// SPDX-License-Identifier: Apache-2.0 +package org.thingsboard.server.dao.subscription; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.dao.DataAccessResourceFailureException; +import org.springframework.dao.DataIntegrityViolationException; +import org.springframework.jdbc.core.JdbcTemplate; +import org.thingsboard.server.dao.service.AbstractServiceTest; +import org.thingsboard.server.dao.service.DaoSqlTest; + +import java.util.Optional; +import java.util.UUID; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatCode; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.Mockito.mock; + +@DaoSqlTest +public class TbClusterStoreTest extends AbstractServiceTest { + + @Autowired + private TbClusterStore tbClusterStore; + + @Autowired + private JdbcTemplate jdbcTemplate; + + private final UUID clusterId = UUID.randomUUID(); + + @Before + public void seedClusterRow() { + jdbcTemplate.update("DELETE FROM tb_cluster"); + jdbcTemplate.update("INSERT INTO tb_cluster (cluster_id) VALUES (?)", clusterId); + } + + @After + public void cleanUpClusterRow() { + jdbcTemplate.update("DELETE FROM tb_cluster"); + } + + @Test + public void testGetClusterId() { + assertThat(tbClusterStore.getClusterId()).contains(clusterId); + } + + @Test + public void testGetClusterIdOnEmptyTable() { + jdbcTemplate.update("DELETE FROM tb_cluster"); + assertThat(tbClusterStore.getClusterId()).isEmpty(); + } + + @Test + public void testSecondRowInsertIsRejectedByUniqueIndex() { + UUID other = new UUID(0, 0); + assertThatThrownBy(() -> jdbcTemplate.update("INSERT INTO tb_cluster (cluster_id) VALUES (?)", other)) + .isInstanceOf(DataIntegrityViolationException.class); + + assertThat(tbClusterStore.getClusterId()).contains(clusterId); + } + + @Test + public void testSaveAndReadLicenseClaimToken() { + assertThat(tbClusterStore.getLicenseClaimToken()).isEmpty(); + tbClusterStore.saveLicenseClaimToken("token-one"); + assertThat(tbClusterStore.getLicenseClaimToken()).contains("token-one"); + tbClusterStore.saveLicenseClaimToken("token-two"); + assertThat(tbClusterStore.getLicenseClaimToken()).contains("token-two"); + } + + @Test + public void testClearLicenseClaimToken() { + tbClusterStore.saveLicenseClaimToken("token-one"); + tbClusterStore.forceClearLicenseClaimToken(); + assertThat(tbClusterStore.getLicenseClaimToken()).isEmpty(); + } + + @Test + public void testCompareAndClearRetiresOnlyTheExpectedToken() { + tbClusterStore.saveLicenseClaimToken("token-one"); + tbClusterStore.clearLicenseClaimToken("token-one"); + assertThat(tbClusterStore.getLicenseClaimToken()).isEmpty(); + + tbClusterStore.saveLicenseClaimToken("token-two"); + tbClusterStore.clearLicenseClaimToken("token-one"); + assertThat(tbClusterStore.getLicenseClaimToken()).contains("token-two"); + } + + @Test + public void testSaveFailsWhenClusterRowIsMissing() { + jdbcTemplate.update("DELETE FROM tb_cluster"); + assertThatThrownBy(() -> tbClusterStore.saveLicenseClaimToken("token-one")) + .isInstanceOf(IllegalStateException.class); + assertThat(tbClusterStore.getLicenseClaimToken()).isEqualTo(Optional.empty()); + } + + @Test + public void testClearNeverThrowsWhenClusterRowIsMissing() { + jdbcTemplate.update("DELETE FROM tb_cluster"); + tbClusterStore.forceClearLicenseClaimToken(); + tbClusterStore.clearLicenseClaimToken("token-one"); + assertThat(tbClusterStore.getLicenseClaimToken()).isEmpty(); + } + + @Test + public void testClearSwallowsAStoreFailureRatherThanPropagatingIt() { + JdbcTemplate failing = mock(JdbcTemplate.class, invocation -> { + throw new DataAccessResourceFailureException("the database is unreachable"); + }); + TbClusterStore store = new TbClusterStore(failing); + + assertThatCode(store::forceClearLicenseClaimToken).doesNotThrowAnyException(); + assertThatCode(() -> store.clearLicenseClaimToken("token-one")).doesNotThrowAnyException(); + } +} diff --git a/dao/src/test/resources/sql/psql/drop-all-tables.sql b/dao/src/test/resources/sql/psql/drop-all-tables.sql index 0387658f2d..bbdcfd751a 100644 --- a/dao/src/test/resources/sql/psql/drop-all-tables.sql +++ b/dao/src/test/resources/sql/psql/drop-all-tables.sql @@ -54,6 +54,7 @@ DROP TABLE IF EXISTS rule_node_state; DROP TABLE IF EXISTS rule_node; DROP TABLE IF EXISTS rule_chain; DROP TABLE IF EXISTS tb_schema_settings; +DROP TABLE IF EXISTS tb_cluster; DROP TABLE IF EXISTS oauth2_mobile; DROP TABLE IF EXISTS oauth2_domain; DROP TABLE IF EXISTS oauth2_registration; diff --git a/ui-ngx/package.json b/ui-ngx/package.json index b686e63a24..6286367864 100644 --- a/ui-ngx/package.json +++ b/ui-ngx/package.json @@ -91,6 +91,7 @@ "tooltipster": "^4.2.8", "tslib": "^2.8.1", "typeface-roboto": "^1.1.13", + "typeface-roboto-mono": "^1.1.13", "zone.js": "~0.15.1" }, "devDependencies": { diff --git a/ui-ngx/src/app/core/auth/auth.service.spec.ts b/ui-ngx/src/app/core/auth/auth.service.spec.ts deleted file mode 100644 index cd58133fe4..0000000000 --- a/ui-ngx/src/app/core/auth/auth.service.spec.ts +++ /dev/null @@ -1,14 +0,0 @@ -// SPDX-FileCopyrightText: Copyright The Thingsboard Authors -// SPDX-License-Identifier: Apache-2.0 -import { TestBed } from '@angular/core/testing'; - -import { AuthService } from './auth.service'; - -describe('AuthService', () => { - beforeEach(() => TestBed.configureTestingModule({})); - - it('should be created', () => { - const service: AuthService = TestBed.get(AuthService); - expect(service).toBeTruthy(); - }); -}); diff --git a/ui-ngx/src/app/core/http/community-grant.service.ts b/ui-ngx/src/app/core/http/community-grant.service.ts new file mode 100644 index 0000000000..c842cfc7e4 --- /dev/null +++ b/ui-ngx/src/app/core/http/community-grant.service.ts @@ -0,0 +1,63 @@ +// SPDX-FileCopyrightText: Copyright The Thingsboard Authors +// SPDX-License-Identifier: Apache-2.0 +import { Injectable } from '@angular/core'; +import { HttpClient } from '@angular/common/http'; +import { Observable } from 'rxjs'; +import { map } from 'rxjs/operators'; +import { defaultHttpOptionsFromConfig, defaultHttpUploadOptions, RequestConfig } from './http-utils'; +import { + CommunityGrantRegistration, + communityGrantRegistrationFrom, + CommunityGrantStateInfo +} from '@shared/models/ce-grant/community-grant.models'; + +@Injectable({ + providedIn: 'root' +}) +export class CommunityGrantService { + + constructor(private http: HttpClient) { + } + + /** + * Mints a fresh claim token and sign-up URL. An unreachable portal is not an error: it answers with + * `mode = OFFLINE`. + */ + public register(config?: RequestConfig): Observable { + return this.http.post('/api/communityGrant/start', null, defaultHttpOptionsFromConfig(config)) + .pipe(map(info => communityGrantRegistrationFrom(info))); + } + + public pollRegistration(config?: RequestConfig): Observable { + return this.http.get('/api/communityGrant/state', defaultHttpOptionsFromConfig(config)) + .pipe(map(info => communityGrantRegistrationFrom(info))); + } + + /** + * Answers once the run has started; its report or failure arrives on a later `GET /state`. Errors are not + * toasted: the dialog shows them itself. + */ + public runOfflineScaleCheck(bundle: File): Observable { + const formData = new FormData(); + formData.append('bundle', bundle); + return this.http.post('/api/communityGrant/offline/run', formData, + defaultHttpUploadOptions(false, true)) + .pipe(map(info => communityGrantRegistrationFrom(info))); + } + + public downloadOfflineReport(config?: RequestConfig): Observable { + return this.http.get('/api/communityGrant/offline/report', + {...{responseType: 'text' as const}, ...defaultHttpOptionsFromConfig(config)}); + } + + public confirmOfflineHandoff(config?: RequestConfig): Observable { + return this.http.post('/api/communityGrant/offline/handoff', null, + defaultHttpOptionsFromConfig(config)) + .pipe(map(info => communityGrantRegistrationFrom(info))); + } + + /** Success means only that the request reached the portal, never that the registered owner was notified. */ + public requestAccess(config?: RequestConfig): Observable { + return this.http.post('/api/communityGrant/requestAccess', null, defaultHttpOptionsFromConfig(config)); + } +} diff --git a/ui-ngx/src/app/core/interceptors/global-http-interceptor.ts b/ui-ngx/src/app/core/interceptors/global-http-interceptor.ts index bf38fbeb01..ab7c446271 100644 --- a/ui-ngx/src/app/core/interceptors/global-http-interceptor.ts +++ b/ui-ngx/src/app/core/interceptors/global-http-interceptor.ts @@ -108,7 +108,9 @@ export class GlobalHttpInterceptor implements HttpInterceptor { this.dialogService.forbidden(); } } else if (errorResponse.status === 0 || errorResponse.status === -1) { + if (!ignoreErrors) { this.showError('Unable to connect'); + } } else if (!(req.url.startsWith('/api/rpc') || req.url.startsWith('/api/plugins/rpc'))) { if (errorResponse.status === 404) { if (!ignoreErrors) { diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/home-page/ce-grant-tokens.scss b/ui-ngx/src/app/modules/home/components/widget/lib/home-page/ce-grant-tokens.scss new file mode 100644 index 0000000000..3df82ec15e --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/widget/lib/home-page/ce-grant-tokens.scss @@ -0,0 +1,34 @@ +// SPDX-FileCopyrightText: Copyright The Thingsboard Authors +// SPDX-License-Identifier: Apache-2.0 +/* `:host` serves the encapsulated widget; `.tb-ce-grant-dialog-panel` the un-encapsulated dialog's overlay. */ +@mixin tb-ce-grant-tokens { + --tb-brand: #17685a; + --tb-brand-tint: #e2f1ec; + --tb-brand-ink: #0e5a4e; + + --tb-ink: rgba(0, 0, 0, 0.87); + --tb-ink-2: rgba(0, 0, 0, 0.6); + --tb-ink-3: rgba(0, 0, 0, 0.38); + --tb-line: rgba(0, 0, 0, 0.12); + + --tb-warn: #f44336; + + --tb-caution: #b26500; + --tb-caution-tint: rgb(255 167 38 / 0.14); + + --tb-radius-card: 8px; + + --tb-font-mono: "Roboto Mono", ui-monospace, monospace; + + --tb-detail-bg: #f6f8f9; + --tb-note-bg: rgba(0, 0, 0, 0.03); + --tb-code-bg: rgba(0, 0, 0, 0.03); +} + +:host { + @include tb-ce-grant-tokens; +} + +.tb-ce-grant-dialog-panel { + @include tb-ce-grant-tokens; +} diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/home-page/community-grant-dialog.component.html b/ui-ngx/src/app/modules/home/components/widget/lib/home-page/community-grant-dialog.component.html new file mode 100644 index 0000000000..343656a496 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/widget/lib/home-page/community-grant-dialog.component.html @@ -0,0 +1,555 @@ + + +

    + {{ value }} +
    + + + + +
    + security +

    {{ textKey | translate }}

    +
    +
    + + +
    + {{ 'ce-grant.safe-to-close' | translate }} + +
    +
    + + +
    + @if (reportPending) { +
    + +
    + } @else if (reportLoadError) { +

    {{ reportLoadError }}

    + } @else { +

    {{ 'ce-grant.result-lede' | translate }}

    + + } +
    +
    + @if (reportLoadError) { + + + } @else { + {{ 'ce-grant.result-safe-to-close' | translate }} + + @if (showHandedOver) { + + } + } +
    +
    + +
    + + +

    {{ 'ce-grant.title' | translate }}

    + + +
    + @if (isLoading$ | async) { + + } + + @if (!config.hero) { + @if (config.rail) { + + } + + @if (config.topBanner) { +
    + @switch (config.topBanner) { + @case ('offlineBanner') { +
    + cloud_off +

    {{ 'ce-grant.offline-caution' | translate }}

    + +
    + @if (registerErrorMessage) { +

    {{ registerErrorMessage }}

    + } + } + } +
    + } + +
    + @if (config.spinner) { + + } @else { +
    + {{ config.icon }} +
    + } +

    {{ title | translate }}

    +
    + } + + @if (!stateKnown) { +
    + @if (initialLoadFailed) { +

    {{ 'ce-grant.load-error-lede' | translate }}

    + } @else { + + } +
    +
    + + @if (initialLoadFailed) { + + } +
    + } @else { + @switch (state) { + + @case (communityGrantState.intro) { +
    + +
    +
    + +
    +
    +
    +

    {{ 'ce-grant.intro-heading' | translate }}

    +
    +

    {{ 'ce-grant.intro-lede' | translate }}

    +

    + + {{ 'ce-grant.intro-read-announcement' | translate }} + mdi:arrow-top-right + +

    + @if (registerErrorMessage) { +

    {{ registerErrorMessage }}

    + } +
    +
    + +
    +

    {{ 'ce-grant.intro-included-title' | translate }}

    +
      +
    • + check + + {{ 'ce-grant.intro-included-devices-and-servers-lead' | translate }} + {{ 'ce-grant.intro-included-devices-and-servers-text' | translate }} + +
    • +
    • + check + + {{ 'ce-grant.intro-included-permanent-lead' | translate }} + {{ 'ce-grant.intro-included-permanent-text' | translate }} + +
    • +
    • + check + + {{ 'ce-grant.intro-included-security-lead' | translate }} + {{ 'ce-grant.intro-included-security-text' | translate }} + +
    • +
    • + check + + {{ 'ce-grant.intro-included-register-lead' | translate }} + {{ 'ce-grant.intro-included-register-text' | translate }} + +
    • +
    + +

    {{ 'ce-grant.intro-assurance' | translate }}

    +
    + +
    + + +
    +
    + } + + @case (communityGrantState.awaiting) { +
    +

    {{ 'ce-grant.awaiting-lede' | translate }}

    +
    +

    + {{ 'ce-grant.need-link' | translate }} +

    +

    + {{ (stalled ? 'ce-grant.stall-note': 'ce-grant.link-use-note') | translate }} +

    + +

    + + {{ 'ce-grant.link-share-caution' | translate }} +

    +
    +
    + + } + + @case (communityGrantState.verifying) { +
    +

    {{ 'ce-grant.verifying-lede' | translate }}

    + + @if (stalled) { +
    +

    + {{ 'ce-grant.no-report-yet' | translate }} +

    +

    + {{ 'ce-grant.verifying-stall-note' | translate }} +

    + +
    + } +
    + + } + + @case (communityGrantState.registered) { +
    +
    + + + + + {{ 'ce-grant.ce-grant' | translate }} + {{ 'ce-grant.ce-grant-note' | translate }} + +
    +

    {{ 'ce-grant.registered-lede' | translate }}

    +
    +
    + + + {{ 'ce-grant.card-registered-link' | translate }} + mdi:arrow-top-right + +
    + } + + @case (communityGrantState.review) { +
    +

    {{ 'ce-grant.review-lede' | translate }}

    +
    +
    + +
    + } + + @case (communityGrantState.offline) { +
    +

    {{ 'ce-grant.offline-lede' | translate }}

    + +

    + + {{ 'ce-grant.link-share-caution' | translate }} +

    +
    +
    + + +
    + } + + @case (communityGrantState.verify) { +
    +

    {{ 'ce-grant.verify-lede' | translate }}

    +

    {{ 'ce-grant.verify-upload-tool' | translate }}

    +
    + + + @if (bundleFile) { + + insert_drive_file + {{ bundleFile.name }} + + + } +
    + @if (!noBundleSelected && !bundleError) { +

    {{ 'ce-grant.verify-upload-hint' | translate }}

    + } + @if (noBundleSelected) { +

    {{ 'ce-grant.verify-error-no-file' | translate }}

    + } + @if (bundleError === communityGrantBundleErrorCode.NOT_A_BUNDLE) { +

    {{ 'ce-grant.verify-error-not-a-bundle' | translate }}

    + } + @if (bundleError === communityGrantBundleErrorCode.MALFORMED) { +

    {{ 'ce-grant.verify-error-malformed' | translate }}

    + } + @if (bundleExpiredAt) { +
    + warning +

    {{ 'ce-grant.bundle-expired-warning' | translate: {date: bundleExpiredAt | date: 'medium'} }}

    +
    + } + + @if (checkFailed) { + @if (checkFailedMessage) { + +

    {{ checkFailedMessage }}

    + } @else { +

    + } + } +
    +
    + + @if (bundleFile || runCheckPending) { + + } @else { + + } +
    + } + + @case (communityGrantState.result) { + + } + @case (communityGrantState.handedOver) { + + } + @case (communityGrantState.expired) { +
    + @if (checkFailedPark) { +

    {{ 'ce-grant.check-failed-lede' | translate }}

    +

    + } @else if (portalUnreachablePark) { +

    {{ 'ce-grant.portal-unreachable-lede' | translate }}

    +

    {{ 'ce-grant.portal-unreachable-text' | translate }}

    + } @else { +

    {{ 'ce-grant.expired-lede' | translate }}

    +

    {{ 'ce-grant.expired-text' | translate }}

    + } + @if (registerErrorMessage) { +

    {{ registerErrorMessage }}

    + } +
    +
    + + +
    + } + + @case (communityGrantState.already) { +
    +

    {{ 'ce-grant.already-lede-no-mask' | translate }}

    +

    +

    {{ 'ce-grant.already-someone-else-registered' | translate }}

    + @if (accessRequested) { +

    {{ 'ce-grant.already-request-sent' | translate }}

    + } + @if (requestAccessErrorMessage) { +

    {{ requestAccessErrorMessage }}

    + } +
    +
    + + +
    + } + + @case (communityGrantState.wrongInstallation) { +
    +

    {{ 'ce-grant.wrong-installation-lede' | translate }}

    +

    +
    +
    + +
    + } + } + } +
    diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/home-page/community-grant-dialog.component.scss b/ui-ngx/src/app/modules/home/components/widget/lib/home-page/community-grant-dialog.component.scss new file mode 100644 index 0000000000..fbf6cf5d75 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/widget/lib/home-page/community-grant-dialog.component.scss @@ -0,0 +1,709 @@ +// SPDX-FileCopyrightText: Copyright The Thingsboard Authors +// SPDX-License-Identifier: Apache-2.0 + +/* ViewEncapsulation.None: every rule stays nested under .tb-ce-grant-dialog-panel or .tb-ce-grant-dialog. */ +@import "constants"; +@import "mixins"; + +.tb-ce-grant-dialog-panel { + width: min(600px, 100%); + + .mdc-dialog__surface { + border-radius: var(--tb-radius-card); + } + + &.tb-ce-grant-dialog-panel-wide { + width: min(860px, 100%); + + /* The intro's actions live inside the grid, so the whole sheet scrolls rather than its content. */ + .mdc-dialog__surface { + overflow-y: auto; + } + + .mat-mdc-dialog-content { + max-height: none; + } + } + + @media screen and (max-width: 900px) { + &.tb-ce-grant-dialog-panel-wide { + width: min(600px, 100%); + } + } + + @media #{$mat-lt-sm} { + .mdc-dialog__surface { + border-radius: 0; + } + } +} + +.tb-dialog .mat-mdc-dialog-container .tb-ce-grant-dialog { + display: flex; + flex-direction: column; + + --mat-progress-spinner-active-indicator-color: var(--tb-brand); + + mat-toolbar.mat-toolbar { + --mat-toolbar-container-background-color: var(--tb-brand); + --mat-toolbar-container-text-color: #fff; + --mat-toolbar-standard-height: 52px; + --mat-toolbar-mobile-height: 52px; + + flex: none; + /* Keeps the only close control in reach while the intro's sheet scrolls. */ + position: sticky; + top: 0; + z-index: 2; + gap: 12px; + padding: 0 8px 0 20px; + + /* mat-dialog-title here only labels the dialog; drop its dialog layout */ + h2.mat-mdc-dialog-title { + display: block; + padding: 0; + margin: 0; + font-size: 16px; + font-weight: 500; + line-height: normal; + letter-spacing: 0.005em; + color: inherit; + + &::before { + display: none; + } + } + } + + .tb-ce-grant-banner-container { + margin: 16px 24px 0; + } + + .tb-ce-grant-condition { + display: flex; + align-items: center; + gap: 10px; + padding: 5px 6px 5px 14px; + border-radius: 8px; + background: var(--tb-caution-tint); + .mat-icon { + @include tb-mat-icon-size(20); + flex: none; + color: var(--tb-caution); + } + svg { + flex: none; + color: var(--tb-caution); + } + p { + flex: 1; + min-width: 0; + margin: 0; + font-size: 13px; + line-height: 1.5; + color: var(--tb-ink); + } + } + + .tb-ce-grant-status { + flex: none; + padding: 24px 24px 0; + + h2 { + margin: 0; + font-size: 20px; + font-weight: 500; + line-height: 1.3; + letter-spacing: 0.005em; + color: var(--tb-ink); + } + } + + .tb-ce-grant-mark { + position: relative; + display: flex; + align-items: center; + justify-content: center; + width: 44px; + height: 44px; + margin: 0 0 14px; + border-radius: 50%; + background: var(--tb-brand); + color: #fff; + + &.tb-ce-grant-mark-live { + &::after { + content: ''; + position: absolute; + inset: 0; + border-radius: 50%; + animation: tb-ce-grant-mark-listen 2.4s cubic-bezier(0.25, 0, 0.35, 1) infinite; + } + @keyframes tb-ce-grant-mark-listen { + 0% { box-shadow: 0 0 0 0 rgb(23 104 90 / 0.30); } + 70% { box-shadow: 0 0 0 13px rgb(23 104 90 / 0); } + 100% { box-shadow: 0 0 0 0 rgb(23 104 90 / 0); } + } + } + + &.tb-ce-grant-mark-info { + background: rgba(0, 0, 0, 0.55); + color: #fff; + } + + .mat-icon { + @include tb-mat-icon-size(22); + + color: inherit; + } + } + + /* Display-only: no navigation, no content pane. */ + mat-stepper.tb-ce-grant-rail { + --mat-stepper-container-color: transparent; + --mat-stepper-header-height: auto; + --mat-stepper-line-color: var(--tb-line); + --mat-stepper-header-icon-background-color: transparent; + --mat-stepper-header-icon-foreground-color: #fff; + --mat-stepper-header-selected-state-icon-background-color: transparent; + --mat-stepper-header-selected-state-icon-foreground-color: #fff; + --mat-stepper-header-done-state-icon-background-color: var(--tb-brand); + --mat-stepper-header-done-state-icon-foreground-color: #fff; + --mat-stepper-header-label-text-size: 13px; + --mat-stepper-header-label-text-color: var(--tb-ink-3); + --mat-stepper-header-selected-state-label-text-size: 13px; + --mat-stepper-header-selected-state-label-text-color: var(--tb-ink-3); + --mat-stepper-header-selected-state-label-text-weight: 500; + --mat-stepper-header-hover-state-layer-color: transparent; + --mat-stepper-header-focus-state-layer-color: transparent; + + flex: none; + padding: 17px 24px; + border-bottom: 1px solid var(--tb-line); + pointer-events: none; + + .mat-horizontal-stepper-header-container { + align-items: center; + .mat-stepper-horizontal-line { + min-width: 16px; + margin: 0 10px; + border-top-width: 2px; + border-top-color: var(--tb-brand); + } + .mat-horizontal-stepper-header[aria-selected="true"] ~ .mat-stepper-horizontal-line { + border-top-color: var(--tb-line); + } + .mat-step-label { + line-height: 1.55; + &.mat-step-label-selected { + color: var(--tb-ink); + } + .tb-ce-grant-rail-completed { + color: var(--tb-ink-2); + } + } + } + + .mat-horizontal-content-container { + display: none; + } + + .mat-horizontal-stepper-header { + padding: 0; + overflow: visible; + } + + .mat-step-icon { + width: 20px; + height: 20px; + margin: 0 7px 0 0; + + .mat-icon { + font-weight: 600; + @include tb-mat-icon-size(14); + } + } + + .mat-step-icon-state-done { + border: 2px solid var(--tb-brand); + } + + .mat-step-icon-state-number { + border: 2px solid var(--tb-ink-3); + + &.mat-step-icon-selected { + border-color: var(--tb-brand); + + .tb-ce-grant-rail-dot { + background: var(--tb-brand); + } + } + } + + .mat-step-icon-state-edit { + background: none; + } + + .tb-ce-grant-rail-dot { + width: 8px; + height: 8px; + border-radius: 50%; + background: transparent; + } + + .tb-ce-grant-rail-active { + flex: none; + width: 20px; + height: 20px; + border-radius: 50%; + border: 2px solid var(--tb-brand); + display: flex; + align-items: center; + justify-content: center; + color: #fff; + .tb-ce-grant-rail-dot { + background: var(--tb-brand); + } + } + } + + .mat-mdc-dialog-content { + padding: 18px 24px 4px; + color: var(--tb-ink-2); + + > p { + margin: 0 0 14px; + font-size: 14px; + line-height: 1.6; + color: var(--tb-ink-2); + } + + > p.tb-ce-grant-body-lede { + font-size: 15px; + color: var(--tb-ink); + } + .tb-ce-grant-section { + margin-top: 24px; + padding-top: 16px; + border-top: 1px solid var(--tb-line); + overflow: hidden; + .tb-ce-grant-section-header { + margin: 0 0 6px; + font-size: 14px; + font-weight: 500; + color: var(--tb-ink); + } + .tb-ce-grant-section-note { + margin: 0 0 12px; + font-size: 13px; + line-height: 1.55; + color: var(--tb-ink-2); + } + } + } + + .mat-mdc-dialog-actions { + flex-wrap: wrap; + gap: 8px; + min-height: 0; + padding: 26px 24px 20px; + + > :not(:first-child) { + margin-left: 0; + } + } + + .tb-ce-grant-safe { + margin-right: auto; + font-size: 12.5px; + color: var(--tb-ink-3); + } + + .mat-mdc-unelevated-button.mat-primary { + --mat-button-filled-container-color: var(--tb-brand); + --mat-button-filled-label-text-color: #fff; + --mat-button-filled-icon-color: #fff; + } + + .mat-mdc-outlined-button.mat-primary:not(:disabled) { + --mat-button-outlined-label-text-color: var(--tb-brand-ink); + --mat-button-outlined-icon-color: var(--tb-brand-ink); + border-color: var(--tb-line); + } + + .mat-mdc-button:not(.mat-primary):not(.mat-accent):not(.mat-warn) { + --mat-button-text-label-text-color: var(--tb-ink-2); + } + + .mat-mdc-button.mat-primary { + --mat-button-text-label-text-color: var(--tb-brand-ink); + --mat-button-text-icon-color: var(--tb-brand-ink); + --mat-button-text-state-layer-color: var(--tb-brand); + } + + .mat-mdc-dialog-content.tb-ce-grant-cols { + display: grid; + grid-template-columns: 1.02fr 1fr; + grid-template-rows: 1fr auto; + padding: 0; + } + + .tb-ce-grant-pitch-col { + grid-column: 1; + grid-row: 1 / span 2; + } + + .tb-ce-grant-detail-col { + grid-column: 2; + grid-row: 1; + padding: 40px 24px 4px; + background: var(--tb-detail-bg); + } + + .tb-ce-grant-cols .mat-mdc-dialog-actions { + grid-column: 2; + grid-row: 2; + padding: 26px 24px 26px; + background: var(--tb-detail-bg); + justify-content: end; + } + + .tb-ce-grant-hero { + display: flex; + align-items: center; + justify-content: center; + padding: 18px 14px 2px; + + img { + display: block; + width: 360px; + max-width: 100%; + height: auto; + } + } + + .tb-ce-grant-pad { + padding: 14px 22px 4px; + } + + .tb-ce-grant-pitch { + padding: 8px 0 14px; + text-align: left; + + h2 { + max-width: none; + margin: 0; + font-size: 26px; + font-weight: 500; + line-height: 1.25; + letter-spacing: -0.01em; + color: var(--tb-ink); + } + } + + .tb-ce-grant-lede { + letter-spacing: normal; + margin: 0 0 12px; + font-size: 14px; + line-height: 1.6; + color: var(--tb-ink-2); + } + + .tb-ce-grant-readmore { + margin: 0 0 20px; + font-size: 13px; + line-height: 1.55; + letter-spacing: normal; + + a { + display: inline-flex; + align-items: center; + gap: 0; + color: var(--tb-brand-ink); + text-decoration: none; + white-space: nowrap; + border-bottom: none; + + &:hover { + text-decoration: underline; + text-underline-offset: 3px; + } + + tb-icon { + @include tb-mat-icon-size(14); + + color: inherit; + } + } + } + + /* The global button-icon rule spaces the wrong side of a trailing icon. */ + .mat-mdc-button-base tb-icon[iconPositionEnd] { + @include tb-mat-icon-size(16); + + margin: 0 0 0 6px; + } + + .tb-ce-grant-label { + margin: 0 0 10px; + font-size: 15px; + font-weight: 500; + color: var(--tb-ink); + } + + .tb-ce-grant-list { + margin: 0; + padding: 0; + list-style: none; + + li { + display: flex; + gap: 10px; + padding: 6px 0; + font-size: 14px; + line-height: 1.55; + color: var(--tb-ink-2); + letter-spacing: normal; + } + + b { + font-weight: 500; + color: var(--tb-ink); + } + + .mat-icon { + @include tb-mat-icon-size(15); + transform: scale(1.5); + margin: 4px 0 0; + color: var(--tb-brand-ink); + } + } + + mat-divider { + margin: 20px 0 0; + border-top-color: var(--tb-line); + } + + .tb-ce-grant-assurance { + margin: 16px 0 0; + font-size: 12.5px; + line-height: 1.6; + letter-spacing: normal; + color: var(--tb-ink-2); + } + + .tb-ce-grant-code { + max-height: calc(4.5em + 24px); + overflow-y: auto; + overscroll-behavior: contain; + padding: 12px 14px; + border-radius: 6px; + background: var(--tb-code-bg); + + code { + display: block; + font-family: var(--tb-font-mono); + font-size: 13px; + line-height: 1.5; + color: var(--tb-ink); + word-break: break-all; + } + } + .tb-ce-grant-link-acts { + display: flex; + align-items: center; + justify-content: flex-end; + flex-wrap: wrap; + gap: 4px; + margin-top: 12px; + overflow: hidden; + } + + /* "Copied" is inert but not disabled, so it keeps its color */ + .mat-mdc-button, .mat-mdc-unelevated-button { + &.tb-ce-grant-copy { + flex: none; + min-width: 0; + --mat-button-text-with-icon-horizontal-padding: 24px; + --mat-button-filled-horizontal-padding: 24px; + + &.tb-ce-grant-copied { + pointer-events: none; + --mat-button-text-state-layer-color: transparent; + } + } + } + + .tb-ce-grant-infobar { + display: flex; + gap: 12px; + margin: 16px 0 4px; + padding: 13px 15px; + border-radius: 8px; + background: var(--tb-note-bg); + + .mat-icon { + @include tb-mat-icon-size(16); + + margin-top: 1px; + color: var(--tb-ink-3); + } + + p { + margin: 0; + font-size: 13px; + line-height: 1.6; + letter-spacing: normal; + color: var(--tb-ink-2); + } + } + + .tb-ce-grant-warnbar { + display: flex; + gap: 12px; + margin: 16px 0 4px; + padding: 13px 15px; + border-radius: 8px; + border: 1px solid color-mix(in srgb, var(--tb-warn) 40%, transparent); + background: color-mix(in srgb, var(--tb-warn) 8%, transparent); + + .mat-icon { + @include tb-mat-icon-size(16); + + margin-top: 1px; + color: var(--tb-warn); + } + + p { + margin: 0; + font-size: 13px; + line-height: 1.6; + color: var(--tb-ink); + } + } + + .tb-ce-grant-lic { + display: flex; + align-items: center; + gap: 12px; + margin: 0 0 16px; + padding: 12px 14px; + border: 1px solid var(--tb-line); + border-radius: 8px; + .tb-ce-grant-lic-mark { + flex: none; + width: 34px; + height: 34px; + display: flex; + align-items: center; + justify-content: center; + border-radius: 50%; + background: rgb(0 105 92 / 0.1); + color: rgb(0 105 92); + } + .tb-ce-grant-lic-text { + display: flex; + flex-direction: column; + gap: 1px; + min-width: 0; + b { + font-size: 15px; + font-weight: 500; + color: var(--tb-ink); + } + span { + font-size: 13px; + color: var(--tb-ink-2); + } + } + } + + .tb-ce-grant-caution { + display: flex; + gap: 8px; + align-items: flex-start; + svg { + flex: none; + margin-top: 3px; + color: var(--tb-caution); + } + } + + p.tb-ce-grant-hint { + text-wrap: pretty; + margin: 14px 0 0; + font-size: 14px; + line-height: 1.55; + color: var(--tb-ink-2); + max-width: 56ch; + } + + p.tb-ce-grant-error { + margin: 10px 0 0; + font-size: 12.5px; + line-height: 1.5; + color: var(--tb-warn); + + a { + color: inherit; + font-weight: 500; + text-decoration: underline; + text-underline-offset: 2px; + } + } + + p.tb-ce-grant-file-title { + margin: 20px 0 10px; + font-size: 16px; + font-weight: 500; + color: var(--tb-ink); + } + .tb-ce-grant-file { + display: flex; + flex-wrap: wrap; + align-items: center; + gap: 12px; + } + + .tb-ce-grant-file-name { + display: inline-flex; + align-items: center; + gap: 7px; + min-width: 0; + overflow-wrap: anywhere; + font-family: var(--tb-font-mono); + font-size: 12.5px; + color: var(--tb-ink-2); + .mat-icon { + flex: none; + color: var(--tb-ink-3); + } + } + + .tb-ce-grant-loading, + .tb-ce-grant-report-loading { + display: flex; + align-items: center; + justify-content: center; + padding: 40px 0; + } + + @media screen and (max-width: 900px) { + .mat-mdc-dialog-content.tb-ce-grant-cols { + display: block; + } + + .tb-ce-grant-pitch { + text-align: center; + + h2 { + max-width: 420px; + margin: 0 auto; + } + } + + .tb-ce-grant-detail-col { + padding-top: 24px; + } + } +} diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/home-page/community-grant-dialog.component.ts b/ui-ngx/src/app/modules/home/components/widget/lib/home-page/community-grant-dialog.component.ts new file mode 100644 index 0000000000..33a6f79d58 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/widget/lib/home-page/community-grant-dialog.component.ts @@ -0,0 +1,492 @@ +// SPDX-FileCopyrightText: Copyright The Thingsboard Authors +// SPDX-License-Identifier: Apache-2.0 +import { ChangeDetectorRef, Component, OnDestroy, OnInit, ViewEncapsulation } from '@angular/core'; +import { HttpErrorResponse } from '@angular/common/http'; +import { MatDialogRef } from '@angular/material/dialog'; +import { STEPPER_GLOBAL_OPTIONS } from '@angular/cdk/stepper'; +import { Router } from '@angular/router'; +import { Store } from '@ngrx/store'; +import { AppState } from '@core/core.state'; +import { DialogComponent } from '@shared/components/dialog.component'; +import { DialogService } from '@core/services/dialog.service'; +import { ClipboardService } from 'ngx-clipboard'; +import { TranslateService } from '@ngx-translate/core'; +import { Subscription, interval, timer } from 'rxjs'; +import { switchMap } from 'rxjs/operators'; +import { CommunityGrantService } from '@core/http/community-grant.service'; +import { RequestConfig } from '@core/http/http-utils'; +import { + CommunityGrantBackendMode, + CommunityGrantBackendState, + CommunityGrantBundleErrorCode, + CommunityGrantBundleParseError, + CommunityGrantParkReason, + CommunityGrantRegistration, + CommunityGrantState, + CommunityGrantStateConfig, + communityGrantOnlinePollableStates, + communityGrantPollInterval, + communityGrantPortalUrl, + communityGrantRailLabels, + communityGrantStallTimeout, + communityGrantStateConfigs, + communityGrantStateTitles, + peekCommunityGrantBundle, + resolveCommunityGrantErrorMessage +} from '@shared/models/ce-grant/community-grant.models'; + +// The calling button shows both the error and the wait, so no toast and no global loading bar. +const startRequestConfig: RequestConfig = {ignoreErrors: true, ignoreLoading: true}; + +@Component({ + selector: 'tb-community-grant-dialog', + templateUrl: './community-grant-dialog.component.html', + styleUrls: ['./ce-grant-tokens.scss', './community-grant-dialog.component.scss'], + encapsulation: ViewEncapsulation.None, + // Lets `[state]` pick the node icons instead of Material's default indicator logic. + providers: [{provide: STEPPER_GLOBAL_OPTIONS, useValue: {displayDefaultIndicatorType: false}}], + standalone: false +}) +export class CommunityGrantDialogComponent extends DialogComponent + implements OnInit, OnDestroy { + + communityGrantState = CommunityGrantState; + communityGrantBundleErrorCode = CommunityGrantBundleErrorCode; + + get portalUrl(): string { + return this.registration.portalUrl ?? communityGrantPortalUrl; + } + + /** `intro` is only the default, so no state screen renders until the first `GET /state` answers. */ + stateKnown = false; + + initialLoadFailed = false; + + state = CommunityGrantState.intro; + + registration: CommunityGrantRegistration = {state: CommunityGrantState.intro}; + + registerPending = false; + retryPending = false; + runCheckPending = false; + startAgainPending = false; + requestAccessPending = false; + + registerErrorMessage: string = null; + + stalled = false; + + accessRequested = false; + requestAccessErrorMessage: string = null; + + bundleFile: File = null; + noBundleSelected = false; + bundleError: CommunityGrantBundleErrorCode = null; + bundleExpiredAt: number = null; + checkFailed = false; + checkFailedMessage: string = null; + + copiedValue: string = null; + + reportPending = false; + reportLoadError: string = null; + + private verifyEntryState = CommunityGrantState.offline; + + private pollSubscription: Subscription; + private stallSubscription: Subscription; + private initialLoadSubscription: Subscription; + private handoffSubscription: Subscription; + private copiedTimer: Subscription; + + constructor(protected store: Store, + protected router: Router, + public dialogRef: MatDialogRef, + private communityGrantService: CommunityGrantService, + private dialogService: DialogService, + private clipboardService: ClipboardService, + private translate: TranslateService, + private cd: ChangeDetectorRef) { + super(store, router, dialogRef); + dialogRef.addPanelClass('tb-ce-grant-dialog-panel'); + this.updatePanelWidth(); + } + + ngOnInit(): void { + this.loadInitialState(); + } + + private loadInitialState(): void { + this.initialLoadFailed = false; + this.initialLoadSubscription?.unsubscribe(); + this.initialLoadSubscription = this.communityGrantService.pollRegistration().subscribe({ + next: (registration) => { + this.stateKnown = true; + this.applyRegistration(registration); + }, + error: () => { + this.initialLoadFailed = true; + this.cd.markForCheck(); + } + }); + } + + retryInitialLoad(): void { + this.loadInitialState(); + } + + ngOnDestroy(): void { + this.stopPolling(); + this.initialLoadSubscription?.unsubscribe(); + this.handoffSubscription?.unsubscribe(); + this.copiedTimer?.unsubscribe(); + super.ngOnDestroy(); + } + + get config(): CommunityGrantStateConfig { + return communityGrantStateConfigs.get(this.state); + } + + get checkFailedPark(): boolean { + return this.isPark(CommunityGrantParkReason.CHECK_FAILED); + } + + get portalUnreachablePark(): boolean { + return this.isPark(CommunityGrantParkReason.PORTAL_UNREACHABLE); + } + + private isPark(reason: CommunityGrantParkReason): boolean { + return this.state === CommunityGrantState.expired && this.registration.parkReason === reason; + } + + get title(): string { + if (this.checkFailedPark) { + return 'ce-grant.check-failed-title'; + } + if (this.portalUnreachablePark) { + return 'ce-grant.portal-unreachable-title'; + } + return communityGrantStateTitles.get(this.state); + } + + get railLabels(): string[] { + return communityGrantRailLabels.get(this.config.rail) ?? []; + } + + get railSelectedIndex(): number { + return Math.min(this.config.railStep, this.railLabels.length - 1); + } + + railStepState(index: number): string { + return index < this.config.railStep ? 'done' : 'number'; + } + + get registrationLink(): string { + return this.registration.registrationLink; + } + + isCopied(value: string): boolean { + return this.copiedValue === value; + } + + copy(value: string): void { + this.clipboardService.copy(value); + this.copiedValue = value; + this.copiedTimer?.unsubscribe(); + this.copiedTimer = timer(1600).subscribe(() => { + this.copiedValue = null; + this.cd.markForCheck(); + }); + } + + private openLink(url: string): void { + window.open(url, '_blank'); + } + + loadReport(): void { + this.reportPending = true; + this.reportLoadError = null; + this.communityGrantService.downloadOfflineReport({ignoreErrors: true}).subscribe({ + next: (report) => { + this.reportPending = false; + if (!report) { + this.reportLoadError = this.translate.instant('ce-grant.result-error-empty'); + this.cd.markForCheck(); + return; + } + this.registration = {...this.registration, report}; + this.cd.markForCheck(); + }, + error: (err: HttpErrorResponse) => { + this.reportPending = false; + this.reportLoadError = this.extractErrorMessage(err, 'text'); + this.cd.markForCheck(); + } + }); + } + + register(open = true): void { + this.registerPending = true; + this.registerErrorMessage = null; + this.communityGrantService.register(startRequestConfig).subscribe({ + next: (registration) => { + this.registerPending = false; + this.applyRegistration(registration); + if (open && this.registrationLink && this.state === CommunityGrantState.awaiting) { + this.openLink(this.registrationLink); + } + }, + error: (err: HttpErrorResponse) => { + this.registerPending = false; + this.registerErrorMessage = this.extractErrorMessage(err); + this.cd.markForCheck(); + } + }); + } + + /** Re-mints over the live link this screen shows, which stops working. */ + retry(): void { + this.retryPending = true; + this.registerErrorMessage = null; + this.communityGrantService.register(startRequestConfig).subscribe({ + next: (registration) => { + this.retryPending = false; + this.applyRegistration(registration); + }, + error: (err: HttpErrorResponse) => { + this.retryPending = false; + this.registerErrorMessage = this.extractErrorMessage(err); + this.cd.markForCheck(); + } + }); + } + + startAgain(): void { + this.startAgainPending = true; + this.registerErrorMessage = null; + this.communityGrantService.register(startRequestConfig).subscribe({ + next: (registration) => { + this.startAgainPending = false; + this.applyRegistration(registration); + }, + error: (err: HttpErrorResponse) => { + this.startAgainPending = false; + this.registerErrorMessage = this.extractErrorMessage(err); + this.cd.markForCheck(); + } + }); + } + + requestAccess(): void { + this.requestAccessPending = true; + this.requestAccessErrorMessage = null; + this.communityGrantService.requestAccess({ignoreErrors: true}).subscribe({ + next: () => { + this.requestAccessPending = false; + this.accessRequested = true; + this.cd.markForCheck(); + }, + error: (err: HttpErrorResponse) => { + this.requestAccessPending = false; + this.requestAccessErrorMessage = this.extractErrorMessage(err); + this.cd.markForCheck(); + } + }); + } + + continueToCheck(): void { + this.verifyEntryState = CommunityGrantState.offline; + this.goToState(CommunityGrantState.verify); + } + + runCheckByHand(): void { + this.verifyEntryState = CommunityGrantState.verifying; + this.goToState(CommunityGrantState.verify); + } + + backFromVerify(): void { + this.goToState(this.verifyEntryState); + } + + bundleFileSelected(event: Event): void { + const input = event.target as HTMLInputElement; + this.bundleFile = input.files?.length ? input.files[0] : null; + this.noBundleSelected = false; + this.bundleError = null; + this.bundleExpiredAt = null; + this.checkFailed = false; + this.checkFailedMessage = null; + const chosen = this.bundleFile; + if (!chosen) { + this.cd.markForCheck(); + return; + } + peekCommunityGrantBundle(chosen).then(preflight => { + if (this.bundleFile !== chosen) { + return; + } + this.bundleExpiredAt = preflight.challengeExpired ? preflight.manifest.challengeExpiresAt : null; + this.cd.markForCheck(); + }).catch((e: unknown) => { + if (this.bundleFile !== chosen) { + return; + } + this.bundleError = e instanceof CommunityGrantBundleParseError + ? e.code : CommunityGrantBundleErrorCode.MALFORMED; + this.cd.markForCheck(); + }); + this.cd.markForCheck(); + } + + clearBundleFile(bundleInput: HTMLInputElement): void { + bundleInput.value = ''; + this.bundleFile = null; + this.noBundleSelected = false; + this.bundleError = null; + this.bundleExpiredAt = null; + this.checkFailed = false; + this.checkFailedMessage = null; + this.cd.markForCheck(); + } + + runCheck(): void { + this.noBundleSelected = !this.bundleFile; + this.checkFailed = false; + this.checkFailedMessage = null; + if (this.noBundleSelected || this.bundleError) { + this.cd.markForCheck(); + return; + } + this.runCheckPending = true; + this.communityGrantService.runOfflineScaleCheck(this.bundleFile).subscribe({ + next: (registration) => this.applyRegistration(registration), + error: (err: HttpErrorResponse) => { + this.runCheckPending = false; + this.checkFailed = true; + this.checkFailedMessage = this.extractErrorMessage(err); + this.cd.markForCheck(); + } + }); + } + + private extractErrorMessage(error: HttpErrorResponse, responseType?: string): string { + return resolveCommunityGrantErrorMessage(error, this.translate, responseType); + } + + /** A refusal usually means the poller moved the state on first, so the state is re-read instead. */ + confirmHandoff(): void { + this.handoffSubscription?.unsubscribe(); + this.handoffSubscription = this.communityGrantService.confirmOfflineHandoff({ignoreErrors: true}).subscribe({ + next: () => this.close(), + error: () => { + this.handoffSubscription = this.communityGrantService.pollRegistration({ignoreErrors: true}) + .subscribe(registration => this.applyRegistration(registration)); + } + }); + } + + close(): void { + this.dialogRef.close(); + } + + /** A by-hand run in progress holds the `verify` screen, whatever state the flow is in. */ + private applyRegistration(registration: CommunityGrantRegistration): void { + const awaitedRun = this.runCheckPending; + this.registration = registration; + this.runCheckPending = !!registration.offlineRunInProgress; + const failed = awaitedRun && !this.runCheckPending && !!registration.offlineRunError; + if (!this.runCheckPending && !failed) { + this.goToState(registration.state); + return; + } + this.showVerify(); + if (failed) { + this.checkFailed = true; + this.checkFailedMessage = registration.offlineRunError; + } + this.cd.markForCheck(); + } + + /** Stays on `verify` without {@link goToState}, which would clear the bundle's pre-flight warning. */ + private showVerify(): void { + if (this.state !== CommunityGrantState.verify) { + this.verifyEntryState = this.registration.state; + this.goToState(CommunityGrantState.verify); + return; + } + if (this.runCheckPending && !this.pollSubscription) { + this.startPolling(); + } else if (!this.runCheckPending) { + this.stopPolling(); + } + } + + private goToState(state: CommunityGrantState): void { + // `VALIDATING` + `ONLINE` with a report is a by-hand run's result, not the automatic wait. + if (state === CommunityGrantState.verifying && this.registration.report + && this.registration.backendState === CommunityGrantBackendState.VALIDATING + && this.registration.mode === CommunityGrantBackendMode.ONLINE) { + state = CommunityGrantState.result; + } + this.state = state; + this.stalled = false; + this.registerErrorMessage = null; + this.noBundleSelected = false; + this.bundleError = null; + this.bundleExpiredAt = null; + this.checkFailed = false; + this.checkFailedMessage = null; + this.reportPending = false; + this.reportLoadError = null; + this.requestAccessErrorMessage = null; + this.stopPolling(); + if (communityGrantOnlinePollableStates.has(state) || this.runCheckPending) { + this.startPolling(); + } + if ((state === CommunityGrantState.result || state === CommunityGrantState.handedOver) + && !this.registration.report) { + // The state omits the report when the server could not read it, so it is fetched on its own. + this.loadReport(); + } + this.updatePanelWidth(); + this.cd.markForCheck(); + } + + private updatePanelWidth(): void { + if (this.stateKnown && this.config.hero) { + this.dialogRef.addPanelClass('tb-ce-grant-dialog-panel-wide'); + } else { + this.dialogRef.removePanelClass('tb-ce-grant-dialog-panel-wide'); + } + } + + /** Compares more than the UI state: the mapping is many-to-one, and a re-mint changes only the link. */ + private startPolling(): void { + this.pollSubscription = interval(communityGrantPollInterval).pipe( + switchMap(() => this.communityGrantService.pollRegistration({ignoreLoading: true, ignoreErrors: true})) + ).subscribe((registration) => { + // A run in progress holds `verify`, so a differing mapped state alone is not a change. + const holdsVerify = this.runCheckPending && registration.offlineRunInProgress; + if ((!holdsVerify && registration.state !== this.state) + || registration.backendState !== this.registration.backendState + || registration.mode !== this.registration.mode + || registration.report !== this.registration.report + || registration.registrationLink !== this.registration.registrationLink + || registration.offlineRunInProgress !== this.registration.offlineRunInProgress + || registration.offlineRunError !== this.registration.offlineRunError) { + this.applyRegistration(registration); + } + }); + this.stallSubscription = timer(communityGrantStallTimeout).subscribe(() => { + this.stalled = true; + this.cd.markForCheck(); + }); + } + + private stopPolling(): void { + this.pollSubscription?.unsubscribe(); + this.pollSubscription = null; + this.stallSubscription?.unsubscribe(); + this.stallSubscription = null; + } +} diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/home-page/home-page-widgets.module.ts b/ui-ngx/src/app/modules/home/components/widget/lib/home-page/home-page-widgets.module.ts index fa07dcc4e2..f3dcf6b1ad 100644 --- a/ui-ngx/src/app/modules/home/components/widget/lib/home-page/home-page-widgets.module.ts +++ b/ui-ngx/src/app/modules/home/components/widget/lib/home-page/home-page-widgets.module.ts @@ -23,6 +23,9 @@ import { } from '@home/components/widget/lib/home-page/recent-dashboards-widget.component'; import { IotHubWidgetComponent } from '@home/components/widget/lib/home-page/iot-hub-widget.component'; import { IotHubComponentsModule } from '@home/components/iot-hub/iot-hub-components.module'; +import { + CommunityGrantDialogComponent +} from '@home/components/widget/lib/home-page/community-grant-dialog.component'; @NgModule({ declarations: @@ -41,7 +44,8 @@ import { IotHubComponentsModule } from '@home/components/iot-hub/iot-hub-compone QuickLinkComponent, AddQuickLinkDialogComponent, RecentDashboardsWidgetComponent, - IotHubWidgetComponent + IotHubWidgetComponent, + CommunityGrantDialogComponent ], imports: [ CommonModule, @@ -63,7 +67,8 @@ import { IotHubComponentsModule } from '@home/components/iot-hub/iot-hub-compone QuickLinkComponent, AddQuickLinkDialogComponent, RecentDashboardsWidgetComponent, - IotHubWidgetComponent + IotHubWidgetComponent, + CommunityGrantDialogComponent ] }) export class HomePageWidgetsModule { } diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/home-page/version-info.component.html b/ui-ngx/src/app/modules/home/components/widget/lib/home-page/version-info.component.html index 7b0807a587..f332a8e86f 100644 --- a/ui-ngx/src/app/modules/home/components/widget/lib/home-page/version-info.component.html +++ b/ui-ngx/src/app/modules/home/components/widget/lib/home-page/version-info.component.html @@ -4,49 +4,107 @@ SPDX-License-Identifier: Apache-2.0 --> -
    +
    -
    -
    -
    - -
    {{ updateMessage?.currentVersion }}
    -
    + + @switch (cardState()) { + + @case (communityGrantCardState.progress) { +
    +
    +

    + {{ grantCard().title | translate }} +

    +

    {{ grantCard().text | translate }}

    + @if (grantCard().waiting) { + + } @else { + + }
    -
    -
    -
    -
    - - widgets.version-info.available-version - widgets.version-info.available - + } + + @case (communityGrantCardState.status) { +
    +
    +

    + {{ grantCard().title | translate }} +

    +

    {{ grantCard().text | translate }}

    + @if (grantCardHasLinks()) { + + }
    -
    {{ updateMessage?.latestVersion }}
    -
    - {{ 'widgets.version-info.upgrade' | translate }} + @if (grantCard().action) { + + } +
    + } + + @case (communityGrantCardState.offer) { +
    +
    +

    {{'widgets.version-info.thingsboard-version-available' | translate: {version: offerVersion()} }}

    +

    {{ 'widgets.version-info.free-community-grant-text' | translate }}

    + @if (showExpiredNote()) { +

    {{ 'ce-grant.card-expired-note' | translate }}

    + } + @if (showCheckFailedNote()) { +

    {{ 'ce-grant.card-check-failed-note' | translate }}

    + } + @if (showPortalUnreachableNote()) { +

    {{ 'ce-grant.card-portal-unreachable-note' | translate }}

    + }
    + +

    {{ 'widgets.version-info.community-grant-registration-close' | translate }}

    -
    - {{ 'widgets.version-info.upgrade' | translate }} + } + + @case (communityGrantCardState.upToDate) { +
    +
    + +
    widgets.version-info.version-is-up-to-date
    +
    -
    -
    + } + + @default {} + }
    - -
    -
    check
    -
    widgets.version-info.version-is-up-to-date
    -
    -
    diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/home-page/version-info.component.scss b/ui-ngx/src/app/modules/home/components/widget/lib/home-page/version-info.component.scss index f6e77b092e..b64a74c258 100644 --- a/ui-ngx/src/app/modules/home/components/widget/lib/home-page/version-info.component.scss +++ b/ui-ngx/src/app/modules/home/components/widget/lib/home-page/version-info.component.scss @@ -3,61 +3,80 @@ @import "../../../../../../../scss/constants"; :host { + + .tb-card-content { + display: flex; + flex-direction: column; + gap: 14px; + @media #{$mat-md-lg} { + gap: 4px; + } + } .tb-card-header { display: flex; flex-direction: row; justify-content: space-between; align-items: center; - margin-bottom: 8px; @media #{$mat-md-lg} { margin-bottom: 4px; } + .tb-title { + font-size: 16px; + font-weight: 500; + color: rgba(0, 0, 0, 0.87); + @media #{$mat-md-lg} { + font-size: 12px; + } + } } - .tb-contact-us { + a.tb-contact-us { + font-size: 13.5px; + border-bottom-color: transparent; + &:hover, &:focus { + border-bottom-color: #4054b2; + } @media #{$mat-md-lg} { - height: 24px; font-size: 12px; } } .tb-version-info-container { - border: 1px solid rgba(0, 0, 0, 0.05); - box-shadow: 0 5px 16px rgba(0, 0, 0, 0.04); - border-radius: 10px; - padding: 8px 16px 4px 16px; - overflow: hidden; + display: flex; + gap: 8px; + align-items: center; + border: 1px solid rgba(0, 0, 0, 0.12); + border-radius: 8px; + padding: 12px 14px; white-space: nowrap; - @media #{$mat-lt-md} { - padding: 16px; - } @media #{$mat-md-lg} { padding: 4px; } &.up-to-date { box-shadow: none; border: none; - background: #F3F6FA; white-space: initial; text-align: center; } } .tb-version-link { + display: flex; + align-items: center; + gap: 8px; font-weight: 400; font-size: 14px; - line-height: 20px; - letter-spacing: 0.2px; - color: rgba(0, 0, 0, 0.76); + line-height: 1.55; + letter-spacing: normal; + color: rgba(0, 0, 0, 0.6); position: relative; border-bottom: none; - @media #{$mat-md-lg} { - font-size: 11px; - line-height: 16px; - } &:hover, &:focus { border-bottom: none; } + b { + color: rgba(0, 0, 0, 0.87); + } &::after { content: 'arrow_forward'; display: inline-block; @@ -68,36 +87,149 @@ font-size: 18px; color: rgba(0, 0, 0, 0.12); vertical-align: bottom; - margin-left: 6px; + margin-left: -4px; } &:hover::after { color: inherit; } } - .tb-version { + /* Shared geometry, so the widget keeps its height as the registration moves. */ + .tb-update-available-container, + .tb-grant-card { + display: flex; + flex-direction: column; + gap: 14px; + padding: 16px 18px; + border-radius: 8px; + background: var(--tb-brand-tint); + @media #{$mat-md-lg} { + gap: 4px; + padding: 8px 10px; + } + } + + .tb-update-available-container p, + .tb-grant-card-text { + letter-spacing: normal; + line-height: 1.55; + color: var(--tb-ink-2); + } + + .tb-update-available-container { + h3 { + letter-spacing: normal; + margin: 0 0 6px; + font-size: 15px; + font-weight: 500; + } + p { + margin: 0; + font-size: 13.5px; + } + .tb-grant-expired-note { + margin-top: 8px; + font-size: 12.5px; + @media #{$mat-md-lg} { + font-size: 11px; + } + } + } + + .tb-grant-card.held { + background: var(--tb-note-bg); + + .tb-grant-card-title, .tb-grant-card-icon { + color: var(--tb-ink-2); + } + } + + .tb-grant-card.done { + .tb-grant-card-title { + color: var(--tb-ink-2); + } + } + + .tb-grant-card-title { + display: flex; + align-items: center; + gap: 9px; + margin: 0; + letter-spacing: normal; + font-size: 14px; font-weight: 500; - font-size: 18px; - line-height: 24px; - letter-spacing: 0.15px; - color: rgba(0, 0, 0, 0.87); + color: var(--tb-ink); @media #{$mat-md-lg} { font-size: 12px; - line-height: 14px; } } - .tb-upgrade { + .tb-grant-card-icon { + flex: none; + font-size: 16px; + color: var(--tb-brand-ink); + } + + .tb-grant-live-dot { + flex: none; + width: 8px; + height: 8px; + border-radius: 50%; + background: var(--tb-brand); + animation: tbCeGrantPulse 1.6s ease-in-out infinite; + &.tb-waiting { + animation: none; + background: none; + box-shadow: inset 0 0 0 2px var(--tb-brand); + } + } + + .tb-grant-card-text { + margin: 8px 0 0; + font-size: 13px; @media #{$mat-md-lg} { - height: 24px; - font-size: 12px; - padding: 0; - overflow: hidden; + margin-top: 4px; + font-size: 11px; + } + } + + .tb-grant-card-link { + display: flex; + flex-wrap: wrap; + gap: 5px 18px; + margin: 12px 0 0; + letter-spacing: normal; + font-size: 12.5px; + + a { + display: inline-flex; + align-items: center; + gap: 4px; + color: var(--tb-brand-ink); + text-decoration: none; + border-bottom: none; + + &:hover, &:focus { + text-decoration: underline; + text-underline-offset: 3px; + border-bottom: none; + } + + tb-icon { + color: inherit; + } } } .check-icon { - color: #198038; + width: 34px; + height: 34px; + border-radius: 50%; + display: flex; + align-items: center; + justify-content: center; + color: var(--tb-brand-ink); + background: var(--tb-brand-tint); font-weight: 600; @media #{$mat-md-lg} { font-size: 16px; @@ -107,12 +239,17 @@ .up-to-date-text { font-weight: 400; font-size: 14px; - line-height: 20px; - letter-spacing: 0.2px; - color: rgba(0, 0, 0, 0.76); + line-height: 1.55; + letter-spacing: normal; + color: rgba(0, 0, 0, 0.6); @media #{$mat-md-lg} { font-size: 11px; line-height: 16px; } } } + +@keyframes tbCeGrantPulse { + 0%, 100% { opacity: 1; } + 50% { opacity: 0.3; } +} diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/home-page/version-info.component.ts b/ui-ngx/src/app/modules/home/components/widget/lib/home-page/version-info.component.ts index d701f6f413..d4b25a1b0d 100644 --- a/ui-ngx/src/app/modules/home/components/widget/lib/home-page/version-info.component.ts +++ b/ui-ngx/src/app/modules/home/components/widget/lib/home-page/version-info.component.ts @@ -1,6 +1,6 @@ // SPDX-FileCopyrightText: Copyright The Thingsboard Authors // SPDX-License-Identifier: Apache-2.0 -import { ChangeDetectorRef, Component, OnInit } from '@angular/core'; +import { ChangeDetectionStrategy, Component, computed, OnDestroy, OnInit, signal } from '@angular/core'; import { PageComponent } from '@shared/components/page.component'; import { Store } from '@ngrx/store'; import { AppState } from '@core/core.state'; @@ -8,32 +8,152 @@ import { AdminService } from '@core/http/admin.service'; import { UpdateMessage } from '@shared/models/settings.models'; import { getCurrentAuthUser } from '@core/auth/auth.selectors'; import { Authority } from '@shared/models/authority.enum'; -import { of } from 'rxjs'; +import { of, Subscription } from 'rxjs'; +import { MatDialog } from '@angular/material/dialog'; +import { + CommunityGrantDialogComponent +} from '@home/components/widget/lib/home-page/community-grant-dialog.component'; +import { CommunityGrantService } from '@core/http/community-grant.service'; +import { + CommunityGrantCardState, + CommunityGrantParkReason, + CommunityGrantState, + communityGrantCardConfigs, + communityGrantPortalUrl, + communityGrantStateConfigs, + CommunityGrantCardConfig +} from '@shared/models/ce-grant/community-grant.models'; @Component({ selector: 'tb-version-info', templateUrl: './version-info.component.html', - styleUrls: ['./home-page-widget.scss', './version-info.component.scss'], + styleUrls: ['./home-page-widget.scss', './ce-grant-tokens.scss', './version-info.component.scss'], + changeDetection: ChangeDetectionStrategy.OnPush, standalone: false }) -export class VersionInfoComponent extends PageComponent implements OnInit { +export class VersionInfoComponent extends PageComponent implements OnInit, OnDestroy { authUser = getCurrentAuthUser(this.store); - updateMessage: UpdateMessage; + + readonly updateMessage = signal(null); + + readonly registrationLink = signal(communityGrantPortalUrl); + + readonly communityGrantCardState = CommunityGrantCardState; + + /** Null is a real answer to the update check, so it cannot double as "not yet". */ + private readonly updateChecked = signal(false); + + private readonly grantState = signal(null); + + private readonly grantStateKnown = signal(false); + + readonly grantCard = computed(() => communityGrantCardConfigs.get(this.grantState()) ?? null); + + readonly grantIcon = computed(() => { + const state = communityGrantStateConfigs.get(this.grantState()); + return state?.cardIcon || state?.icon; + }); + + readonly grantCardHasLinks = computed(() => + this.hasLinks(communityGrantCardConfigs.get(this.grantState()) ?? null)); + + private readonly grantParkReason = signal(null); + + readonly showExpiredNote = computed(() => this.isPark(null)); + + readonly showCheckFailedNote = computed(() => this.isPark(CommunityGrantParkReason.CHECK_FAILED)); + + readonly showPortalUnreachableNote = + computed(() => this.isPark(CommunityGrantParkReason.PORTAL_UNREACHABLE)); + + /** A registration outranks the release offer; anything about the release waits for both reads. */ + readonly cardState = computed(() => { + const card = this.grantCard(); + if (card) { + return card.body; + } + if (!this.grantStateKnown() || !this.updateChecked()) { + return CommunityGrantCardState.pending; + } + return this.authUser.authority === Authority.SYS_ADMIN + ? CommunityGrantCardState.offer + : CommunityGrantCardState.upToDate; + }); + + readonly offerVersion = computed(() => + this.updateMessage()?.updateAvailable ? this.updateMessage().latestVersion : '4.4'); + + private communityGrantStateSubscription: Subscription; constructor(protected store: Store, - private cd: ChangeDetectorRef, - private adminService: AdminService) { + private adminService: AdminService, + private communityGrantService: CommunityGrantService, + private dialog: MatDialog) { super(store); } ngOnInit() { (this.authUser.authority === Authority.SYS_ADMIN ? - this.adminService.checkUpdates() : of(null)).subscribe( - (updateMessage) => { - this.updateMessage = updateMessage; - this.cd.markForCheck(); - } - ); + this.adminService.checkUpdates() : of(null)).subscribe({ + next: (updateMessage) => { + this.updateMessage.set(updateMessage); + this.updateChecked.set(true); + }, + error: () => this.updateChecked.set(true) + }); + this.loadCommunityGrantState(); + } + + ngOnDestroy(): void { + this.communityGrantStateSubscription?.unsubscribe(); + super.ngOnDestroy(); + } + + private loadCommunityGrantState(): void { + if (this.authUser.authority !== Authority.SYS_ADMIN) { + this.grantStateKnown.set(true); + return; + } + this.communityGrantStateSubscription?.unsubscribe(); + this.communityGrantStateSubscription = this.communityGrantService.pollRegistration({ignoreErrors: true}) + .subscribe({ + next: (registration) => { + this.registrationLink.set(registration.registrationLink ?? communityGrantPortalUrl); + this.applyGrantState(registration.state, registration.parkReason); + }, + error: () => this.applyGrantState(null, null) + }); + } + + private applyGrantState(state: CommunityGrantState, parkReason: CommunityGrantParkReason): void { + this.grantState.set(state); + this.grantParkReason.set(parkReason); + this.grantStateKnown.set(true); + } + + /** `null` matches any park reason other than the two retryable ones. */ + private isPark(reason: CommunityGrantParkReason): boolean { + if (this.grantState() !== CommunityGrantState.expired) { + return false; + } + const parked = this.grantParkReason(); + return reason === null + ? parked !== CommunityGrantParkReason.CHECK_FAILED + && parked !== CommunityGrantParkReason.PORTAL_UNREACHABLE + : parked === reason; + } + + private hasLinks(config: CommunityGrantCardConfig): boolean { + return !!config?.registrationLink || !!config?.linkAction; + } + + getCommunityGrant(): void { + this.dialog.open(CommunityGrantDialogComponent, { + panelClass: ['tb-dialog', 'tb-fullscreen-dialog'], + maxWidth: '100vw', + maxHeight: '92vh', + autoFocus: false + }).afterClosed().subscribe(() => this.loadCommunityGrantState()); } } diff --git a/ui-ngx/src/app/shared/models/audit-log.models.ts b/ui-ngx/src/app/shared/models/audit-log.models.ts index 4f7ed322ea..a006ce11e2 100644 --- a/ui-ngx/src/app/shared/models/audit-log.models.ts +++ b/ui-ngx/src/app/shared/models/audit-log.models.ts @@ -51,7 +51,10 @@ export enum ActionType { TIMESERIES_DELETED = 'TIMESERIES_DELETED', ASSIGNED_TO_EDGE = 'ASSIGNED_TO_EDGE', UNASSIGNED_FROM_EDGE = 'UNASSIGNED_FROM_EDGE', - SMS_SENT = 'SMS_SENT' + SMS_SENT = 'SMS_SENT', + COMMUNITY_GRANT_OFFLINE_CHECKER_RUN = 'COMMUNITY_GRANT_OFFLINE_CHECKER_RUN', + COMMUNITY_GRANT_REQUEST_ACCESS = 'COMMUNITY_GRANT_REQUEST_ACCESS', + COMMUNITY_GRANT_ENROLLMENT = 'COMMUNITY_GRANT_ENROLLMENT' } export enum ActionStatus { @@ -97,6 +100,9 @@ export const actionTypeTranslations = new Map( [ActionType.ASSIGNED_TO_EDGE, 'audit-log.type-assigned-to-edge'], [ActionType.UNASSIGNED_FROM_EDGE, 'audit-log.type-unassigned-from-edge'], [ActionType.SMS_SENT, 'audit-log.type-sms-sent'], + [ActionType.COMMUNITY_GRANT_OFFLINE_CHECKER_RUN, 'audit-log.type-community-grant-offline-checker-run'], + [ActionType.COMMUNITY_GRANT_REQUEST_ACCESS, 'audit-log.type-community-grant-request-access'], + [ActionType.COMMUNITY_GRANT_ENROLLMENT, 'audit-log.type-community-grant-enrollment'], ] ); diff --git a/ui-ngx/src/app/shared/models/ce-grant/community-grant.models.ts b/ui-ngx/src/app/shared/models/ce-grant/community-grant.models.ts new file mode 100644 index 0000000000..7e04a45a87 --- /dev/null +++ b/ui-ngx/src/app/shared/models/ce-grant/community-grant.models.ts @@ -0,0 +1,479 @@ +// SPDX-FileCopyrightText: Copyright The Thingsboard Authors +// SPDX-License-Identifier: Apache-2.0 +import { HttpErrorResponse } from '@angular/common/http'; +import { TranslateService } from '@ngx-translate/core'; +import { parseHttpErrorMessage } from '@core/utils'; + +export enum CommunityGrantState { + intro = 'intro', + awaiting = 'awaiting', + verifying = 'verifying', + registered = 'registered', + review = 'review', + offline = 'offline', + verify = 'verify', + result = 'result', + /** The report was carried to the portal by hand; the outcome is read there, never reported back here. */ + handedOver = 'handedOver', + expired = 'expired', + already = 'already', + wrongInstallation = 'wrongInstallation' +} + +export type CommunityGrantMarkTone = 'brand' | 'info'; + +export type CommunityGrantRailKind = 'online' | 'offline'; + +export interface CommunityGrantStateConfig { + icon?: string; + cardIcon?: string; + tone?: CommunityGrantMarkTone; + rail?: CommunityGrantRailKind; + railStep?: number; + hero?: boolean; + live?: boolean; + spinner?: boolean; + topBanner?: string; +} + +export const communityGrantStateConfigs = + new Map([ + [CommunityGrantState.intro, {hero: true}], + [CommunityGrantState.awaiting, {icon: 'ce-grant-waiting', tone: 'brand', rail: 'online', railStep: 0, live: true}], + [CommunityGrantState.verifying, {spinner: true, tone: 'brand', rail: 'online', railStep: 1, live: true}], + [CommunityGrantState.registered, {icon: 'check', tone: 'brand'}], + [CommunityGrantState.review, {icon: 'hourglass_empty', tone: 'brand'}], + [CommunityGrantState.offline, {icon: 'computer', tone: 'brand', rail: 'offline', railStep: 0, topBanner: 'offlineBanner'}], + [CommunityGrantState.verify, {icon: 'upload_file', tone: 'brand', rail: 'offline', railStep: 1}], + [CommunityGrantState.result, {icon: 'assignment_return', tone: 'brand', rail: 'offline', railStep: 2}], + // Opens the report screen, so it shares `result`'s header. + [CommunityGrantState.handedOver, {cardIcon: 'check', icon: 'assignment_return', tone: 'brand', rail: 'offline', railStep: 2}], + [CommunityGrantState.expired, {icon: 'timer_off', tone: 'info'}], + [CommunityGrantState.already, {icon: 'how_to_reg', tone: 'info'}], + [CommunityGrantState.wrongInstallation, {icon: 'link_off', tone: 'info'}] + ]); + +export const communityGrantStateTitles = new Map([ + [CommunityGrantState.awaiting, 'ce-grant.awaiting-title'], + [CommunityGrantState.verifying, 'ce-grant.verifying-title'], + [CommunityGrantState.registered, 'ce-grant.registered-title'], + [CommunityGrantState.review, 'ce-grant.review-title'], + [CommunityGrantState.offline, 'ce-grant.offline-title'], + [CommunityGrantState.verify, 'ce-grant.verify-title'], + [CommunityGrantState.result, 'ce-grant.result-title'], + [CommunityGrantState.handedOver, 'ce-grant.result-title'], + [CommunityGrantState.expired, 'ce-grant.expired-title'], + [CommunityGrantState.already, 'ce-grant.already-title'], + [CommunityGrantState.wrongInstallation, 'ce-grant.wrong-installation-title'] +]); + +export enum CommunityGrantCardState { + progress = 'progress', + status = 'status', + offer = 'offer', + upToDate = 'upToDate', + /** A read is still out, so nothing is rendered. */ + pending = 'pending' +} + +export type CommunityGrantCardBody = CommunityGrantCardState.progress | CommunityGrantCardState.status; + +export interface CommunityGrantCardConfig { + body: CommunityGrantCardBody; + title: string; + text: string; + action?: string; + registrationLink?: string; + /** Label for a link that reopens this dialog, so it carries no external-link arrow. */ + linkAction?: string; + held?: boolean; + waiting?: boolean; + done?: boolean; +} + +/** `intro` and `expired` have no entry on purpose: the card falls through to the release offer. */ +export const communityGrantCardConfigs = new Map([ + [CommunityGrantState.awaiting, { + body: CommunityGrantCardState.progress, + title: 'ce-grant.card-progress-title', + text: 'ce-grant.card-awaiting-text', + action: 'ce-grant.action-continue' + }], + [CommunityGrantState.verifying, { + body: CommunityGrantCardState.progress, + title: 'ce-grant.card-progress-title', + text: 'ce-grant.card-verifying-text', + action: 'ce-grant.action-continue' + }], + [CommunityGrantState.offline, { + body: CommunityGrantCardState.progress, + title: 'ce-grant.card-progress-title', + text: 'ce-grant.card-offline-text', + action: 'ce-grant.action-continue' + }], + [CommunityGrantState.verify, { + body: CommunityGrantCardState.progress, + title: 'ce-grant.card-verify-title', + text: 'ce-grant.card-verify-text', + action: 'ce-grant.action-verify-deployment', + waiting: true + }], + [CommunityGrantState.result, { + body: CommunityGrantCardState.progress, + title: 'ce-grant.card-result-title', + text: 'ce-grant.card-result-text', + action: 'ce-grant.action-return-report', + waiting: true + }], + [CommunityGrantState.handedOver, { + body: CommunityGrantCardState.status, + title: 'ce-grant.card-handed-over-title', + text: 'ce-grant.card-handed-over-text', + registrationLink: 'ce-grant.card-handed-over-link', + linkAction: 'ce-grant.action-open-report', + done: true + }], + [CommunityGrantState.registered, { + body: CommunityGrantCardState.status, + title: 'ce-grant.card-registered-title', + text: 'ce-grant.card-registered-text', + registrationLink: 'ce-grant.card-registered-link', + done: true + }], + [CommunityGrantState.review, { + body: CommunityGrantCardState.status, + title: 'ce-grant.card-review-title', + text: 'ce-grant.card-review-text', + done: true + }], + [CommunityGrantState.already, { + body: CommunityGrantCardState.status, + title: 'ce-grant.card-already-title', + text: 'ce-grant.card-already-text-no-mask', + action: 'ce-grant.action-see-options', + held: true + }], + // Terminal: without an entry the card would fall through to the release offer. + [CommunityGrantState.wrongInstallation, { + body: CommunityGrantCardState.status, + title: 'ce-grant.card-wrong-installation-title', + text: 'ce-grant.card-wrong-installation-text', + action: 'ce-grant.action-see-details', + held: true + }] +]); + +export const communityGrantRailLabels = new Map([ + ['online', ['ce-grant.step-account-and-terms', 'ce-grant.step-verification', 'ce-grant.step-ce-grant']], + ['offline', ['ce-grant.step-account-and-terms', 'ce-grant.step-verification', 'ce-grant.step-report-back']] +]); + +export interface CommunityGrantRegistration { + state: CommunityGrantState; + mode?: CommunityGrantBackendMode; + /** Kept because {@link mapCommunityGrantState} is many-to-one and the dialog needs the raw state. */ + backendState?: CommunityGrantBackendState; + parkReason?: CommunityGrantParkReason; + portalUrl?: string; + /** A bearer credential: it identifies this registration wherever it is opened. */ + registrationLink?: string; + report?: string; + offlineRunInProgress?: boolean; + offlineRunError?: string; +} + +/** How often the dialog re-reads this instance's `GET /state`. */ +export const communityGrantPollInterval = 3000; + +export const communityGrantStallTimeout = 30000; + +/** Used when the server supplies no portal URL or sign-up link. */ +export const communityGrantPortalUrl = 'https://license.thingsboard.io'; + +/** Mirrors the backend's `CommunityGrantState`. */ +export enum CommunityGrantBackendState { + NOT_STARTED = 'NOT_STARTED', + AWAITING_SIGNUP = 'AWAITING_SIGNUP', + COLLECTING = 'COLLECTING', + VALIDATING = 'VALIDATING', + REPORT_HANDED_OVER = 'REPORT_HANDED_OVER', + REGISTERED = 'REGISTERED', + UNDER_REVIEW = 'UNDER_REVIEW', + ALREADY_REGISTERED = 'ALREADY_REGISTERED', + WRONG_INSTALLATION = 'WRONG_INSTALLATION', + RESUME = 'RESUME' +} + +/** Mirrors the backend's `CommunityGrantMode`: the server's own reachability to the portal. */ +export enum CommunityGrantBackendMode { + ONLINE = 'ONLINE', + OFFLINE = 'OFFLINE' +} + +/** Mirrors the backend's `CommunityGrantParkReason`; set only with `RESUME`. */ +export enum CommunityGrantParkReason { + LINK_EXPIRED = 'LINK_EXPIRED', + SIGNUP_ABANDONED = 'SIGNUP_ABANDONED', + CHECK_FAILED = 'CHECK_FAILED', + PORTAL_UNREACHABLE = 'PORTAL_UNREACHABLE' +} + +/** Mirrors the backend's `CommunityGrantStateInfo`. */ +export interface CommunityGrantStateInfo { + mode: CommunityGrantBackendMode; + state: CommunityGrantBackendState; + signUpUrl?: string; + lastPolledAt?: number; + parkReason?: CommunityGrantParkReason; + portalUrl?: string; + /** Present only while the flow sits on the report step; `GET /offline/report` serves it otherwise. */ + offlineReport?: string; + offlineRunInProgress?: boolean; + offlineRunError?: string; +} + +/** Mirrors the backend's `CommunityGrantState.isPollable()`. */ +const communityGrantPollableBackendStates: readonly CommunityGrantBackendState[] = [ + CommunityGrantBackendState.AWAITING_SIGNUP, + CommunityGrantBackendState.COLLECTING, + CommunityGrantBackendState.VALIDATING, + CommunityGrantBackendState.UNDER_REVIEW, + CommunityGrantBackendState.REPORT_HANDED_OVER +]; + +/** + * `VALIDATING` + `ONLINE` maps to `verifying` even when a by-hand report exists; the dialog tells the two + * apart by the report. Throws on a value this build does not know. + */ +export function mapCommunityGrantState(state: CommunityGrantBackendState, + mode: CommunityGrantBackendMode): CommunityGrantState { + switch (state) { + case CommunityGrantBackendState.NOT_STARTED: + return CommunityGrantState.intro; + case CommunityGrantBackendState.AWAITING_SIGNUP: + return mapByMode(mode, CommunityGrantState.awaiting, CommunityGrantState.offline); + case CommunityGrantBackendState.COLLECTING: + return mapByMode(mode, CommunityGrantState.verifying, CommunityGrantState.verify); + case CommunityGrantBackendState.VALIDATING: + return mapByMode(mode, CommunityGrantState.verifying, CommunityGrantState.result); + case CommunityGrantBackendState.REPORT_HANDED_OVER: + return CommunityGrantState.handedOver; + case CommunityGrantBackendState.REGISTERED: + return CommunityGrantState.registered; + case CommunityGrantBackendState.UNDER_REVIEW: + return CommunityGrantState.review; + case CommunityGrantBackendState.ALREADY_REGISTERED: + return CommunityGrantState.already; + case CommunityGrantBackendState.WRONG_INSTALLATION: + return CommunityGrantState.wrongInstallation; + case CommunityGrantBackendState.RESUME: + return CommunityGrantState.expired; + default: + return assertNeverCommunityGrantValue('backend Community Grant state', state); + } +} + +function mapByMode(mode: CommunityGrantBackendMode, + online: CommunityGrantState, + offline: CommunityGrantState): CommunityGrantState { + switch (mode) { + case CommunityGrantBackendMode.ONLINE: + return online; + case CommunityGrantBackendMode.OFFLINE: + return offline; + default: + return assertNeverCommunityGrantValue('backend Community Grant mode', mode); + } +} + +function assertNeverCommunityGrantValue(what: string, value: never): never { + throw new Error(`Unhandled ${what}: ${JSON.stringify(value)}`); +} + +/** Checked in either mode: offline, `handedOver` re-reads `/state` to no effect. */ +export const communityGrantOnlinePollableStates: ReadonlySet = new Set( + communityGrantPollableBackendStates.map(state => mapCommunityGrantState(state, CommunityGrantBackendMode.ONLINE)) +); + +export function communityGrantRegistrationFrom(info: CommunityGrantStateInfo): CommunityGrantRegistration { + return { + state: mapCommunityGrantState(info.state, info.mode), + mode: info.mode, + backendState: info.state, + parkReason: info.parkReason, + portalUrl: info.portalUrl, + registrationLink: info.signUpUrl, + report: info.offlineReport, + offlineRunInProgress: info.offlineRunInProgress, + offlineRunError: info.offlineRunError + }; +} + +/** + * The `TBICBDL1` enrollment bundle the License Portal writes for one installation: + * + * ``` + * offset width field value / constraint + * 0 8 MAGIC "TBICBDL1" + * 8 1 VERSION 0x01 + * 9 4 MANIFEST_LEN uint32 big-endian, 1..8192 + * 13 4 CHECKER_LEN uint32 big-endian, >= 1 + * 17 74 RELSIG a complete TBICSIG1 file, verbatim + * 91 M MANIFEST UTF-8 JSON + * 91+M C CHECKER the executable image + * ``` + */ +const COMMUNITY_GRANT_BUNDLE_MAGIC = 'TBICBDL1'; +const COMMUNITY_GRANT_BUNDLE_VERSION = 1; +const COMMUNITY_GRANT_BUNDLE_HEADER_LEN = 91; +const COMMUNITY_GRANT_BUNDLE_MIN_MANIFEST_LEN = 1; +const COMMUNITY_GRANT_BUNDLE_MAX_MANIFEST_LEN = 8192; + +export interface CommunityGrantBundleManifest { + bundleVersion: number; + os: string; + arch: string; + clusterId: string; + checkerInput: Record; + challengeExpiresAt: number; + issuedAt: number; + checkerFileName: string; +} + +export enum CommunityGrantBundleErrorCode { + /** Too short, wrong magic, or an unsupported version. */ + NOT_A_BUNDLE = 'NOT_A_BUNDLE', + MALFORMED = 'MALFORMED' +} + +export class CommunityGrantBundleParseError extends Error { + constructor(public readonly code: CommunityGrantBundleErrorCode, message: string) { + super(message); + this.name = 'CommunityGrantBundleParseError'; + } +} + +export interface CommunityGrantBundlePreflight { + manifest: CommunityGrantBundleManifest; + /** By this browser's clock. A warning only: the portal's clock decides expiry. */ + challengeExpired: boolean; +} + +/** + * Pre-flight before uploading: reads only the header and manifest, and checks structure alone. The + * installation, platform and release signature are checked by the server. + */ +export async function peekCommunityGrantBundle(file: File): Promise { + if (!file || file.size < COMMUNITY_GRANT_BUNDLE_HEADER_LEN) { + throw notABundle(`The file is ${file ? file.size : 0} bytes, shorter than a bundle's ` + + `${COMMUNITY_GRANT_BUNDLE_HEADER_LEN}-byte header.`); + } + const header = new DataView(await file.slice(0, COMMUNITY_GRANT_BUNDLE_HEADER_LEN).arrayBuffer()); + for (let i = 0; i < COMMUNITY_GRANT_BUNDLE_MAGIC.length; i++) { + if (header.getUint8(i) !== COMMUNITY_GRANT_BUNDLE_MAGIC.charCodeAt(i)) { + throw notABundle('The file does not carry the marker every enrollment bundle begins with.'); + } + } + const version = header.getUint8(COMMUNITY_GRANT_BUNDLE_MAGIC.length); + if (version !== COMMUNITY_GRANT_BUNDLE_VERSION) { + throw notABundle(`The bundle declares format version ${version}, and this server supports version ` + + `${COMMUNITY_GRANT_BUNDLE_VERSION} only.`); + } + const manifestLength = header.getUint32(9); + const checkerLength = header.getUint32(13); + if (manifestLength < COMMUNITY_GRANT_BUNDLE_MIN_MANIFEST_LEN + || manifestLength > COMMUNITY_GRANT_BUNDLE_MAX_MANIFEST_LEN) { + throw malformedBundle(`The bundle declares a manifest of ${manifestLength} bytes, outside the permitted ` + + `range of ${COMMUNITY_GRANT_BUNDLE_MIN_MANIFEST_LEN} to ${COMMUNITY_GRANT_BUNDLE_MAX_MANIFEST_LEN}.`); + } + if (checkerLength < 1) { + throw malformedBundle(`The bundle declares a checker of ${checkerLength} bytes.`); + } + const expectedSize = COMMUNITY_GRANT_BUNDLE_HEADER_LEN + manifestLength + checkerLength; + if (file.size !== expectedSize) { + throw malformedBundle(`The bundle's declared lengths need a file of ${expectedSize} bytes, but this one ` + + `is ${file.size} bytes.`); + } + const manifestBytes = await file + .slice(COMMUNITY_GRANT_BUNDLE_HEADER_LEN, COMMUNITY_GRANT_BUNDLE_HEADER_LEN + manifestLength) + .arrayBuffer(); + const manifest = parseCommunityGrantBundleManifest(manifestBytes); + // Strictly later, as the portal compares: the challenge is still live at the deadline instant. + return {manifest, challengeExpired: Date.now() > manifest.challengeExpiresAt}; +} + +function parseCommunityGrantBundleManifest(bytes: ArrayBuffer): CommunityGrantBundleManifest { + let text: string; + try { + // `fatal`, so binary fails here as unreadable text rather than later as bad JSON. + text = new TextDecoder('utf-8', {fatal: true}).decode(bytes); + } catch { + throw malformedBundle('The bundle\'s manifest is not readable text.'); + } + let parsed: unknown; + try { + parsed = JSON.parse(text); + } catch { + throw malformedBundle('The bundle\'s manifest is not valid JSON.'); + } + if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) { + throw malformedBundle('The bundle\'s manifest is not a JSON object.'); + } + const candidate = parsed as Record; + // Presence and type only; the server judges the values. + for (const key of ['os', 'arch', 'clusterId', 'checkerFileName']) { + if (typeof candidate[key] !== 'string' || !(candidate[key] as string).length) { + throw malformedBundle(`The bundle's manifest is missing "${key}".`); + } + } + const checkerInput = candidate.checkerInput; + if (!checkerInput || typeof checkerInput !== 'object' || Array.isArray(checkerInput) + || !Object.keys(checkerInput).length) { + throw malformedBundle('The bundle\'s manifest is missing "checkerInput".'); + } + for (const key of ['bundleVersion', 'challengeExpiresAt', 'issuedAt']) { + if (typeof candidate[key] !== 'number' || !Number.isFinite(candidate[key] as number)) { + throw malformedBundle(`The bundle's manifest is missing "${key}".`); + } + } + if (candidate.bundleVersion !== COMMUNITY_GRANT_BUNDLE_VERSION) { + throw notABundle(`The bundle's manifest declares version ${candidate.bundleVersion}.`); + } + return candidate as unknown as CommunityGrantBundleManifest; +} + +function notABundle(message: string): CommunityGrantBundleParseError { + return new CommunityGrantBundleParseError(CommunityGrantBundleErrorCode.NOT_A_BUNDLE, message); +} + +function malformedBundle(message: string): CommunityGrantBundleParseError { + return new CommunityGrantBundleParseError(CommunityGrantBundleErrorCode.MALFORMED, message); +} + +/** A `text` request's error body arrives as an unparsed JSON string, so it is parsed first. */ +function communityGrantErrorHasServerMessage(error: HttpErrorResponse, responseType?: string): boolean { + let body: unknown = null; + if (responseType === 'text') { + try { + body = error.error ? JSON.parse(error.error) : null; + } catch { + body = null; + } + } else { + body = error.error; + } + return !!(body && typeof body === 'object' && (body as { message?: unknown }).message); +} + +/** + * The server's own message, or the generic one when it sent none — never `HttpErrorResponse.message`, which + * names the request path. Pass the request's `responseType`. + */ +export function resolveCommunityGrantErrorMessage(error: HttpErrorResponse, + translate: TranslateService, + responseType?: string): string { + if (!communityGrantErrorHasServerMessage(error, responseType)) { + return translate.instant('ce-grant.register-error-generic'); + } + return parseHttpErrorMessage(error, translate, responseType).message; +} diff --git a/ui-ngx/src/app/shared/models/icon.models.ts b/ui-ngx/src/app/shared/models/icon.models.ts index 7e76bf2c2d..0d2bed0621 100644 --- a/ui-ngx/src/app/shared/models/icon.models.ts +++ b/ui-ngx/src/app/shared/models/icon.models.ts @@ -60,7 +60,10 @@ export const svgIcons: {[key: string]: string} = { '14.7267L9.61134 13.5985L8.48664 14.7213L7.64059 13.8767L8.76673 12.7525L7.64928 11.6331L8.77533 10.5051L7.64059 9.37227L8.48664 ' + '8.52767L9.61993 9.65905L10.7461 8.53103L9.61465 7.40158L10.4607 6.55697L11.5907 7.68499L12.7169 6.55688L13.843 7.68494L14.9729 ' + '6.55688ZM12.7169 8.24609L13.5629 9.0907L10.1787 12.4691L9.33268 11.6245L12.7169 8.24609ZM13.4262 10.0805L14.2723 10.9251L11.4521 ' + - '13.7404L10.6061 12.8958L13.4262 10.0805ZM14.6909 13.0321L13.8449 12.1875L11.8708 14.1583L12.7168 15.0029L14.6909 13.0321Z"/>' + '13.7404L10.6061 12.8958L13.4262 10.0805ZM14.6909 13.0321L13.8449 12.1875L11.8708 14.1583L12.7168 15.0029L14.6909 13.0321Z"/>', + 'ce-grant-waiting': '' }; export const svgIconsUrl: { [key: string]: string } = { diff --git a/ui-ngx/src/assets/ce-grant/key-visual-apps.svg b/ui-ngx/src/assets/ce-grant/key-visual-apps.svg new file mode 100644 index 0000000000..ee92510d69 --- /dev/null +++ b/ui-ngx/src/assets/ce-grant/key-visual-apps.svg @@ -0,0 +1,124 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/ui-ngx/src/assets/locale/locale.constant-en_US.json b/ui-ngx/src/assets/locale/locale.constant-en_US.json index bcac1a5d1a..d38bb11913 100644 --- a/ui-ngx/src/assets/locale/locale.constant-en_US.json +++ b/ui-ngx/src/assets/locale/locale.constant-en_US.json @@ -1082,6 +1082,9 @@ "type-timeseries-updated": "Telemetry updated", "type-timeseries-deleted": "Telemetry deleted", "type-sms-sent": "SMS sent", + "type-community-grant-offline-checker-run": "Community Grant offline check run", + "type-community-grant-request-access": "Community Grant access requested", + "type-community-grant-enrollment": "Community Grant enrollment", "any-type":"Any type", "audit-log-filter-title": "Audit log filter", "filter-title": "Filter", @@ -1660,6 +1663,125 @@ "token": "Token", "token-required": "Token is required." }, + "ce-grant": { + "ce-grant": "Community Grant", + "ce-grant-note": "Free, and it doesn’t expire.", + "title": "Community Grant registration", + "load-error-lede": "Couldn’t check this deployment’s registration status.", + "step-account-and-terms": "Account and terms", + "step-verification": "Verification", + "step-ce-grant": "Community Grant", + "step-report-back": "Report back", + "intro-heading": "Your Community Grant makes the upgrade to 4.4 free", + "intro-lede": "From 4.4, Community and Professional become one source-available platform, and running it takes a license key. What you run today is untouched: 4.3 stays Apache 2.0 permanently.", + "intro-read-announcement": "Read the announcement", + "intro-included-title": "What’s included", + "intro-included-devices-and-servers-lead": "The devices and servers you were running when 4.4 was announced, plus 10% headroom on devices.", + "intro-included-devices-and-servers-text": "Never a grant below 100 devices, with headroom up to 1,000, so normal growth stays free.", + "intro-included-permanent-lead": "Permanent.", + "intro-included-permanent-text": "The grant does not expire, any white-labeling you already run stays, and past use is never charged for.", + "intro-included-security-lead": "SSO, RBAC and Secrets.", + "intro-included-security-text": "The advanced security features that were Professional-only, at no extra cost.", + "intro-included-register-lead": "Register any time until July 20, 2027.", + "intro-included-register-text": "That is the day registration closes and support for 4.3 ends.", + "intro-assurance": "Nothing on this deployment changes today. Registering opens the License Portal in a new tab: create your account there, and this dialog updates on its own.", + "register-error-generic": "Something went wrong starting your registration. Try again, or contact support if this continues.", + "awaiting-title": "Finish in the License Portal", + "awaiting-lede": "Create your account there and accept the grant terms.", + "need-link": "Need the link?", + "link-use-note": "Use it on any machine, or send it to whoever handles licensing.", + "link-share-caution": "Registers this deployment to whoever opens it — share with care.", + "stall-note": "No response from the portal yet. If this deployment’s connection is restricted, finish from any machine using the link above — it’s tied to this deployment wherever it’s opened.", + "verifying-title": "Verifying your deployment", + "verifying-lede": "It runs read-only on this server, and can take a few minutes on a large database.", + "no-report-yet": "No report yet?", + "verifying-stall-note": "If this deployment’s connection is restricted, the check can run here by hand instead — you carry the report to the portal yourself.", + "privacy-online": "It reads entity counts, creation timestamps and table sizes — never telemetry values, device names or personal data — and sends one encrypted report to the portal.", + "privacy-offline": "It reads entity counts, creation timestamps and table sizes — never telemetry values, device names or personal data. Nothing leaves this server; you carry the encrypted report back yourself.", + "registered-title": "This deployment is registered", + "registered-lede": "We’ve emailed you a copy of what was granted. The license key is in your License Portal account — apply it during the upgrade to 4.4, and nothing on this deployment changes before then.", + "review-title": "We’re reviewing your registration", + "review-lede": "You’ll hear from us at the address on your portal account as soon as it’s done. This deployment keeps running as it is until then.", + "offline-title": "Register on a connected machine", + "offline-lede": "Open this link there and create your account. The portal sends you back here once, with a tool to run on this server — and you carry its report back.", + "offline-caution": "This deployment can’t reach the License Portal.", + "verify-title": "Verify this deployment", + "verify-lede": "It runs read-only, and can take a few minutes on a large database.", + "verify-upload-tool": "Upload the deployment verification tool", + "verify-choose-bundle-file": "Choose the bundle file", + "verify-upload-hint": "Upload it as you downloaded it — your deployment opens the file itself, and checks the tool’s signature before running anything.", + "verify-error-no-file": "Choose the bundle file — the one you downloaded from the portal for this server’s platform.", + "verify-error-not-a-bundle": "Invalid enrollment bundle file. Choose the bundle file — the one you downloaded from the portal for this server’s platform.", + "verify-error-malformed": "Malformed enrollment bundle file. Choose the bundle file — the one you downloaded from the portal for this server’s platform.", + "bundle-expired-warning": "This bundle expired on {{ date }}. You can still run the check — if the report is refused, download a fresh bundle.", + "verify-error-failed": "The check couldn’t read this deployment’s database. Try again — if it keeps failing, our team can finish this by hand: contact support.", + "result-title": "Return this report to the portal", + "result-lede": "Paste it into the portal page you started from.", + "result-error-empty": "No report content came back. Try again.", + "result-safe-to-close": "Not pasted yet? This stays here.", + "expired-title": "This registration link has expired", + "expired-lede": "The link timed out or was replaced by a newer one.", + "expired-text": "Start again issues a fresh link for this deployment — nothing else is affected.", + "portal-unreachable-title": "Couldn’t reach the License Portal", + "portal-unreachable-lede": "This deployment stopped getting answers from the portal, so the registration didn’t finish.", + "portal-unreachable-text": "Nothing was registered and nothing here has changed. Trying again checks the connection afresh — and if the portal still can’t be reached, it will offer to register from another machine instead.", + "check-failed-title": "The deployment verification couldn’t finish", + "check-failed-lede": "After several attempts the verification tool didn’t complete on this server.", + "check-failed-text": "Try again — if it keeps failing, our team can finish this by hand: contact support.", + "already-title": "This deployment is already registered", + "already-lede-no-mask": "A deployment can hold only one Community Grant.", + "already-same-organization": "The license key is in the account that registered it. If that’s yours — a restored backup registers under the same identity — sign in to the License Portal and copy it from there.", + "already-someone-else-registered": "If someone else in your organization registered it, ask them for the key — or request access, and we’ll email the registered contact.", + "already-request-sent": "Requested — the registered contact decides what happens next. If you know who they are, asking directly is faster.", + "wrong-installation-title": "This deployment can’t be registered", + "wrong-installation-lede": "This deployment’s installation records don’t match what the License Portal has on file, so a Community Grant can’t be registered from here.", + "wrong-installation-text": "Nothing on this deployment has changed, and no grant was registered. This is rare, and usually follows a database restore or migration — contact support and our team can sort it out.", + "safe-to-close": "Safe to close.", + "card-expired-note": "Your earlier registration link expired — starting again takes a few seconds.", + "card-check-failed-note": "The scale check didn’t finish — trying again takes a few seconds.", + "card-portal-unreachable-note": "The License Portal didn’t answer — trying again re-checks the connection.", + "card-progress-title": "Registering this deployment", + "card-awaiting-text": "Registration continues in the License Portal — this updates on its own once you’ve finished there.", + "card-verifying-text": "Verifying this deployment — a few minutes, all on this server.", + "card-offline-text": "Registration continues in the License Portal on another machine — continue here when a step needs this server.", + "card-verify-title": "Verification waiting here", + "card-verify-text": "Upload the enrollment bundle from the portal, then run verification here.", + "card-result-title": "Report ready to return", + "card-result-text": "Copy it into the License Portal to finish registering.", + "card-registered-title": "Community Grant registered", + "card-registered-text": "Nothing more to do here — apply your license key when you upgrade this deployment to 4.4.", + "card-registered-link": "See what was granted", + "card-handed-over-title": "Report handed over", + "card-handed-over-text": "Your registration finishes in the License Portal — the outcome and the key are there; this deployment isn’t told.", + "card-handed-over-link": "Follow your registration", + "card-review-title": "Registration under review", + "card-review-text": "You’ll hear from us as soon as it’s done. This deployment keeps running as it is.", + "card-wrong-installation-title": "Can’t be registered", + "card-wrong-installation-text": "This deployment’s installation records don’t match the License Portal’s, so no grant was registered.", + "card-already-title": "Already registered", + "card-already-text-no-mask": "A Community Grant for this deployment already exists — a deployment can hold only one.", + "action-not-now": "Not now", + "action-register": "Register this deployment", + "action-close": "Close", + "action-copy": "Copy", + "action-copied": "Copied", + "action-open": "Open", + "action-reissue-link": "Reissue link", + "action-continue-to-verification": "Continue to verification", + "action-try-again": "Try again", + "action-back": "Back", + "action-run-verification": "Run verification", + "action-start-again": "Start again", + "action-request-access": "Request access", + "action-continue": "Continue", + "action-see-options": "See your options", + "action-see-details": "See details", + "action-return-report": "Return the report", + "action-report-handed-over": "Report handed over", + "action-open-report": "Open the report", + "action-verify-by-hand-instead": "Verify by hand instead", + "action-verify-deployment": "Verify this deployment" + }, "confirm-on-exit": { "message": "You have unsaved changes. Are you sure you want to leave this page?", "html-message": "You have unsaved changes.
    Are you sure you want to leave this page?", @@ -10300,10 +10422,11 @@ "contact-us": "Contact us", "current-version": "Current version", "current": "Current", - "available-version": "Available version", - "available": "Available", - "upgrade": "Upgrade", - "version-is-up-to-date": "Version is up to date" + "version-is-up-to-date": "Version is up to date", + "thingsboard-version-available": "ThingsBoard {{ version }} is available", + "free-community-grant-text": "4.4 is licensed differently and requires a license key. Your Community Grant is free.", + "get-community-grant": "Get your Community Grant", + "community-grant-registration-close": "Registration closes July 20, 2027." }, "usage-info": { "title": "Usage", diff --git a/ui-ngx/src/assets/locale/locale.constant-ro_RO.json b/ui-ngx/src/assets/locale/locale.constant-ro_RO.json index f1b712e205..345c5d8aac 100644 --- a/ui-ngx/src/assets/locale/locale.constant-ro_RO.json +++ b/ui-ngx/src/assets/locale/locale.constant-ro_RO.json @@ -1399,7 +1399,7 @@ "metadata-required": "Intrările metadata nu pot fi vide", "output": "Ieşire", "test": "Test", - "help": "Ajutor", + "help": "Ajutor" }, "tenant": { "tenant": "Locatar", diff --git a/ui-ngx/src/styles.scss b/ui-ngx/src/styles.scss index 44ebced31e..9ebf19e219 100644 --- a/ui-ngx/src/styles.scss +++ b/ui-ngx/src/styles.scss @@ -2,6 +2,7 @@ // SPDX-License-Identifier: Apache-2.0 /* You can add global styles to this file, and also import other style files */ @import 'typeface-roboto/index.css'; +@import 'typeface-roboto-mono/index.css'; @import 'font-awesome/css/font-awesome.min.css'; @import 'theme.scss'; @import './scss/constants'; diff --git a/ui-ngx/yarn.lock b/ui-ngx/yarn.lock index 7d184f78dc..ea4d0a9122 100644 --- a/ui-ngx/yarn.lock +++ b/ui-ngx/yarn.lock @@ -10570,6 +10570,11 @@ typed-assert@^1.0.8: resolved "https://registry.yarnpkg.com/typed-assert/-/typed-assert-1.0.9.tgz#8af9d4f93432c4970ec717e3006f33f135b06213" integrity sha512-KNNZtayBCtmnNmbo5mG47p1XsCyrx6iVqomjcZnec/1Y5GGARaxPs6r49RnSPeUP3YjNYiU9sQHAtY4BBvnZwg== +typeface-roboto-mono@^1.1.13: + version "1.1.13" + resolved "https://registry.yarnpkg.com/typeface-roboto-mono/-/typeface-roboto-mono-1.1.13.tgz#2af8662db8f9119c00efd55d6ed8877d2a69ec94" + integrity sha512-pnzDc70b7ywJHin/BUFL7HZX8DyOTBLT2qxlJ92eH1UJOFcENIBXa9IZrxsJX/gEKjbEDKhW5vz/TKRBNk/ufQ== + typeface-roboto@^1.1.13: version "1.1.13" resolved "https://registry.yarnpkg.com/typeface-roboto/-/typeface-roboto-1.1.13.tgz#9c4517cb91e311706c74823e857b4bac9a764ae5" From d37e0c3506c9df31347127218af5b41443da8640 Mon Sep 17 00:00:00 2001 From: Maksym Tsymbarov Date: Thu, 24 Sep 2026 22:09:51 +0200 Subject: [PATCH 077/159] Add CARTO as a separate map provider with an optional API key (#16189) * Add API key support for CARTO basemap layers * Move CARTO basemaps to a dedicated map provider and drop legacy HERE v2 credentials - Add MapProvider.carto with its own layer types, settings and TbCartoMapLayer; the API key is optional since CARTO serves tiles without one. - Read CARTO layers stored under the OpenStreetMap provider as CARTO layers (normalized in the layer factory and in the map layers settings form), so existing widgets migrate on the next settings save without an upgrade script. - Reset the API key when switching to CARTO instead of keeping the previous provider's key. - Remove the useV3 toggle and app_id/app_code fields from legacy HERE settings; leaflet-providers 4.x only supports HERE v3 with an API key. --------- Co-authored-by: Vladyslav Prykhodko --- ui-ngx/package.json | 2 +- .../widget/lib/maps-legacy/map-models.ts | 6 -- .../lib/maps-legacy/providers/here-map.ts | 11 ++- .../components/widget/lib/maps/map-layer.ts | 31 +++++++- .../common/map/map-layer-row.component.html | 8 +++ .../common/map/map-layer-row.component.ts | 14 +++- .../map-layer-settings-panel.component.html | 18 ++++- .../map/map-layer-settings-panel.component.ts | 18 ++++- .../common/map/map-layers.component.ts | 5 +- .../here-map-provider-settings.component.html | 23 ++---- .../here-map-provider-settings.component.ts | 34 ++------- .../shared/models/widget/maps/map.models.ts | 72 +++++++++++++++++-- .../assets/locale/locale.constant-en_US.json | 16 +++-- ui-ngx/yarn.lock | 8 +-- 14 files changed, 181 insertions(+), 85 deletions(-) diff --git a/ui-ngx/package.json b/ui-ngx/package.json index c830027a3c..c410d5bed4 100644 --- a/ui-ngx/package.json +++ b/ui-ngx/package.json @@ -61,7 +61,7 @@ "jszip": "^3.10.1", "leaflet": "1.9.4", "leaflet-polylinedecorator": "1.6.0", - "leaflet-providers": "2.0.0", + "leaflet-providers": "4.0.0", "leaflet.gridlayer.googlemutant": "0.15.0", "leaflet.markercluster": "1.5.3", "libphonenumber-js": "^1.12.35", diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/maps-legacy/map-models.ts b/ui-ngx/src/app/modules/home/components/widget/lib/maps-legacy/map-models.ts index b918e859e6..a34f88e9b0 100644 --- a/ui-ngx/src/app/modules/home/components/widget/lib/maps-legacy/map-models.ts +++ b/ui-ngx/src/app/modules/home/components/widget/lib/maps-legacy/map-models.ts @@ -121,9 +121,6 @@ export const hereMapProviderTranslationMap = new Map( export interface HereMapProviderSettings { mapProviderHere: HereMapProvider; credentials: { - useV3: boolean; - app_id: string; - app_code: string; apiKey: string; }; } @@ -131,9 +128,6 @@ export interface HereMapProviderSettings { export const defaultHereMapProviderSettings: HereMapProviderSettings = { mapProviderHere: HereMapProvider.hereNormalDay, credentials: { - useV3: true, - app_id: 'AhM6TzD9ThyK78CT3ptx', - app_code: 'p6NPiITB3Vv0GMUFnkLOOg', apiKey: 'kVXykxAfZ6LS4EbCTO02soFVfjA7HoBzNVVH9u7nzoE' } }; diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/maps-legacy/providers/here-map.ts b/ui-ngx/src/app/modules/home/components/widget/lib/maps-legacy/providers/here-map.ts index 5afa3c4c6d..64f4f6752b 100644 --- a/ui-ngx/src/app/modules/home/components/widget/lib/maps-legacy/providers/here-map.ts +++ b/ui-ngx/src/app/modules/home/components/widget/lib/maps-legacy/providers/here-map.ts @@ -2,9 +2,9 @@ // SPDX-License-Identifier: Apache-2.0 import L from 'leaflet'; import LeafletMap from '../leaflet-map'; -import { DEFAULT_ZOOM_LEVEL, WidgetUnitedMapSettings } from '../map-models'; +import { DEFAULT_ZOOM_LEVEL, defaultHereMapProviderSettings, WidgetUnitedMapSettings } from '../map-models'; import { WidgetContext } from '@home/models/widget-component.models'; -import { isDefinedAndNotNull } from '@core/utils'; +import { hereV3Provider } from '@shared/models/widget/maps/map.models'; export class HEREMap extends LeafletMap { constructor(ctx: WidgetContext, $container: HTMLElement, options: WidgetUnitedMapSettings) { @@ -13,11 +13,8 @@ export class HEREMap extends LeafletMap { doubleClickZoom: !this.options.disableDoubleClickZooming, zoomControl: !this.options.disableZoomControl }).setView(options?.parsedDefaultCenterPosition, options?.defaultZoomLevel || DEFAULT_ZOOM_LEVEL); - let provider = options.mapProviderHere || 'HERE.normalDay'; - if (options.credentials.useV3 && isDefinedAndNotNull(options.credentials.apiKey)) { - provider = options.mapProviderHere?.replace('HERE', 'HEREv3') || 'HEREv3.normalDay'; - } - const tileLayer = (L.tileLayer as any).provider(provider, options.credentials); + const apiKey = options.credentials?.apiKey || defaultHereMapProviderSettings.credentials.apiKey; + const tileLayer = L.tileLayer.provider(hereV3Provider(options.mapProviderHere), {apiKey}); tileLayer.addTo(map); super.setMap(map); } diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/maps/map-layer.ts b/ui-ngx/src/app/modules/home/components/widget/lib/maps/map-layer.ts index a79f290c9b..d61e81ca6e 100644 --- a/ui-ngx/src/app/modules/home/components/widget/lib/maps/map-layer.ts +++ b/ui-ngx/src/app/modules/home/components/widget/lib/maps/map-layer.ts @@ -1,7 +1,9 @@ // SPDX-FileCopyrightText: Copyright The Thingsboard Authors // SPDX-License-Identifier: Apache-2.0 import { + CartoMapLayerSettings, CustomMapLayerSettings, + defaultCartoMapLayerSettings, defaultCustomMapLayerSettings, defaultGoogleMapLayerSettings, defaultHereMapLayerSettings, @@ -10,8 +12,10 @@ import { defaultTencentMapLayerSettings, GoogleMapLayerSettings, HereMapLayerSettings, + hereV3Provider, MapLayerSettings, MapProvider, + normalizeMapLayerSettings, OpenStreetMapLayerSettings, ReferenceLayerType, TencentMapLayerSettings, WEBGL_ERROR_EVENT @@ -46,9 +50,12 @@ export abstract class TbMapLayer { static fromSettings(ctx: WidgetContext, inputSettings: DeepPartial) { + inputSettings = normalizeMapLayerSettings(inputSettings as MapLayerSettings); switch (inputSettings.provider) { case MapProvider.openstreet: return new TbOpenStreetMapLayer(ctx, inputSettings); + case MapProvider.carto: + return new TbCartoMapLayer(ctx, inputSettings); case MapProvider.google: return new TbGoogleMapLayer(ctx, inputSettings); case MapProvider.tencent: @@ -212,6 +219,24 @@ class TbOpenStreetMapLayer extends TbMapLayer { } +class TbCartoMapLayer extends TbMapLayer { + + constructor(protected ctx: WidgetContext, + protected inputSettings: DeepPartial) { + super(ctx, inputSettings); + } + + protected defaultSettings(): CartoMapLayerSettings { + return defaultCartoMapLayerSettings; + } + + protected createLayer(): Observable { + const layer = L.tileLayer.provider(this.settings.layerType, {apikey: this.settings.apiKey || ''}); + return of(layer); + } + +} + class TbGoogleMapLayer extends TbMapLayer { static loadedApiKeysGlobal: {[key: string]: boolean} = {}; @@ -293,7 +318,7 @@ class TbHereMapLayer extends TbMapLayer { protected createLayer(): Observable { const apiKey = this.settings.apiKey || defaultHereMapLayerSettings.apiKey; - const layer = L.tileLayer.provider(this.settings.layerType, {useV3: true, apiKey} as any); + const layer = L.tileLayer.provider(hereV3Provider(this.settings.layerType), {apiKey}); return of(layer); } @@ -311,7 +336,9 @@ class TbCustomMapLayer extends TbMapLayer { } protected createLayer(): Observable { - const layer = L.tileLayer(this.settings.tileUrl); + const layer = L.tileLayer(this.settings.tileUrl, this.settings.customAttribution ? { + attribution: this.settings.customAttribution + } : undefined); return of(layer); } diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/settings/common/map/map-layer-row.component.html b/ui-ngx/src/app/modules/home/components/widget/lib/settings/common/map/map-layer-row.component.html index e19007a1e5..02ddc00901 100644 --- a/ui-ngx/src/app/modules/home/components/widget/lib/settings/common/map/map-layer-row.component.html +++ b/ui-ngx/src/app/modules/home/components/widget/lib/settings/common/map/map-layer-row.component.html @@ -23,6 +23,14 @@ + + + + {{ cartoLayerTranslationMap.get(layerType) | translate }} + + + diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/settings/common/map/map-layer-row.component.ts b/ui-ngx/src/app/modules/home/components/widget/lib/settings/common/map/map-layer-row.component.ts index 9680188046..93ed9be3f1 100644 --- a/ui-ngx/src/app/modules/home/components/widget/lib/settings/common/map/map-layer-row.component.ts +++ b/ui-ngx/src/app/modules/home/components/widget/lib/settings/common/map/map-layer-row.component.ts @@ -25,6 +25,8 @@ import { TbPopoverService } from '@shared/components/popover.service'; import { TranslateService } from '@ngx-translate/core'; import { takeUntilDestroyed } from '@angular/core/rxjs-interop'; import { + cartoLayerTranslationMap, + cartoLayerTypes, defaultLayerTitle, defaultMapLayerSettings, googleMapLayerTranslationMap, @@ -35,6 +37,8 @@ import { MapProvider, mapProviders, mapProviderTranslationMap, + mapProviderHasApiKey, + mapProviderRequiresApiKey, openStreetLayerTypes, openStreetMapLayerTranslationMap, tencentLayerTranslationMap, @@ -71,6 +75,10 @@ export class MapLayerRowComponent implements ControlValueAccessor, OnInit { openStreetMapLayerTranslationMap = openStreetMapLayerTranslationMap; + cartoLayerTypes = cartoLayerTypes; + + cartoLayerTranslationMap = cartoLayerTranslationMap; + googleMapLayerTypes = googleMapLayerTypes; googleMapLayerTranslationMap = googleMapLayerTranslationMap; @@ -110,6 +118,7 @@ export class MapLayerRowComponent implements ControlValueAccessor, OnInit { provider: [null, [Validators.required]], layerType: [null, [Validators.required]], tileUrl: [null, [Validators.required]], + customAttribution: [null, []], apiKey: [null, [Validators.required]], referenceLayer: [null, []] }); @@ -202,12 +211,15 @@ export class MapLayerRowComponent implements ControlValueAccessor, OnInit { const provider: MapProvider = this.layerFormGroup.get('provider').value; if (provider === MapProvider.custom) { this.layerFormGroup.get('tileUrl').enable({emitEvent: false}); + this.layerFormGroup.get('customAttribution').enable({emitEvent: false}); this.layerFormGroup.get('layerType').disable({emitEvent: false}); } else { this.layerFormGroup.get('tileUrl').disable({emitEvent: false}); + this.layerFormGroup.get('customAttribution').disable({emitEvent: false}); this.layerFormGroup.get('layerType').enable({emitEvent: false}); } - if ([MapProvider.google, MapProvider.here].includes(provider)) { + if (mapProviderHasApiKey(provider)) { + this.layerFormGroup.get('apiKey').setValidators(mapProviderRequiresApiKey(provider) ? [Validators.required] : []); this.layerFormGroup.get('apiKey').enable({emitEvent: false}); } else { this.layerFormGroup.get('apiKey').disable({emitEvent: false}); diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/settings/common/map/map-layer-settings-panel.component.html b/ui-ngx/src/app/modules/home/components/widget/lib/settings/common/map/map-layer-settings-panel.component.html index cdf24fd07c..a65dc5bf18 100644 --- a/ui-ngx/src/app/modules/home/components/widget/lib/settings/common/map/map-layer-settings-panel.component.html +++ b/ui-ngx/src/app/modules/home/components/widget/lib/settings/common/map/map-layer-settings-panel.component.html @@ -33,6 +33,14 @@ + + + + {{ cartoLayerTranslationMap.get(layerType) | translate }} + + + @@ -62,12 +70,18 @@
    -
    +
    +
    widgets.maps.layer.provider.custom.attribution
    + + + +
    +
    widgets.maps.layer.credentials.credentials
    widgets.maps.layer.credentials.api-key
    - +
    diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/settings/common/map/map-layer-settings-panel.component.ts b/ui-ngx/src/app/modules/home/components/widget/lib/settings/common/map/map-layer-settings-panel.component.ts index bddca3f360..5e4866df9c 100644 --- a/ui-ngx/src/app/modules/home/components/widget/lib/settings/common/map/map-layer-settings-panel.component.ts +++ b/ui-ngx/src/app/modules/home/components/widget/lib/settings/common/map/map-layer-settings-panel.component.ts @@ -5,6 +5,8 @@ import { TbPopoverComponent } from '@shared/components/popover.component'; import { UntypedFormBuilder, UntypedFormGroup, Validators } from '@angular/forms'; import { takeUntilDestroyed } from '@angular/core/rxjs-interop'; import { + cartoLayerTranslationMap, + cartoLayerTypes, defaultLayerTitle, defaultMapLayerSettings, googleMapLayerTranslationMap, @@ -15,6 +17,8 @@ import { MapProvider, mapProviders, mapProviderTranslationMap, + mapProviderHasApiKey, + mapProviderRequiresApiKey, openStreetLayerTypes, openStreetMapLayerTranslationMap, referenceLayerTypes, referenceLayerTypeTranslationMap, tencentLayerTranslationMap, @@ -42,6 +46,10 @@ export class MapLayerSettingsPanelComponent implements OnInit { openStreetMapLayerTranslationMap = openStreetMapLayerTranslationMap; + cartoLayerTypes = cartoLayerTypes; + + cartoLayerTranslationMap = cartoLayerTranslationMap; + googleMapLayerTypes = googleMapLayerTypes; googleMapLayerTranslationMap = googleMapLayerTranslationMap; @@ -81,6 +89,7 @@ export class MapLayerSettingsPanelComponent implements OnInit { provider: [null, [Validators.required]], layerType: [null, [Validators.required]], tileUrl: [null, [Validators.required]], + customAttribution: [null, []], apiKey: [null, [Validators.required]], referenceLayer: [null, []] } @@ -108,6 +117,10 @@ export class MapLayerSettingsPanelComponent implements OnInit { return this.translate.instant(translationKey); } + hasApiKey(): boolean { + return mapProviderHasApiKey(this.layerFormGroup.get('provider').value); + } + applyLayerSettings() { const layerSettings: MapLayerSettings = this.layerFormGroup.value; this.mapLayerSettingsApplied.emit(layerSettings); @@ -126,12 +139,15 @@ export class MapLayerSettingsPanelComponent implements OnInit { const provider: MapProvider = this.layerFormGroup.get('provider').value; if (provider === MapProvider.custom) { this.layerFormGroup.get('tileUrl').enable({emitEvent: false}); + this.layerFormGroup.get('customAttribution').enable({emitEvent: false}); this.layerFormGroup.get('layerType').disable({emitEvent: false}); } else { this.layerFormGroup.get('tileUrl').disable({emitEvent: false}); + this.layerFormGroup.get('customAttribution').disable({emitEvent: false}); this.layerFormGroup.get('layerType').enable({emitEvent: false}); } - if ([MapProvider.google, MapProvider.here].includes(provider)) { + if (mapProviderHasApiKey(provider)) { + this.layerFormGroup.get('apiKey').setValidators(mapProviderRequiresApiKey(provider) ? [Validators.required] : []); this.layerFormGroup.get('apiKey').enable({emitEvent: false}); } else { this.layerFormGroup.get('apiKey').disable({emitEvent: false}); diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/settings/common/map/map-layers.component.ts b/ui-ngx/src/app/modules/home/components/widget/lib/settings/common/map/map-layers.component.ts index d6ac020c42..a73c9bfbb5 100644 --- a/ui-ngx/src/app/modules/home/components/widget/lib/settings/common/map/map-layers.component.ts +++ b/ui-ngx/src/app/modules/home/components/widget/lib/settings/common/map/map-layers.component.ts @@ -20,7 +20,8 @@ import { MapLayerSettings, mapLayerValid, mapLayerValidator, - MapProvider + MapProvider, + normalizeMapLayerSettings } from '@shared/models/widget/maps/map.models'; @Component({ @@ -93,7 +94,7 @@ export class MapLayersComponent implements ControlValueAccessor, OnInit, Validat } writeValue(value: MapLayerSettings[] | undefined): void { - const layers: MapLayerSettings[] = value || []; + const layers: MapLayerSettings[] = (value || []).map(layer => normalizeMapLayerSettings(layer)); this.layersFormGroup.setControl('layers', this.prepareLayersFormArray(layers), {emitEvent: false}); } diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/settings/map/legacy/here-map-provider-settings.component.html b/ui-ngx/src/app/modules/home/components/widget/lib/settings/map/legacy/here-map-provider-settings.component.html index d95bb0daa3..2131e54bdf 100644 --- a/ui-ngx/src/app/modules/home/components/widget/lib/settings/map/legacy/here-map-provider-settings.component.html +++ b/ui-ngx/src/app/modules/home/components/widget/lib/settings/map/legacy/here-map-provider-settings.component.html @@ -16,25 +16,10 @@
    widgets.maps.credentials - - {{ 'widgets.maps.here-use-new-version-api-3' | translate }} - -
    - - widgets.maps.here-app-id - - - - widgets.maps.here-app-code - - -
    - - - widgets.maps.here-api-key - - - + + widgets.maps.here-api-key + +
    diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/settings/map/legacy/here-map-provider-settings.component.ts b/ui-ngx/src/app/modules/home/components/widget/lib/settings/map/legacy/here-map-provider-settings.component.ts index 823840b624..14d5236473 100644 --- a/ui-ngx/src/app/modules/home/components/widget/lib/settings/map/legacy/here-map-provider-settings.component.ts +++ b/ui-ngx/src/app/modules/home/components/widget/lib/settings/map/legacy/here-map-provider-settings.component.ts @@ -16,11 +16,11 @@ import { Store } from '@ngrx/store'; import { AppState } from '@core/core.state'; import { TranslateService } from '@ngx-translate/core'; import { + defaultHereMapProviderSettings, HereMapProvider, HereMapProviderSettings, hereMapProviderTranslationMap } from '@home/components/widget/lib/maps-legacy/map-models'; -import { isDefinedAndNotNull } from '@core/utils'; import { takeUntilDestroyed } from '@angular/core/rxjs-interop'; @Component({ @@ -67,25 +67,9 @@ export class HereMapProviderSettingsComponent extends PageComponent implements O this.providerSettingsFormGroup = this.fb.group({ mapProviderHere: [null, [Validators.required]], credentials: this.fb.group({ - useV3: [true], - app_id: [null, [Validators.required]], - app_code: [null, [Validators.required]], apiKey: [null, [Validators.required]] }) }); - this.providerSettingsFormGroup.get('credentials.useV3').valueChanges.pipe( - takeUntilDestroyed(this.destroyRef) - ).subscribe(value => { - if (value) { - this.providerSettingsFormGroup.get('credentials.apiKey').enable({emitEvent: false}); - this.providerSettingsFormGroup.get('credentials.app_id').disable({emitEvent: false}); - this.providerSettingsFormGroup.get('credentials.app_code').disable({emitEvent: false}); - } else { - this.providerSettingsFormGroup.get('credentials.apiKey').disable({emitEvent: false}); - this.providerSettingsFormGroup.get('credentials.app_id').enable({emitEvent: false}); - this.providerSettingsFormGroup.get('credentials.app_code').enable({emitEvent: false}); - } - }); this.providerSettingsFormGroup.valueChanges.pipe( takeUntilDestroyed(this.destroyRef) ).subscribe(() => { @@ -106,21 +90,17 @@ export class HereMapProviderSettingsComponent extends PageComponent implements O this.providerSettingsFormGroup.disable({emitEvent: false}); } else { this.providerSettingsFormGroup.enable({emitEvent: false}); - this.providerSettingsFormGroup.get('credentials.useV3').updateValueAndValidity({onlySelf: true}); } } writeValue(value: HereMapProviderSettings): void { - if (!isDefinedAndNotNull(value.credentials.useV3)) { - if (isDefinedAndNotNull(value.credentials.app_id) && isDefinedAndNotNull(value.credentials.app_code)) { - value.credentials.useV3 = false; - } - } this.modelValue = value; - this.providerSettingsFormGroup.patchValue( - value, {emitEvent: false} - ); - this.providerSettingsFormGroup.get('credentials.useV3').updateValueAndValidity({onlySelf: true}); + this.providerSettingsFormGroup.patchValue({ + mapProviderHere: value?.mapProviderHere, + credentials: { + apiKey: value?.credentials?.apiKey || defaultHereMapProviderSettings.credentials.apiKey + } + }, {emitEvent: false}); } public validate(c: FormControl) { diff --git a/ui-ngx/src/app/shared/models/widget/maps/map.models.ts b/ui-ngx/src/app/shared/models/widget/maps/map.models.ts index 3271c3dc36..a3dbcf63bc 100644 --- a/ui-ngx/src/app/shared/models/widget/maps/map.models.ts +++ b/ui-ngx/src/app/shared/models/widget/maps/map.models.ts @@ -832,6 +832,7 @@ export const defaultMapActionButtonSettings: MapActionButtonSettings = { export enum MapProvider { openstreet = 'openstreet', + carto = 'carto', google = 'google', here = 'here', tencent = 'tencent', @@ -843,6 +844,7 @@ export const mapProviders = Object.keys(MapProvider) as MapProvider[]; export const mapProviderTranslationMap = new Map( [ [MapProvider.openstreet, 'widgets.maps.layer.provider.openstreet.title'], + [MapProvider.carto, 'widgets.maps.layer.provider.carto.title'], [MapProvider.google, 'widgets.maps.layer.provider.google.title'], [MapProvider.here, 'widgets.maps.layer.provider.here.title'], [MapProvider.tencent, 'widgets.maps.layer.provider.tencent.title'], @@ -880,6 +882,9 @@ export const mapLayerValid = (layer: MapLayerSettings): boolean => { case MapProvider.openstreet: const openStreetLayer = layer as OpenStreetMapLayerSettings; return !!openStreetLayer.layerType; + case MapProvider.carto: + const cartoLayer = layer as CartoMapLayerSettings; + return !!cartoLayer.layerType; case MapProvider.google: const googleLayer = layer as GoogleMapLayerSettings; return !!googleLayer.layerType; @@ -913,6 +918,9 @@ export const defaultLayerTitle = (layer: MapLayerSettings): string => { case MapProvider.openstreet: const openStreetLayer = layer as OpenStreetMapLayerSettings; return openStreetMapLayerTranslationMap.get(openStreetLayer.layerType); + case MapProvider.carto: + const cartoLayer = layer as CartoMapLayerSettings; + return cartoLayerTranslationMap.get(cartoLayer.layerType); case MapProvider.google: const googleLayer = layer as GoogleMapLayerSettings; return googleMapLayerTranslationMap.get(googleLayer.layerType); @@ -932,9 +940,7 @@ export enum OpenStreetLayerType { openStreetHot = 'OpenStreetMap.HOT', esriWorldStreetMap = 'Esri.WorldStreetMap', esriWorldTopoMap = 'Esri.WorldTopoMap', - esriWorldImagery = 'Esri.WorldImagery', - cartoDbPositron = 'CartoDB.Positron', - cartoDbDarkMatter = 'CartoDB.DarkMatter' + esriWorldImagery = 'Esri.WorldImagery' } export const openStreetLayerTypes = Object.values(OpenStreetLayerType) as OpenStreetLayerType[]; @@ -945,9 +951,7 @@ export const openStreetMapLayerTranslationMap = new Map( + [ + [CartoLayerType.cartoPositron, 'widgets.maps.layer.provider.carto.positron'], + [CartoLayerType.cartoDarkMatter, 'widgets.maps.layer.provider.carto.dark-matter'] + ] +); + +export interface CartoMapLayerSettings extends MapLayerSettings { + provider: MapProvider.carto; + layerType: CartoLayerType; + apiKey?: string; +} + +export const defaultCartoMapLayerSettings: CartoMapLayerSettings = { + provider: MapProvider.carto, + layerType: CartoLayerType.cartoPositron, + apiKey: null +} + export enum GoogleLayerType { roadmap = 'roadmap', satellite = 'satellite', @@ -1021,6 +1051,16 @@ export const defaultHereMapLayerSettings: HereMapLayerSettings = { apiKey: 'kVXykxAfZ6LS4EbCTO02soFVfjA7HoBzNVVH9u7nzoE' } +const hereV3Variants: {[v2Variant: string]: string} = { + normalDay: 'exploreDay', + normalNight: 'exploreNight', + hybridDay: 'exploreSatelliteDay', + terrainDay: 'topoDay' +}; + +export const hereV3Provider = (layerType: string): string => + `HERE.${hereV3Variants[layerType?.split('.')[1]] || hereV3Variants.normalDay}`; + export enum TencentLayerType { tencentNormal = 'Tencent.Normal', tencentSatellite = 'Tencent.Satellite', @@ -1050,6 +1090,7 @@ export const defaultTencentMapLayerSettings: TencentMapLayerSettings = { export interface CustomMapLayerSettings extends MapLayerSettings { provider: MapProvider.custom; tileUrl: string; + customAttribution?: string; } export const defaultCustomMapLayerSettings: CustomMapLayerSettings = { @@ -1057,10 +1098,29 @@ export const defaultCustomMapLayerSettings: CustomMapLayerSettings = { tileUrl: 'https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png' } +export const mapProviderHasApiKey = (provider: MapProvider): boolean => + [MapProvider.carto, MapProvider.google, MapProvider.here].includes(provider); + +export const mapProviderRequiresApiKey = (provider: MapProvider): boolean => + [MapProvider.google, MapProvider.here].includes(provider); + +const legacyOpenStreetCartoLayerTypes = new Set(cartoLayerTypes); + +// CARTO layers used to be stored under the OpenStreetMap provider, keep reading them as CARTO layers +export const normalizeMapLayerSettings = (layer: MapLayerSettings): MapLayerSettings => { + if (layer?.provider === MapProvider.openstreet && + legacyOpenStreetCartoLayerTypes.has((layer as OpenStreetMapLayerSettings).layerType)) { + return {...layer, provider: MapProvider.carto}; + } + return layer; +}; + export const defaultMapLayerSettings = (provider: MapProvider): MapLayerSettings => { switch (provider) { case MapProvider.openstreet: return defaultOpenStreetMapLayerSettings; + case MapProvider.carto: + return defaultCartoMapLayerSettings; case MapProvider.google: return defaultGoogleMapLayerSettings; case MapProvider.here: diff --git a/ui-ngx/src/assets/locale/locale.constant-en_US.json b/ui-ngx/src/assets/locale/locale.constant-en_US.json index b5f51fd6d4..b3aa95d6ec 100644 --- a/ui-ngx/src/assets/locale/locale.constant-en_US.json +++ b/ui-ngx/src/assets/locale/locale.constant-en_US.json @@ -8563,9 +8563,12 @@ "hot": "HOT", "esri-street": "WorldStreetMap", "esri-topo": "WorldTopoMap", - "esri-imagery": "WorldImagery", - "cartodb-positron": "Positron", - "cartodb-dark-matter": "DarkMatter" + "esri-imagery": "WorldImagery" + }, + "carto": { + "title": "CARTO", + "positron": "Positron", + "dark-matter": "DarkMatter" }, "google": { "title": "Google", @@ -8589,7 +8592,9 @@ }, "custom": { "title": "Custom", - "tile-url": "Tile URL" + "tile-url": "Tile URL", + "attribution": "Copyright text", + "attribution-hint": "Displayed at the bottom of the map. Required by most tile providers." } }, "credentials": { @@ -8866,10 +8871,7 @@ "here-map-hybrid-day": "HERE.hybridDay", "here-map-terrain-day": "HERE.terrainDay", "credentials": "Credentials", - "here-app-id": "HERE app id", - "here-app-code": "HERE app code", "here-api-key": "HERE API key", - "here-use-new-version-api-3": "Use API version 3", "tencent-maps-api-key": "Tencent Maps API Key", "tencent-map-type-roadmap": "Roadmap", "tencent-map-type-satelite": "Satellite", diff --git a/ui-ngx/yarn.lock b/ui-ngx/yarn.lock index 7d184f78dc..9b6453cd01 100644 --- a/ui-ngx/yarn.lock +++ b/ui-ngx/yarn.lock @@ -7576,10 +7576,10 @@ leaflet-polylinedecorator@1.6.0: dependencies: leaflet-rotatedmarker "^0.2.0" -leaflet-providers@2.0.0: - version "2.0.0" - resolved "https://registry.yarnpkg.com/leaflet-providers/-/leaflet-providers-2.0.0.tgz#dfdab9ca2dccc57c79e1462bc3dd20f78910afcb" - integrity sha512-CWwKEnHd66Qsx0m4o5q5ZOa60s00B91pMxnlr4Y22msubfs7dhbZhdMIz8bvZQkrZqi67ppI1fsZRS6vtrLcOA== +leaflet-providers@4.0.0: + version "4.0.0" + resolved "https://registry.yarnpkg.com/leaflet-providers/-/leaflet-providers-4.0.0.tgz#a98c5631a671c366739d8658e40be1d02e2c57cb" + integrity sha512-4m3Q4t0e+cHVNIPzlkW9HFWEgplImFRv8cnUFJYOfFoS6p2KosAfmh2Do6qk4HMdqutqbHMpv3F7sn/CUSw6oQ== leaflet-rotatedmarker@^0.2.0: version "0.2.0" From 84c1cfb26aca80d024738e4a8feaa718d7f05008 Mon Sep 17 00:00:00 2001 From: Viacheslav Klimov Date: Fri, 25 Sep 2026 09:26:37 +0300 Subject: [PATCH 078/159] Bump jackson-bom from 2.21.5 to 2.21.6 to fix CVE-2026-68497 --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index a1136afd0f..37e3afe09f 100755 --- a/pom.xml +++ b/pom.xml @@ -73,7 +73,7 @@ 10.1.59 5.4.3 1.5.38 - 2.21.5 + 2.21.6 42.7.12 5.33.1 5.6.4 From 6e3818f83374ed17728c70cbdf3faba15603ea74 Mon Sep 17 00:00:00 2001 From: Viacheslav Klimov Date: Fri, 25 Sep 2026 09:26:37 +0300 Subject: [PATCH 079/159] Bump amqp-client from 5.33.1 to 5.34.0 to fix CVE-2026-75516 --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index 37e3afe09f..157cd042ea 100755 --- a/pom.xml +++ b/pom.xml @@ -75,7 +75,7 @@ 1.5.38 2.21.6 42.7.12 - 5.33.1 + 5.34.0 5.6.4 2.4.0-b180830.0359 0.12.5 From b16701288fde7d67bcd69c6107d803d6007735b2 Mon Sep 17 00:00:00 2001 From: Viacheslav Klimov Date: Fri, 25 Sep 2026 09:26:37 +0300 Subject: [PATCH 080/159] Bump wire-schema from 6.3.0 to 6.4.5 to fix CVE-2026-63126 --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index 157cd042ea..76b2c8ae4d 100755 --- a/pom.xml +++ b/pom.xml @@ -142,7 +142,7 @@ 1.11.0 4.4 1.0.4TB - 6.3.0 + 6.4.5 10.1.3 3.7.4 4.0.2 From ebebc194cbb8b54728322b1f9a64e371809370e3 Mon Sep 17 00:00:00 2001 From: Viacheslav Klimov Date: Fri, 25 Sep 2026 10:28:38 +0300 Subject: [PATCH 081/159] Bump zstd-jni from 1.5.6-4 to 1.5.7-14 to fix CVE-2026-87795, CVE-2026-87823, and 5 others --- pom.xml | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/pom.xml b/pom.xml index 76b2c8ae4d..db90bce5f5 100755 --- a/pom.xml +++ b/pom.xml @@ -77,6 +77,7 @@ 42.7.12 5.34.0 5.6.4 + 1.5.7-14 2.4.0-b180830.0359 0.12.5 0.10 @@ -1114,6 +1115,13 @@ ${httpclient5.version} + + + com.github.luben + zstd-jni + ${zstd-jni.version} + + org.springframework.boot spring-boot-dependencies From 0bc466a165c755fa8ce221665df1b1a8f28164ec Mon Sep 17 00:00:00 2001 From: Vladyslav_Prykhodko Date: Fri, 25 Sep 2026 10:45:58 +0300 Subject: [PATCH 082/159] Bump npm dependencies to fix CVE-2026-90711, CVE-2026-17495, CVE-2026-87776, and CVE-2026-84375 - proxy-addr 2.0.7 -> 2.0.8 (CVE-2026-90711, GHSA-jqcg-44mw-7w3h) - moment 2.30.1 -> 2.31.0 (CVE-2026-17495, GHSA-4p3w-j4w9-5jqw) - compression 1.8.1 -> 1.8.2 (CVE-2026-87776, GHSA-vc2v-76pw-4v95) - js-yaml 4.3.1 -> 4.3.2 in ui-ngx (CVE-2026-84375, GHSA-2883-xcg3-v3hh) --- msa/js-executor/yarn.lock | 12 ++++++------ msa/web-ui/package.json | 2 +- msa/web-ui/yarn.lock | 26 ++++++++++++++++---------- ui-ngx/package.json | 2 +- ui-ngx/yarn.lock | 27 ++++++++++++++------------- 5 files changed, 38 insertions(+), 31 deletions(-) diff --git a/msa/js-executor/yarn.lock b/msa/js-executor/yarn.lock index e4f6409a3d..bb1095b947 100644 --- a/msa/js-executor/yarn.lock +++ b/msa/js-executor/yarn.lock @@ -1170,9 +1170,9 @@ mkdirp-classic@^0.5.2, mkdirp-classic@^0.5.3: integrity sha512-gKLcREMhtuZRwRAfqP3RFW+TK4JqApVBtOIftVgjuABpAtpxhPGaDcfvbhNvD0B8iD1oUr/txX35NjcaY6Ns/A== moment@^2.29.1: - version "2.30.1" - resolved "https://registry.yarnpkg.com/moment/-/moment-2.30.1.tgz#f8c91c07b7a786e30c59926df530b4eac96974ae" - integrity sha512-uEmtNhbDOrWPFS+hdjFCBfy9f2YoyzRpwcl+DqpC6taX21FzsTLQVbMV/W7PzNSX6x/bhC1zA3c2UQ5NzH6how== + version "2.31.0" + resolved "https://registry.yarnpkg.com/moment/-/moment-2.31.0.tgz#6e19184e8005a9dfc61c9351263d4d6ea2ace7aa" + integrity sha512-0acOTfMiWOheYS4eoWb80yYMb/JLvVv9SHbs2PehaDzfUG0Bw855SKyk0IKTnPGa5+U2bmi3W68l1+sGLX/pvw== ms@^2.1.1, ms@^2.1.3: version "2.1.3" @@ -1332,9 +1332,9 @@ progress@^2.0.3: integrity sha512-7PiHtLll5LdnKIMw100I+8xJXR5gW2QwWYkT6iJva0bXitZKa/XMrSbdmg3r2Xnaidz9Qumd0VPaMrZlF9V9sA== proxy-addr@^2.0.7: - version "2.0.7" - resolved "https://registry.yarnpkg.com/proxy-addr/-/proxy-addr-2.0.7.tgz#f19fe69ceab311eeb94b42e70e8c2070f9ba1025" - integrity sha512-llQsMLSUDUPT44jdrU/O37qlnifitDP+ZwrmmZcoSKyLKvtZxpyV0n2/bD/N4tBAAZ/gJEdZU7KMraoK1+XYAg== + version "2.0.8" + resolved "https://registry.yarnpkg.com/proxy-addr/-/proxy-addr-2.0.8.tgz#624e760fd8ab06b1b8320c2f8506d4422cf8e932" + integrity sha512-5nnx0yGyVUcY6t9RnWcARWtwT9F1D8O9rt08htPvnd49W1IgZtmLkhu9WfMzQj1cFxjHIO6connUNVW5k7AVyQ== dependencies: forwarded "0.2.0" ipaddr.js "1.9.1" diff --git a/msa/web-ui/package.json b/msa/web-ui/package.json index e0099bbdc5..f557b40769 100644 --- a/msa/web-ui/package.json +++ b/msa/web-ui/package.json @@ -13,7 +13,7 @@ "build": "tsc" }, "dependencies": { - "compression": "^1.8.1", + "compression": "^1.8.2", "config": "^3.3.12", "connect-history-api-fallback": "1.6.0", "express": "^5.1.0", diff --git a/msa/web-ui/yarn.lock b/msa/web-ui/yarn.lock index 3e96bc2e85..ca2d727bf8 100644 --- a/msa/web-ui/yarn.lock +++ b/msa/web-ui/yarn.lock @@ -511,14 +511,15 @@ compressible@~2.0.18: dependencies: mime-db ">= 1.43.0 < 2" -compression@^1.8.1: - version "1.8.1" - resolved "https://registry.yarnpkg.com/compression/-/compression-1.8.1.tgz#4a45d909ac16509195a9a28bd91094889c180d79" - integrity sha512-9mAqGPHLakhCLeNyxPkK4xVo746zQ/czLH1Ky+vkitMnWfWZps8r0qXuwhwizagCRttsL4lfG4pIOvaWLpAP0w== +compression@^1.8.2: + version "1.8.2" + resolved "https://registry.yarnpkg.com/compression/-/compression-1.8.2.tgz#781397127ae2da00c0c5f7c76bda5b2a9b32a49f" + integrity sha512-o8vI5RE5A6EVVOd9o41jKp41aJom+QTEO/Bx8MYNjexMo/Bv2WOjUfZr+aL0WnYSgymUy6zeguqLTsIhV0gMvQ== dependencies: bytes "3.1.2" compressible "~2.0.18" debug "2.6.9" + destroy "1.2.0" negotiator "~0.6.4" on-headers "~1.1.0" safe-buffer "5.2.1" @@ -604,6 +605,11 @@ depd@2.0.0, depd@^2.0.0: resolved "https://registry.yarnpkg.com/depd/-/depd-2.0.0.tgz#b696163cc757560d09cf22cc8fad1571b79e76df" integrity sha512-g7nH6P6dyDioJogAAGprGpCtVImJhpPk/roCzdb3fIh61/s/nPsfR6onyMwkCAR/OlC3yBC0lESvUoQEAssIrw== +destroy@1.2.0: + version "1.2.0" + resolved "https://registry.yarnpkg.com/destroy/-/destroy-1.2.0.tgz#4803735509ad8be552934c67df614f94e66fa015" + integrity sha512-2sJGJTaXIIaR1w4iJSNoN0hnMY7Gpc/n8D4qSCJw8QqFWXf7cuAgnEHxBpweaVcPevC2l3KpjYCx3NypQQgaJg== + detect-libc@^2.0.0: version "2.0.4" resolved "https://registry.yarnpkg.com/detect-libc/-/detect-libc-2.0.4.tgz#f04715b8ba815e53b4d8109655b6508a6865a7e8" @@ -1127,9 +1133,9 @@ mkdirp-classic@^0.5.2, mkdirp-classic@^0.5.3: integrity sha512-gKLcREMhtuZRwRAfqP3RFW+TK4JqApVBtOIftVgjuABpAtpxhPGaDcfvbhNvD0B8iD1oUr/txX35NjcaY6Ns/A== moment@^2.29.1: - version "2.30.1" - resolved "https://registry.yarnpkg.com/moment/-/moment-2.30.1.tgz#f8c91c07b7a786e30c59926df530b4eac96974ae" - integrity sha512-uEmtNhbDOrWPFS+hdjFCBfy9f2YoyzRpwcl+DqpC6taX21FzsTLQVbMV/W7PzNSX6x/bhC1zA3c2UQ5NzH6how== + version "2.31.0" + resolved "https://registry.yarnpkg.com/moment/-/moment-2.31.0.tgz#6e19184e8005a9dfc61c9351263d4d6ea2ace7aa" + integrity sha512-0acOTfMiWOheYS4eoWb80yYMb/JLvVv9SHbs2PehaDzfUG0Bw855SKyk0IKTnPGa5+U2bmi3W68l1+sGLX/pvw== ms@2.0.0: version "2.0.0" @@ -1304,9 +1310,9 @@ progress@^2.0.3: integrity sha512-7PiHtLll5LdnKIMw100I+8xJXR5gW2QwWYkT6iJva0bXitZKa/XMrSbdmg3r2Xnaidz9Qumd0VPaMrZlF9V9sA== proxy-addr@^2.0.7: - version "2.0.7" - resolved "https://registry.yarnpkg.com/proxy-addr/-/proxy-addr-2.0.7.tgz#f19fe69ceab311eeb94b42e70e8c2070f9ba1025" - integrity sha512-llQsMLSUDUPT44jdrU/O37qlnifitDP+ZwrmmZcoSKyLKvtZxpyV0n2/bD/N4tBAAZ/gJEdZU7KMraoK1+XYAg== + version "2.0.8" + resolved "https://registry.yarnpkg.com/proxy-addr/-/proxy-addr-2.0.8.tgz#624e760fd8ab06b1b8320c2f8506d4422cf8e932" + integrity sha512-5nnx0yGyVUcY6t9RnWcARWtwT9F1D8O9rt08htPvnd49W1IgZtmLkhu9WfMzQj1cFxjHIO6connUNVW5k7AVyQ== dependencies: forwarded "0.2.0" ipaddr.js "1.9.1" diff --git a/ui-ngx/package.json b/ui-ngx/package.json index c410d5bed4..ab946678a2 100644 --- a/ui-ngx/package.json +++ b/ui-ngx/package.json @@ -67,7 +67,7 @@ "libphonenumber-js": "^1.12.35", "maplibre-gl": "5.2.0", "marked": "~16.4.2", - "moment": "^2.30.1", + "moment": "^2.31.0", "moment-timezone": "^0.6.0", "ngx-clipboard": "^16.0.0", "ngx-daterangepicker-material": "^6.0.4", diff --git a/ui-ngx/yarn.lock b/ui-ngx/yarn.lock index 9b6453cd01..a70a3e66fb 100644 --- a/ui-ngx/yarn.lock +++ b/ui-ngx/yarn.lock @@ -4861,13 +4861,14 @@ compressible@~2.0.18: mime-db ">= 1.43.0 < 2" compression@^1.8.1: - version "1.8.1" - resolved "https://registry.yarnpkg.com/compression/-/compression-1.8.1.tgz#4a45d909ac16509195a9a28bd91094889c180d79" - integrity sha512-9mAqGPHLakhCLeNyxPkK4xVo746zQ/czLH1Ky+vkitMnWfWZps8r0qXuwhwizagCRttsL4lfG4pIOvaWLpAP0w== + version "1.8.2" + resolved "https://registry.yarnpkg.com/compression/-/compression-1.8.2.tgz#781397127ae2da00c0c5f7c76bda5b2a9b32a49f" + integrity sha512-o8vI5RE5A6EVVOd9o41jKp41aJom+QTEO/Bx8MYNjexMo/Bv2WOjUfZr+aL0WnYSgymUy6zeguqLTsIhV0gMvQ== dependencies: bytes "3.1.2" compressible "~2.0.18" debug "2.6.9" + destroy "1.2.0" negotiator "~0.6.4" on-headers "~1.1.0" safe-buffer "5.2.1" @@ -7363,9 +7364,9 @@ js-tokens@^4.0.0: integrity sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ== js-yaml@^4.1.0, js-yaml@^4.3.0: - version "4.3.1" - resolved "https://registry.yarnpkg.com/js-yaml/-/js-yaml-4.3.1.tgz#01216c001d67f48e2cd560d708c7af21090a3848" - integrity sha512-CY6crGq313MX8GkwvB7tzgp99vjQxY1++5y10/BKN/GUfHqWaOGQMNZkBvqSzsZKWk/ijwHlWzzkLulsGHhjWQ== + version "4.3.2" + resolved "https://registry.yarnpkg.com/js-yaml/-/js-yaml-4.3.2.tgz#8e44fb14a2643c59726bb15787b5f1512cb3d3fb" + integrity sha512-SFNOvSJ+Dgf/9An904Yx+CgSlIPCkIpao4qo51lpee25TIRejdH3rhR4EZMGoNx3/TP3O+wzWuiTFl4sqbltzA== dependencies: argparse "^2.0.1" @@ -8104,10 +8105,10 @@ moment-timezone@^0.6.0: dependencies: moment "^2.29.4" -moment@^2.29.4, moment@^2.30.1: - version "2.30.1" - resolved "https://registry.yarnpkg.com/moment/-/moment-2.30.1.tgz#f8c91c07b7a786e30c59926df530b4eac96974ae" - integrity sha512-uEmtNhbDOrWPFS+hdjFCBfy9f2YoyzRpwcl+DqpC6taX21FzsTLQVbMV/W7PzNSX6x/bhC1zA3c2UQ5NzH6how== +moment@^2.29.4, moment@^2.31.0: + version "2.31.0" + resolved "https://registry.yarnpkg.com/moment/-/moment-2.31.0.tgz#6e19184e8005a9dfc61c9351263d4d6ea2ace7aa" + integrity sha512-0acOTfMiWOheYS4eoWb80yYMb/JLvVv9SHbs2PehaDzfUG0Bw855SKyk0IKTnPGa5+U2bmi3W68l1+sGLX/pvw== moo@^0.5.1: version "0.5.2" @@ -9110,9 +9111,9 @@ protocol-buffers-schema@^3.3.1: integrity sha512-TdDRD+/QNdrCGCE7v8340QyuXd4kIWIgapsE2+n/SaGiSSbomYl4TjHlvIoCWRpE7wFt02EpB35VVA2ImcBVqw== proxy-addr@^2.0.7, proxy-addr@~2.0.7: - version "2.0.7" - resolved "https://registry.yarnpkg.com/proxy-addr/-/proxy-addr-2.0.7.tgz#f19fe69ceab311eeb94b42e70e8c2070f9ba1025" - integrity sha512-llQsMLSUDUPT44jdrU/O37qlnifitDP+ZwrmmZcoSKyLKvtZxpyV0n2/bD/N4tBAAZ/gJEdZU7KMraoK1+XYAg== + version "2.0.8" + resolved "https://registry.yarnpkg.com/proxy-addr/-/proxy-addr-2.0.8.tgz#624e760fd8ab06b1b8320c2f8506d4422cf8e932" + integrity sha512-5nnx0yGyVUcY6t9RnWcARWtwT9F1D8O9rt08htPvnd49W1IgZtmLkhu9WfMzQj1cFxjHIO6connUNVW5k7AVyQ== dependencies: forwarded "0.2.0" ipaddr.js "1.9.1" From a0684dc65f3ea7fce9fa807c6fa371659a232ce6 Mon Sep 17 00:00:00 2001 From: Vladyslav_Prykhodko Date: Fri, 25 Sep 2026 10:45:58 +0300 Subject: [PATCH 083/159] Bump maplibre-gl from 5.2.0 to 6.11.2 to fix CVE-2026-85061 Fixes the XSS sanitizer bypass in DOM.sanitize() (GHSA-jrc7-96c5-q579, maplibre-gl <= 6.4.0). - v6 removed the internal map.transform: sync the GL map with Leaflet through the public jumpTo() and detect resizes from the container size - v6 is ESM-only and the worker must be registered via setWorkerUrl(): copy maplibre-gl-worker.mjs and its maplibre-gl-shared.mjs dependency to assets/maplibre-gl/ --- ui-ngx/angular.json | 10 + ui-ngx/package.json | 2 +- .../widget/lib/maps/leaflet/leaflet-tb.ts | 19 +- ui-ngx/yarn.lock | 262 +++++++----------- 4 files changed, 113 insertions(+), 180 deletions(-) diff --git a/ui-ngx/angular.json b/ui-ngx/angular.json index 08ffdd7b9a..49af337a74 100644 --- a/ui-ngx/angular.json +++ b/ui-ngx/angular.json @@ -77,6 +77,16 @@ "input": "node_modules/hugerte", "output": "/assets/hugerte/" }, + { + "glob": "maplibre-gl-worker.mjs", + "input": "node_modules/maplibre-gl/dist/", + "output": "/assets/maplibre-gl/" + }, + { + "glob": "maplibre-gl-shared.mjs", + "input": "node_modules/maplibre-gl/dist/", + "output": "/assets/maplibre-gl/" + }, { "glob": "marker-icon-2x.png", "input": "node_modules/leaflet/dist/images/", diff --git a/ui-ngx/package.json b/ui-ngx/package.json index ab946678a2..f72456f0a3 100644 --- a/ui-ngx/package.json +++ b/ui-ngx/package.json @@ -65,7 +65,7 @@ "leaflet.gridlayer.googlemutant": "0.15.0", "leaflet.markercluster": "1.5.3", "libphonenumber-js": "^1.12.35", - "maplibre-gl": "5.2.0", + "maplibre-gl": "6.11.2", "marked": "~16.4.2", "moment": "^2.31.0", "moment-timezone": "^0.6.0", diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/maps/leaflet/leaflet-tb.ts b/ui-ngx/src/app/modules/home/components/widget/lib/maps/leaflet/leaflet-tb.ts index 9ad91048d7..d092a0078f 100644 --- a/ui-ngx/src/app/modules/home/components/widget/lib/maps/leaflet/leaflet-tb.ts +++ b/ui-ngx/src/app/modules/home/components/widget/lib/maps/leaflet/leaflet-tb.ts @@ -3,7 +3,7 @@ import L, { TB } from 'leaflet'; import { guid, isDefinedAndNotNull, isNotEmptyStr } from '@core/utils'; import 'leaflet-providers'; -import { Map as MapLibreGLMap, LngLat as MapLibreGLLngLat } from 'maplibre-gl'; +import { Map as MapLibreGLMap, setWorkerUrl } from 'maplibre-gl'; import '@geoman-io/leaflet-geoman-free'; import 'leaflet.markercluster'; import { MatIconRegistry } from '@angular/material/icon'; @@ -1070,6 +1070,9 @@ const chinaProvider = (type: string, options?: L.TileLayerOptions): L.TB.TileLay return new ChinaProvider(type, options); } +// The worker is copied to assets by angular.json, bundlers cannot resolve it from import.meta.url +setWorkerUrl(new URL('assets/maplibre-gl/maplibre-gl-worker.mjs', document.baseURI).href); + class MapLibreGLLayer extends L.Layer implements TB.MapLibreGL.MapLibreGLLayer { options: TB.MapLibreGL.LeafletMapLibreGLMapOptions; @@ -1246,23 +1249,19 @@ class MapLibreGLLayer extends L.Layer implements TB.MapLibreGL.MapLibreGLLayer { this._transformGL(gl); - if (gl.transform.width !== size.x || gl.transform.height !== size.y) { + if (container.clientWidth !== size.x || container.clientHeight !== size.y) { container.style.width = size.x + 'px'; container.style.height = size.y + 'px'; gl.resize(); - } else { - gl._update(); } } private _transformGL(gl: MapLibreGLMap) { const center = this._map.getCenter(); - const tr = gl._getTransformForUpdate(); - if (!tr) { return; } - tr.setCenter(MapLibreGLLngLat.convert([center.lng, center.lat])); - tr.setZoom(this._map.getZoom() - 1); - gl.transform.apply(tr); - gl._fireMoveEvents(); + gl.jumpTo({ + center: [center.lng, center.lat], + zoom: this._map.getZoom() - 1 + }); } private _pinchZoom() { diff --git a/ui-ngx/yarn.lock b/ui-ngx/yarn.lock index a70a3e66fb..fdb5a6da01 100644 --- a/ui-ngx/yarn.lock +++ b/ui-ngx/yarn.lock @@ -2115,59 +2115,70 @@ resolved "https://registry.yarnpkg.com/@lmdb/lmdb-win32-x64/-/lmdb-win32-x64-3.4.2.tgz#99caf114bb74d39c9e1baca99b907353ad8bf461" integrity sha512-IY+r3bxKW6Q6sIPiMC0L533DEfRJSXibjSI3Ft/w9Q8KQBNqEIvUFXt+09wV8S5BRk0a8uSF19YWxuRwEfI90g== -"@mapbox/geojson-rewind@^0.5.2": - version "0.5.2" - resolved "https://registry.yarnpkg.com/@mapbox/geojson-rewind/-/geojson-rewind-0.5.2.tgz#591a5d71a9cd1da1a0bf3420b3bea31b0fc7946a" - integrity sha512-tJaT+RbYGJYStt7wI3cq4Nl4SXxG8W7JDG5DMJu97V25RnbNg3QtQtf+KD+VLjNpWKYsRvXDNmNrBgEETr1ifA== - dependencies: - get-stream "^6.0.1" - minimist "^1.2.6" - -"@mapbox/jsonlint-lines-primitives@^2.0.2", "@mapbox/jsonlint-lines-primitives@~2.0.2": - version "2.0.2" - resolved "https://registry.yarnpkg.com/@mapbox/jsonlint-lines-primitives/-/jsonlint-lines-primitives-2.0.2.tgz#ce56e539f83552b58d10d672ea4d6fc9adc7b234" - integrity sha512-rY0o9A5ECsTQRVhv7tL/OyDpGAoUB4tTvLiW1DSzQGq4bvTPhNw1VpSNjDJc5GFZ2XuyOtSWSVN05qOtcD71qQ== +"@mapbox/jsonlint-lines-primitives@^2.0.3": + version "2.0.3" + resolved "https://registry.yarnpkg.com/@mapbox/jsonlint-lines-primitives/-/jsonlint-lines-primitives-2.0.3.tgz#7d7b0b971fbaf6d60953272db4df03020d3fb004" + integrity sha512-0SElaV0uMxEnxzBhhX9WTuPyUeMsAN/SS0i16tjuba4/mio63MG9khjC1a0JAiPGXAwvwm4UfHJURCN7nyudQg== -"@mapbox/point-geometry@0.1.0", "@mapbox/point-geometry@^0.1.0", "@mapbox/point-geometry@~0.1.0": - version "0.1.0" - resolved "https://registry.yarnpkg.com/@mapbox/point-geometry/-/point-geometry-0.1.0.tgz#8a83f9335c7860effa2eeeca254332aa0aeed8f2" - integrity sha512-6j56HdLTwWGO0fJPlrZtdU/B13q8Uwmo18Ck2GnGgN9PCFyKTZ3UbXeEdRFh18i9XQ92eH2VdtpJHpBD3aripQ== +"@mapbox/point-geometry@^1.1.0", "@mapbox/point-geometry@~1.1.0": + version "1.1.0" + resolved "https://registry.yarnpkg.com/@mapbox/point-geometry/-/point-geometry-1.1.0.tgz#3328fb54b3a1273bc619bf0a6baad8de37181749" + integrity sha512-YGcBz1cg4ATXDCM/71L9xveh4dynfGmcLDqufR+nQQy3fKwsAZsWd/x4621/6uJaeB9mwOHE6hPeDgXz9uViUQ== -"@mapbox/tiny-sdf@^2.0.6": - version "2.0.7" - resolved "https://registry.yarnpkg.com/@mapbox/tiny-sdf/-/tiny-sdf-2.0.7.tgz#0d67d65a43195003b282764f2297c619736bbc6e" - integrity sha512-25gQLQMcpivjOSA40g3gO6qgiFPDpWRoMfd+G/GoppPIeP6JDaMMkMrEJnMZhKyyS6iKwVt5YKu02vCUyJM3Ug== +"@mapbox/tiny-sdf@^2.2.0": + version "2.2.0" + resolved "https://registry.yarnpkg.com/@mapbox/tiny-sdf/-/tiny-sdf-2.2.0.tgz#95dae0dc371b8c55c53d70f3e25d56823427f4c8" + integrity sha512-LVL4wgI9YAum5V+LNVQO6QgFBPw7/MIIY4XJPNsPDMrjEwcE+JfKk1LuIl8GnF197ejVdC9QdPaxrx5gfgdGXg== -"@mapbox/unitbezier@^0.0.1": - version "0.0.1" - resolved "https://registry.yarnpkg.com/@mapbox/unitbezier/-/unitbezier-0.0.1.tgz#d32deb66c7177e9e9dfc3bbd697083e2e657ff01" - integrity sha512-nMkuDXFv60aBr9soUG5q+GvZYL+2KZHVvsqFCzqnkGEf46U2fvmytHaEVc1/YZbiLn8X+eR3QzX1+dwDO1lxlw== +"@mapbox/unitbezier@^1.0.0": + version "1.0.0" + resolved "https://registry.yarnpkg.com/@mapbox/unitbezier/-/unitbezier-1.0.0.tgz#54319aff6c467bb1b909e04895c08cdb966bfbff" + integrity sha512-fqd515fjBmANKGGsQ286E2Wvj/XvDFpGzwJxq4CI6jMQue6Oy04uCKp+JWKF00xRTmk6cEu1jPJ9p3xqH8YWqQ== -"@mapbox/vector-tile@^1.3.1": - version "1.3.1" - resolved "https://registry.yarnpkg.com/@mapbox/vector-tile/-/vector-tile-1.3.1.tgz#d3a74c90402d06e89ec66de49ec817ff53409666" - integrity sha512-MCEddb8u44/xfQ3oD+Srl/tNcQoqTw3goGk2oLsrFxOTc3dUp+kAnby3PvAeeBYSMSjSPD1nd1AJA6W49WnoUw== +"@mapbox/vector-tile@^3.0.0": + version "3.0.0" + resolved "https://registry.yarnpkg.com/@mapbox/vector-tile/-/vector-tile-3.0.0.tgz#71a75acb5ee20c20adca5c4e1ffb5ef95a56e351" + integrity sha512-Qf10S1uIHMk20ri/IVBnpS+esUEkVaR5Hftmz88jTInrpmWgPGJfPe3LVjjlE77trLx8tH6qjTG7uWH9hIq/0Q== dependencies: - "@mapbox/point-geometry" "~0.1.0" + "@mapbox/point-geometry" "~1.1.0" + "@types/geojson" "^7946.0.16" + pbf "^5.0.0" -"@mapbox/whoots-js@^3.1.0": - version "3.1.0" - resolved "https://registry.yarnpkg.com/@mapbox/whoots-js/-/whoots-js-3.1.0.tgz#497c67a1cef50d1a2459ba60f315e448d2ad87fe" - integrity sha512-Es6WcD0nO5l+2BOQS4uLfNPYQaNDfbot3X1XUoloz+x0mPDS3eeORZJl06HXjwBG1fOGwCRnzK88LMdxKRrd6Q== +"@maplibre/geojson-vt@^6.1.1": + version "6.1.1" + resolved "https://registry.yarnpkg.com/@maplibre/geojson-vt/-/geojson-vt-6.1.1.tgz#25a032435b4ce2236ea0ba911aff5fb6d5454fc1" + integrity sha512-FVMOcmSP/yqol45t7StApEyTL5/vmqBCuFhH9n+fFuINenhaX+YgHHIt1yJ86S8kln3uJLcMvmEU2cfn6E2eCQ== + dependencies: + kdbush "^4.1.0" -"@maplibre/maplibre-gl-style-spec@^23.1.0": - version "23.3.0" - resolved "https://registry.yarnpkg.com/@maplibre/maplibre-gl-style-spec/-/maplibre-gl-style-spec-23.3.0.tgz#b69ab48cb3abead4e49213396c8f83492638b97c" - integrity sha512-IGJtuBbaGzOUgODdBRg66p8stnwj9iDXkgbYKoYcNiiQmaez5WVRfXm4b03MCDwmZyX93csbfHFWEJJYHnn5oA== +"@maplibre/maplibre-gl-style-spec@^26.4.4": + version "26.4.4" + resolved "https://registry.yarnpkg.com/@maplibre/maplibre-gl-style-spec/-/maplibre-gl-style-spec-26.4.4.tgz#e103d50f9eed8a44f1fde1c4970c5d2a47b19b78" + integrity sha512-hG4RZR4PBd/+6A3ODdZ3AnQRF106ZQk1y3bhwDg8bH/A4Oz2tnRUJVVWs9BZa6gXZ1d3UKe89C+Mm+olGBELvA== dependencies: - "@mapbox/jsonlint-lines-primitives" "~2.0.2" - "@mapbox/unitbezier" "^0.0.1" + "@mapbox/jsonlint-lines-primitives" "^2.0.3" + "@mapbox/unitbezier" "^1.0.0" json-stringify-pretty-compact "^4.0.0" minimist "^1.2.8" quickselect "^3.0.0" - rw "^1.3.3" tinyqueue "^3.0.0" +"@maplibre/mlt@^1.3.0": + version "1.3.0" + resolved "https://registry.yarnpkg.com/@maplibre/mlt/-/mlt-1.3.0.tgz#3a9467d12a0b6edfcdba429dd3a260ca48f11129" + integrity sha512-7M2O7ABM80Oi8XPkfkrjKB8mOBIxGoVgkA52Mu4RMWoBvvMdagQ522+WxVYujZsMpqIr3BpzrTbXrm4k8lCzCQ== + dependencies: + "@mapbox/point-geometry" "^1.1.0" + +"@maplibre/vt-pbf@^4.3.2": + version "4.3.2" + resolved "https://registry.yarnpkg.com/@maplibre/vt-pbf/-/vt-pbf-4.3.2.tgz#cfcdbdadaf88b4cb8645e43c8eead77cd6546030" + integrity sha512-j6p0AdjvAR19Z3XaCysle7A4ZSo08tYOzxD0Y9NQylwPAkwJJeYub5b2eVucdeDh7erhv69DahoLOevDRERRUw== + dependencies: + "@mapbox/point-geometry" "^1.1.0" + "@types/geojson" "^7946.0.16" + pbf "^5.1.0" + "@mat-datetimepicker/core@~16.0.1": version "16.0.1" resolved "https://registry.yarnpkg.com/@mat-datetimepicker/core/-/core-16.0.1.tgz#f2b19b6ed85f83a83f93be866af1a9564ac0d978" @@ -3503,13 +3514,6 @@ resolved "https://registry.yarnpkg.com/@types/flowjs/-/flowjs-2.13.14.tgz#62cdd8d5d8e0222e505e4a140e73cd385c0a496c" integrity sha512-OlZFH9hbOq5B+GeBjcM3UvvSailseRT+sKoi9jyFFczvvS1n1LTiTKJysDSLVWnUvGD+tsn7kxb6eC2uaJD+Zw== -"@types/geojson-vt@3.2.5": - version "3.2.5" - resolved "https://registry.yarnpkg.com/@types/geojson-vt/-/geojson-vt-3.2.5.tgz#b6c356874991d9ab4207533476dfbcdb21e38408" - integrity sha512-qDO7wqtprzlpe8FfQ//ClPV9xiuoh2nkIgiouIptON9w5jvD/fA4szvP9GBlDVdJ5dldAl0kX/sy3URbWwLx0g== - dependencies: - "@types/geojson" "*" - "@types/geojson@*", "@types/geojson@^7946.0.10", "@types/geojson@^7946.0.16": version "7946.0.16" resolved "https://registry.yarnpkg.com/@types/geojson/-/geojson-7946.0.16.tgz#8ebe53d69efada7044454e3305c19017d97ced2a" @@ -3594,20 +3598,6 @@ resolved "https://registry.yarnpkg.com/@types/lodash/-/lodash-4.17.23.tgz#c1bb06db218acc8fc232da0447473fc2fb9d9841" integrity sha512-RDvF6wTulMPjrNdCoYRC8gNR880JNGT8uB+REUpC2Ns4pRqQJhGz90wh7rgdXDPpCczF3VGktDuFGVnz8zP7HA== -"@types/mapbox__point-geometry@*", "@types/mapbox__point-geometry@^0.1.4": - version "0.1.4" - resolved "https://registry.yarnpkg.com/@types/mapbox__point-geometry/-/mapbox__point-geometry-0.1.4.tgz#0ef017b75eedce02ff6243b4189210e2e6d5e56d" - integrity sha512-mUWlSxAmYLfwnRBmgYV86tgYmMIICX4kza8YnE/eIlywGe2XoOxlpVnXWwir92xRLjwyarqwpu2EJKD2pk0IUA== - -"@types/mapbox__vector-tile@^1.3.4": - version "1.3.4" - resolved "https://registry.yarnpkg.com/@types/mapbox__vector-tile/-/mapbox__vector-tile-1.3.4.tgz#ad757441ef1d34628d9e098afd9c91423c1f8734" - integrity sha512-bpd8dRn9pr6xKvuEBQup8pwQfD4VUyqO/2deGjfpe6AwC8YRlyEipvefyRJUSiCJTZuCb8Pl1ciVV5ekqJ96Bg== - dependencies: - "@types/geojson" "*" - "@types/mapbox__point-geometry" "*" - "@types/pbf" "*" - "@types/mime@^1": version "1.3.5" resolved "https://registry.yarnpkg.com/@types/mime/-/mime-1.3.5.tgz#1ef302e01cf7d2b5a0fa526790c9123bf1d06690" @@ -3625,11 +3615,6 @@ dependencies: undici-types "~6.21.0" -"@types/pbf@*", "@types/pbf@^3.0.5": - version "3.0.5" - resolved "https://registry.yarnpkg.com/@types/pbf/-/pbf-3.0.5.tgz#a9495a58d8c75be4ffe9a0bd749a307715c07404" - integrity sha512-j3pOPiEcWZ34R6a6mN07mUkM4o4Lwf6hPNt8eilOeZhTFbxFXmKhvXl9Y28jotFPaI1bpPDJsbCprUoNke6OrA== - "@types/qs@*": version "6.9.16" resolved "https://registry.yarnpkg.com/@types/qs/-/qs-6.9.16.tgz#52bba125a07c0482d26747d5d4947a64daf8f794" @@ -3686,13 +3671,6 @@ dependencies: "@types/node" "*" -"@types/supercluster@^7.1.3": - version "7.1.3" - resolved "https://registry.yarnpkg.com/@types/supercluster/-/supercluster-7.1.3.tgz#1a1bc2401b09174d9c9e44124931ec7874a72b27" - integrity sha512-Z0pOY34GDFl3Q6hUFYf3HkTwKEE02e7QgtJppBt+beEAxnyOpJua+voGFvxINBHa06GwLFFym7gRPY2SiKIfIA== - dependencies: - "@types/geojson" "*" - "@types/systemjs@6.15.3": version "6.15.3" resolved "https://registry.yarnpkg.com/@types/systemjs/-/systemjs-6.15.3.tgz#d758dceafee62d2ed4aad7d07342b145d623e260" @@ -4437,6 +4415,13 @@ beasties@0.3.5: postcss "^8.4.49" postcss-media-query-parser "^0.2.3" +bidi-js@^1.1.0: + version "1.1.0" + resolved "https://registry.yarnpkg.com/bidi-js/-/bidi-js-1.1.0.tgz#c92efafe3fce3b9fdd30ba67bdddf0dd4d424af7" + integrity sha512-fX1Onk0tdVPC7obPWB5EbJ1z7NVhLq4m2xZLq2YXBkxzMXIGRpNMU88n0EPgWseKl12J7zXs7qrDxPK4sRs2fg== + dependencies: + require-from-string "^2.0.2" + big.js@^5.2.2: version "5.2.2" resolved "https://registry.yarnpkg.com/big.js/-/big.js-5.2.2.tgz#65f0af382f578bcdc742bd9c281e9cb2d7768328" @@ -5606,10 +5591,10 @@ dunder-proto@^1.0.0, dunder-proto@^1.0.1: es-errors "^1.3.0" gopd "^1.2.0" -earcut@^3.0.1: - version "3.0.2" - resolved "https://registry.yarnpkg.com/earcut/-/earcut-3.0.2.tgz#d478a29aaf99acf418151493048aa197d0512248" - integrity sha512-X7hshQbLyMJ/3RPhyObLARM2sNxxmRALLKx1+NVFFnQ9gKzmCrxm9+uLIAdBcvc8FNLpctqlQ2V6AE92Ol9UDQ== +earcut@^3.2.3: + version "3.2.3" + resolved "https://registry.yarnpkg.com/earcut/-/earcut-3.2.3.tgz#74aec19555a7e28773429826729d2e4bfeb19022" + integrity sha512-vnS4AVwp1KHAF13i1vp1/2D5evWy3k5u/iW/B81QVsUZtV8cv2tU0b2VNFlqvh4kYwrFMDdjPCfAmfyJW9y14Q== eastasianwidth@^0.2.0: version "0.2.0" @@ -6483,11 +6468,6 @@ gensync@^1.0.0-beta.2: resolved "https://registry.yarnpkg.com/gensync/-/gensync-1.0.0-beta.2.tgz#32a6ee76c3d7f52d46b2b1ae5d93fea8580a25e0" integrity sha512-3hN7NaskYvMDLQY55gnW3NQ+mesEAepTqlg+VEbj7zzqEMBVNhzcGYYeqFo/TlYz6eQiFcp1HcsCZO+nGgS8zg== -geojson-vt@^4.0.2: - version "4.0.2" - resolved "https://registry.yarnpkg.com/geojson-vt/-/geojson-vt-4.0.2.tgz#1162f6c7d61a0ba305b1030621e6e111f847828a" - integrity sha512-AV9ROqlNqoZEIJGfm1ncNjEXfkz2hdFlZf0qkVfmkwdKa8vj7H16YUOT81rJw1rdFhyEDlN2Tds91p/glzbl5A== - get-caller-file@^2.0.1, get-caller-file@^2.0.5: version "2.0.5" resolved "https://registry.yarnpkg.com/get-caller-file/-/get-caller-file-2.0.5.tgz#4f94412a82db32f36e3b0b9741f8a97feb031f7e" @@ -6522,11 +6502,6 @@ get-proto@^1.0.1: dunder-proto "^1.0.1" es-object-atoms "^1.0.0" -get-stream@^6.0.1: - version "6.0.1" - resolved "https://registry.yarnpkg.com/get-stream/-/get-stream-6.0.1.tgz#a262d8eef67aced57c2852ad6167526a43cbf7b7" - integrity sha512-ts6Wi+2j3jQjqi70w5AlN8DFnkSwC+MqmxEzdEALB2qXZYV3X/b1CTfgPLGJNMeAWxdPfU8FO1ms3NUfaHCPYg== - get-symbol-description@^1.1.0: version "1.1.0" resolved "https://registry.yarnpkg.com/get-symbol-description/-/get-symbol-description-1.1.0.tgz#7bdd54e0befe8ffc9f3b4e203220d9f1e881b6ee" @@ -6536,7 +6511,7 @@ get-symbol-description@^1.1.0: es-errors "^1.3.0" get-intrinsic "^1.2.6" -gl-matrix@^3.4.3: +gl-matrix@^3.4.4: version "3.4.4" resolved "https://registry.yarnpkg.com/gl-matrix/-/gl-matrix-3.4.4.tgz#7789ee4982f62c7a7af447ee488f3bd6b0c77003" integrity sha512-latSnyDNt/8zYUB6VIJ6PCh2jBjJX6gnDsoCZ7LyW7GkqrD51EWwa9qCoGixj8YqBtETQK/xY7OmpTF8xz1DdQ== @@ -6586,15 +6561,6 @@ glob@^13.0.0: minipass "^7.1.2" path-scurry "^2.0.0" -global-prefix@^4.0.0: - version "4.0.0" - resolved "https://registry.yarnpkg.com/global-prefix/-/global-prefix-4.0.0.tgz#e9cc79aab9be1d03287e156a3f912dd0895463ed" - integrity sha512-w0Uf9Y9/nyHinEk5vMJKRie+wa4kR5hmDbEhGGds/kG1PwGLLHKRoNMeJOyCQjjBkANlnScqgzcFwGHgmgLkVA== - dependencies: - ini "^4.1.3" - kind-of "^6.0.3" - which "^4.0.0" - globals@^14.0.0: version "14.0.0" resolved "https://registry.yarnpkg.com/globals/-/globals-14.0.0.tgz#898d7413c29babcf6bafe56fcadded858ada724e" @@ -6853,11 +6819,6 @@ icss-utils@^5.0.0, icss-utils@^5.1.0: resolved "https://registry.yarnpkg.com/icss-utils/-/icss-utils-5.1.0.tgz#c6be6858abd013d768e98366ae47e25d5887b1ae" integrity sha512-soFhflCVWLfRNOPU3iv5Z9VUdT44xFRbzjLsEzSr5AQmgqPMTHdU3PMT1Cf1ssx8fLNJDA1juftYl+PUcv3MqA== -ieee754@^1.1.12: - version "1.2.1" - resolved "https://registry.yarnpkg.com/ieee754/-/ieee754-1.2.1.tgz#8eb7a10a63fff25d15a57b001586d177d1b0d352" - integrity sha512-dcyqhDvX1C46lXZcVqCpK+FtMRQVdIMN6/Df5js2zouUsqG7I6sFxitIC+7KYK29KdXOLHdu9zL4sFnoVQnqaA== - ignore-walk@^8.0.0: version "8.0.0" resolved "https://registry.yarnpkg.com/ignore-walk/-/ignore-walk-8.0.0.tgz#380c173badc3a18c57ff33440753f0052f572b14" @@ -6918,11 +6879,6 @@ ini@^1.3.4: resolved "https://registry.yarnpkg.com/ini/-/ini-1.3.8.tgz#a29da425b48806f34767a4efce397269af28432c" integrity sha512-JV/yugV2uzW5iMRSiZAyDtQd+nxtUnjeLt0acNdw98kKLrvuRVyB80tsREOE7yvGVgalhZ6RNXCmEHkUKBKxew== -ini@^4.1.3: - version "4.1.3" - resolved "https://registry.yarnpkg.com/ini/-/ini-4.1.3.tgz#4c359675a6071a46985eb39b14e4a2c0ec98a795" - integrity sha512-X7rqawQBvfdjS10YU1y1YVreA3SsLrW9dX2CewP2EbBJM4ypVNLDkO5y04gejPwKIY9lR+7r9gn3rFPt/kmWFg== - ini@^6.0.0: version "6.0.0" resolved "https://registry.yarnpkg.com/ini/-/ini-6.0.0.tgz#efc7642b276f6a37d22fdf56ef50889d7146bf30" @@ -7511,10 +7467,10 @@ katex@^0.16.0, katex@^0.16.25: dependencies: commander "^8.3.0" -kdbush@^4.0.2: - version "4.0.2" - resolved "https://registry.yarnpkg.com/kdbush/-/kdbush-4.0.2.tgz#2f7b7246328b4657dd122b6c7f025fbc2c868e39" - integrity sha512-WbCVYJ27Sz8zi9Q7Q0xHC+05iwkm3Znipc2XTlrnJbsHMYktW4hPhXUE8Ys1engBrvffoSCqbil1JQAa7clRpA== +kdbush@^4.1.0: + version "4.1.0" + resolved "https://registry.yarnpkg.com/kdbush/-/kdbush-4.1.0.tgz#d504bc0447a59be4fb75533a5c25e316b3ed8859" + integrity sha512-e9vurzrXJQrFX6ckpHP3bvj5l+9CnYzkxDNnNQ1h2QTqdWsUAJgXiKdGNcOa1EY85dU8KbQ+z/FdQdB7P+9yfQ== keyv@^4.5.4: version "4.5.4" @@ -7528,7 +7484,7 @@ khroma@^2.1.0: resolved "https://registry.yarnpkg.com/khroma/-/khroma-2.1.0.tgz#45f2ce94ce231a437cf5b63c2e886e6eb42bbbb1" integrity sha512-Ls993zuzfayK269Svk9hzpeGUKob/sIgZzyHYdjQoAdQetRKpOLj+k/QQQ/6Qi0Yz65mlROrfd+Ev+1+7dz9Kw== -kind-of@^6.0.2, kind-of@^6.0.3: +kind-of@^6.0.2: version "6.0.3" resolved "https://registry.yarnpkg.com/kind-of/-/kind-of-6.0.3.tgz#07c05034a6c349fa06e24fa35aa76db4580ce4dd" integrity sha512-dcS1ul+9tmeD95T+x28/ehLgd9mENa3LsvDTtzm3vyBEO7RPptvAD+t44WVXaUjTBRcrpFeFlC8WCruUR456hw== @@ -7825,37 +7781,29 @@ make-plural@^7.0.0: resolved "https://registry.yarnpkg.com/make-plural/-/make-plural-7.4.0.tgz#fa6990dd550dea4de6b20163f74e5ed83d8a8d6d" integrity sha512-4/gC9KVNTV6pvYg2gFeQYTW3mWaoJt7WZE5vrp1KnQDgW92JtYZnzmZT81oj/dUTqAIu0ufI2x3dkgu3bB1tYg== -maplibre-gl@5.2.0: - version "5.2.0" - resolved "https://registry.yarnpkg.com/maplibre-gl/-/maplibre-gl-5.2.0.tgz#e3cdb66c82232cffbe149b032776484722caee4e" - integrity sha512-9zZKD0M80qtDsqBet+EDuAhoCeA/cnAuZAA0p3hcGKGbyjM/SH+R6wQvnBEgvJz9UhDynnkoKdUwhI+fUkHoXQ== - dependencies: - "@mapbox/geojson-rewind" "^0.5.2" - "@mapbox/jsonlint-lines-primitives" "^2.0.2" - "@mapbox/point-geometry" "^0.1.0" - "@mapbox/tiny-sdf" "^2.0.6" - "@mapbox/unitbezier" "^0.0.1" - "@mapbox/vector-tile" "^1.3.1" - "@mapbox/whoots-js" "^3.1.0" - "@maplibre/maplibre-gl-style-spec" "^23.1.0" +maplibre-gl@6.11.2: + version "6.11.2" + resolved "https://registry.yarnpkg.com/maplibre-gl/-/maplibre-gl-6.11.2.tgz#25f1266666c16f6b935cabccba554c238a3cf394" + integrity sha512-Xh06pxoipjX/Ad1sUPGhiNh9go9naCNGZZ1IJm3sIeqK1kYGuMaMDSTIGDQ2igOLfVyukJU7kvEOA089VO7Z7g== + dependencies: + "@mapbox/point-geometry" "^1.1.0" + "@mapbox/tiny-sdf" "^2.2.0" + "@mapbox/unitbezier" "^1.0.0" + "@mapbox/vector-tile" "^3.0.0" + "@maplibre/geojson-vt" "^6.1.1" + "@maplibre/maplibre-gl-style-spec" "^26.4.4" + "@maplibre/mlt" "^1.3.0" + "@maplibre/vt-pbf" "^4.3.2" "@types/geojson" "^7946.0.16" - "@types/geojson-vt" "3.2.5" - "@types/mapbox__point-geometry" "^0.1.4" - "@types/mapbox__vector-tile" "^1.3.4" - "@types/pbf" "^3.0.5" - "@types/supercluster" "^7.1.3" - earcut "^3.0.1" - geojson-vt "^4.0.2" - gl-matrix "^3.4.3" - global-prefix "^4.0.0" - kdbush "^4.0.2" + bidi-js "^1.1.0" + earcut "^3.2.3" + gl-matrix "^3.4.4" + kdbush "^4.1.0" murmurhash-js "^1.0.0" - pbf "^3.3.0" - potpack "^2.0.0" + pbf "^5.1.2" + potpack "^2.1.0" quickselect "^3.0.0" - supercluster "^8.0.1" tinyqueue "^3.0.0" - vt-pbf "^3.1.3" marked@^16.3.0, marked@~16.4.2: version "16.4.2" @@ -8845,12 +8793,11 @@ pathe@^2.0.1, pathe@^2.0.3: resolved "https://registry.yarnpkg.com/pathe/-/pathe-2.0.3.tgz#3ecbec55421685b70a9da872b2cff3e1cbed1716" integrity sha512-WUjGcAqP1gQacoQe+OBJsFA7Ld4DyXuUIjZ5cc75cLHvJ7dtNsTugphxIADwspS+AraAUePCKrSVtPLFj/F88w== -pbf@^3.2.1, pbf@^3.3.0: - version "3.3.0" - resolved "https://registry.yarnpkg.com/pbf/-/pbf-3.3.0.tgz#1790f3d99118333cc7f498de816028a346ef367f" - integrity sha512-XDF38WCH3z5OV/OVa8GKUNtLAyneuzbCisx7QUCF8Q6Nutx0WnJrQe5O+kOtBlLfRNUws98Y58Lblp+NJG5T4Q== +pbf@^5.0.0, pbf@^5.1.0, pbf@^5.1.2: + version "5.1.2" + resolved "https://registry.yarnpkg.com/pbf/-/pbf-5.1.2.tgz#07c427819eda32f02f1ec9741558f61444f2e1c0" + integrity sha512-mnvGdvOrIvJOBGUEdGkrVXjN8E/VkIJCkf2eS1DH2yv82ORUlLttmDt0rWY38yYZmVwciZwBUvHM20qxBZf40w== dependencies: - ieee754 "^1.1.12" resolve-protobuf-schema "^2.1.0" photoswipe@^5.4.4: @@ -9053,7 +9000,7 @@ postinstall-prepare@^2.0.0: resolved "https://registry.yarnpkg.com/postinstall-prepare/-/postinstall-prepare-2.0.0.tgz#2a6867c1a13a05502aa115d0495efbbd778769cb" integrity sha512-lLFwEKdnGLAaRAm8OpXP6HwrXRW+b8Hh9vRhVHZKmCdobd+D21YM38BCDsi3zrePLSe8Tt0H/mbYkh7/ySQQMg== -potpack@^2.0.0: +potpack@^2.1.0: version "2.1.0" resolved "https://registry.yarnpkg.com/potpack/-/potpack-2.1.0.tgz#fe548e2f9061e9937f17191c1ab6dd98ca30e02f" integrity sha512-pcaShQc1Shq0y+E7GqJqvZj8DTthWV1KeHGdi0Z6IAin2Oi3JnLCOfwnCo84qc+HAp52wT9nK9H7FAJp5a44GQ== @@ -9495,7 +9442,7 @@ run-parallel@^1.1.9: dependencies: queue-microtask "^1.2.2" -rw@1, rw@^1.3.3: +rw@1: version "1.3.3" resolved "https://registry.yarnpkg.com/rw/-/rw-1.3.3.tgz#3f862dfa91ab766b14885ef4d01124bfda074fb4" integrity sha512-PdhdWy89SiZogBLaw42zdeqtRJ//zFd2PgQavcICDUgJT5oW10QCRKbJ6bg4r0/UY2M6BWd5tkxuGFRvCkgfHQ== @@ -10172,13 +10119,6 @@ sucrase@^3.35.0: tinyglobby "^0.2.11" ts-interface-checker "^0.1.9" -supercluster@^8.0.1: - version "8.0.1" - resolved "https://registry.yarnpkg.com/supercluster/-/supercluster-8.0.1.tgz#9946ba123538e9e9ab15de472531f604e7372df5" - integrity sha512-IiOea5kJ9iqzD2t7QJq/cREyLHTtSmUT6gQsweojg9WH2sYJqZK9SswTu6jrscO6D1G5v5vYZ9ru/eq85lXeZQ== - dependencies: - kdbush "^4.0.2" - supports-color@^5.3.0: version "5.5.0" resolved "https://registry.yarnpkg.com/supports-color/-/supports-color-5.5.0.tgz#e2e69a44ac8772f78a1ec0b35b689df6530efc8f" @@ -10787,15 +10727,6 @@ vscode-uri@~3.1.0: resolved "https://registry.yarnpkg.com/vscode-uri/-/vscode-uri-3.1.0.tgz#dd09ec5a66a38b5c3fffc774015713496d14e09c" integrity sha512-/BpdSx+yCQGnCvecbyXdxHDkuk55/G3xwnC0GqY4gmQ3j+A+g8kzzgB4Nk/SINjqn6+waqw3EgbVF2QKExkRxQ== -vt-pbf@^3.1.3: - version "3.1.3" - resolved "https://registry.yarnpkg.com/vt-pbf/-/vt-pbf-3.1.3.tgz#68fd150756465e2edae1cc5c048e063916dcfaac" - integrity sha512-2LzDFzt0mZKZ9IpVF2r69G9bXaP2Q2sArJCmcCgvfTdCCZzSyz4aCLoQyUilu37Ll56tCblIZrXFIjNUpGIlmA== - dependencies: - "@mapbox/point-geometry" "0.1.0" - "@mapbox/vector-tile" "^1.3.1" - pbf "^3.2.1" - watchpack@2.4.4: version "2.4.4" resolved "https://registry.yarnpkg.com/watchpack/-/watchpack-2.4.4.tgz#473bda72f0850453da6425081ea46fc0d7602947" @@ -11025,13 +10956,6 @@ which@^2.0.1: dependencies: isexe "^2.0.0" -which@^4.0.0: - version "4.0.0" - resolved "https://registry.yarnpkg.com/which/-/which-4.0.0.tgz#cd60b5e74503a3fbcfbf6cd6b4138a8bae644c1a" - integrity sha512-GlaYyEb07DPxYCKhKzplCWBJtvxZcZMrL+4UkrTSJHHPyZU4mYYTv3qaOe77H7EODLSSopAUFAc6W8U4yqvscg== - dependencies: - isexe "^3.1.1" - which@^6.0.0: version "6.0.0" resolved "https://registry.yarnpkg.com/which/-/which-6.0.0.tgz#a3a721a14cdd9b991a722e493c177eeff82ff32a" From d30a2ca32b04888f2bbd1a63fa630687d2603585 Mon Sep 17 00:00:00 2001 From: Viacheslav Klimov Date: Fri, 25 Sep 2026 11:44:34 +0300 Subject: [PATCH 084/159] Set docker.skip.latest.tag to true --- msa/pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/msa/pom.xml b/msa/pom.xml index e9862177ea..0107c06654 100644 --- a/msa/pom.xml +++ b/msa/pom.xml @@ -189,7 +189,7 @@ 4.3.1-latest - false + true From 862b224dd7e4e770804ffad3411255166daa4501 Mon Sep 17 00:00:00 2001 From: Viacheslav Klimov Date: Fri, 25 Sep 2026 16:19:59 +0300 Subject: [PATCH 085/159] Reject non-user JWT scopes on WebSocket API --- .../controller/plugin/TbWebSocketHandler.java | 17 +++++++- .../server/controller/TwoFactorAuthTest.java | 42 +++++++++++++++++++ 2 files changed, 57 insertions(+), 2 deletions(-) diff --git a/application/src/main/java/org/thingsboard/server/controller/plugin/TbWebSocketHandler.java b/application/src/main/java/org/thingsboard/server/controller/plugin/TbWebSocketHandler.java index a7e3ed4ba9..2e8dda4d32 100644 --- a/application/src/main/java/org/thingsboard/server/controller/plugin/TbWebSocketHandler.java +++ b/application/src/main/java/org/thingsboard/server/controller/plugin/TbWebSocketHandler.java @@ -19,6 +19,7 @@ import org.springframework.beans.factory.BeanCreationNotAllowedException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Lazy; +import org.springframework.security.authentication.BadCredentialsException; import org.springframework.stereotype.Service; import org.springframework.web.socket.CloseStatus; import org.springframework.web.socket.PongMessage; @@ -34,6 +35,7 @@ import org.thingsboard.server.common.data.id.CustomerId; import org.thingsboard.server.common.data.id.TenantId; import org.thingsboard.server.common.data.id.UserId; import org.thingsboard.server.common.data.limit.LimitedApi; +import org.thingsboard.server.common.data.security.Authority; import org.thingsboard.server.common.data.tenant.profile.DefaultTenantProfileConfiguration; import org.thingsboard.server.config.WebSocketConfiguration; import org.thingsboard.server.dao.tenant.TbTenantProfileCache; @@ -55,6 +57,7 @@ import org.thingsboard.server.service.ws.telemetry.cmd.TelemetryCmdsWrapper; import java.io.IOException; import java.security.InvalidParameterException; +import java.util.EnumSet; import java.util.Optional; import java.util.Queue; import java.util.Set; @@ -76,6 +79,8 @@ import static org.thingsboard.server.service.ws.DefaultWebSocketService.NUMBER_O @RequiredArgsConstructor public class TbWebSocketHandler extends TextWebSocketHandler implements WebSocketMsgEndpoint { + private static final Set USER_AUTHORITIES = EnumSet.of(Authority.SYS_ADMIN, Authority.TENANT_ADMIN, Authority.CUSTOMER_USER); + private final ConcurrentMap internalSessionMap = new ConcurrentHashMap<>(); private final ConcurrentMap externalSessionMap = new ConcurrentHashMap<>(); @@ -181,7 +186,7 @@ public class TbWebSocketHandler extends TextWebSocketHandler implements WebSocke log.trace("{} Authenticating session", sessionRef); SecurityUser securityCtx; try { - securityCtx = authenticationProvider.authenticate(authCmd.getToken()); + securityCtx = authenticate(authCmd.getToken()); } catch (Exception e) { close(sessionRef, CloseStatus.BAD_DATA.withReason(e.getMessage())); return; @@ -317,7 +322,7 @@ public class TbWebSocketHandler extends TextWebSocketHandler implements WebSocke SecurityUser securityCtx = null; String token = StringUtils.substringAfter(session.getUri().getQuery(), "token="); if (StringUtils.isNotEmpty(token)) { - securityCtx = authenticationProvider.authenticate(token); + securityCtx = authenticate(token); } return WebSocketSessionRef.builder() .sessionId(UUID.randomUUID().toString()) @@ -328,6 +333,14 @@ public class TbWebSocketHandler extends TextWebSocketHandler implements WebSocke .build(); } + private SecurityUser authenticate(String token) { + SecurityUser securityUser = authenticationProvider.authenticate(token); + if (!USER_AUTHORITIES.contains(securityUser.getAuthority())) { + throw new BadCredentialsException("Token is invalid"); + } + return securityUser; + } + private SessionMetaData getSessionMd(String internalSessionId) { SessionMetaData sessionMd = internalSessionMap.get(internalSessionId); if (sessionMd == null) { diff --git a/application/src/test/java/org/thingsboard/server/controller/TwoFactorAuthTest.java b/application/src/test/java/org/thingsboard/server/controller/TwoFactorAuthTest.java index 3170d9480f..4618ebf4e0 100644 --- a/application/src/test/java/org/thingsboard/server/controller/TwoFactorAuthTest.java +++ b/application/src/test/java/org/thingsboard/server/controller/TwoFactorAuthTest.java @@ -13,6 +13,8 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.bean.override.mockito.MockitoBean; import org.springframework.test.context.bean.override.mockito.MockitoSpyBean; import org.thingsboard.rule.engine.api.SmsService; +import org.thingsboard.server.common.data.Device; +import org.thingsboard.server.common.data.EntityType; import org.thingsboard.server.common.data.StringUtils; import org.thingsboard.server.common.data.User; import org.thingsboard.server.common.data.audit.ActionStatus; @@ -23,6 +25,8 @@ import org.thingsboard.server.common.data.id.TenantId; import org.thingsboard.server.common.data.page.PageLink; import org.thingsboard.server.common.data.page.SortOrder; import org.thingsboard.server.common.data.page.TimePageLink; +import org.thingsboard.server.common.data.query.EntityData; +import org.thingsboard.server.common.data.query.EntityTypeFilter; import org.thingsboard.server.common.data.security.Authority; import org.thingsboard.server.common.data.security.model.JwtPair; import org.thingsboard.server.common.data.security.model.mfa.PlatformTwoFaSettings; @@ -40,6 +44,7 @@ import org.thingsboard.server.dao.user.UserService; import org.thingsboard.server.service.security.auth.mfa.TwoFactorAuthService; import org.thingsboard.server.service.security.auth.mfa.config.TwoFaConfigManager; import org.thingsboard.server.service.security.auth.rest.LoginRequest; +import org.thingsboard.server.service.ws.telemetry.cmd.v2.EntityDataUpdate; import java.time.Duration; import java.util.Arrays; @@ -141,6 +146,43 @@ public class TwoFactorAuthTest extends AbstractControllerTest { assertThat(currentUser.getId()).isEqualTo(user.getId()); } + @Test + public void testWsAuthCmd_preVerificationTokenRejected() throws Exception { + configureTotpTwoFa(); + logInWithPreVerificationToken(username, password); + + wsClient = buildAndConnectWebSocketClient(); + + await().atMost(TIMEOUT, TimeUnit.SECONDS).until(wsClient::isClosed); + } + + @Test + public void testWsQueryToken_preVerificationTokenRejected() throws Exception { + configureTotpTwoFa(); + logInWithPreVerificationToken(username, password); + + wsClient = buildAndConnectWebSocketClient("/api/ws?token=" + token); + + await().atMost(TIMEOUT, TimeUnit.SECONDS).until(wsClient::isClosed); + } + + @Test + public void testWs_accessTokenAcceptedAfterTwoFa() throws Exception { + TotpTwoFaAccountConfig totpTwoFaAccountConfig = configureTotpTwoFa(); + logInWithPreVerificationToken(username, password); + JsonNode tokenPair = readResponse(doPost("/api/auth/2fa/verification/check?providerType=TOTP&verificationCode=" + getCorrectTotp(totpTwoFaAccountConfig)) + .andExpect(status().isOk()), JsonNode.class); + validateAndSetJwtToken(tokenPair, username); + Device device = createDevice("2FA device", "2FA device token"); + + EntityTypeFilter deviceFilter = new EntityTypeFilter(); + deviceFilter.setEntityType(EntityType.DEVICE); + EntityDataUpdate update = getWsClient().sendEntityDataQuery(deviceFilter); + + assertThat(update.getData().getData()).singleElement() + .extracting(EntityData::getEntityId).isEqualTo(device.getId()); + } + @Test public void testTwoFaPreVerificationTokenLifetime() throws Exception { configureTotpTwoFa(twoFaSettings -> { From fde680928770f0756e85d64ff48476be56a6e626 Mon Sep 17 00:00:00 2001 From: Viacheslav Klimov Date: Fri, 25 Sep 2026 16:42:39 +0300 Subject: [PATCH 086/159] Store the granted license key in tb_cluster The enrollment now collects its license key from the portal when the grant is done, and keeps it in tb_cluster.license_secret. A claim that has nothing to hand over yet leaves the flow for the next poll; a refused claim ends the flow registered without a key; a transport failure is left to the existing backoff. --- .../upgrade/lts/4.3.1.6/schema_update.sql | 8 +++ ...nityGrantLicenseClaimRefusedException.java | 16 ++++++ .../CommunityGrantLicenseClaimRequest.java | 4 ++ .../CommunityGrantLicenseClaimResponse.java | 8 +++ .../community_grant/CommunityGrantPoller.java | 44 ++++++++++++--- .../CommunityGrantPortalClient.java | 25 +++++++++ .../CommunityGrantPollerTest.java | 56 +++++++++++++++++++ .../CommunityGrantPortalClientTest.java | 48 ++++++++++++++++ .../dao/subscription/TbClusterStore.java | 13 ++++- .../main/resources/sql/schema-entities.sql | 1 + .../dao/subscription/TbClusterStoreTest.java | 27 +++++++++ 11 files changed, 242 insertions(+), 8 deletions(-) create mode 100644 application/src/main/java/org/thingsboard/server/service/community_grant/CommunityGrantLicenseClaimRefusedException.java create mode 100644 application/src/main/java/org/thingsboard/server/service/community_grant/CommunityGrantLicenseClaimRequest.java create mode 100644 application/src/main/java/org/thingsboard/server/service/community_grant/CommunityGrantLicenseClaimResponse.java diff --git a/application/src/main/data/upgrade/lts/4.3.1.6/schema_update.sql b/application/src/main/data/upgrade/lts/4.3.1.6/schema_update.sql index e984d996f5..740462d6c9 100644 --- a/application/src/main/data/upgrade/lts/4.3.1.6/schema_update.sql +++ b/application/src/main/data/upgrade/lts/4.3.1.6/schema_update.sql @@ -11,6 +11,7 @@ CREATE TABLE IF NOT EXISTS tb_cluster ( cluster_id uuid NOT NULL, license_claim_token varchar, + license_secret varchar, CONSTRAINT tb_cluster_pkey PRIMARY KEY (cluster_id) ); @@ -19,3 +20,10 @@ CREATE TABLE IF NOT EXISTS tb_cluster ( CREATE UNIQUE INDEX IF NOT EXISTS tb_cluster_single_row ON tb_cluster ((true)); -- TB_CLUSTER END + +-- TB_CLUSTER LICENSE SECRET START + +-- The CREATE above is a no-op on a database that already carries tb_cluster. +ALTER TABLE tb_cluster ADD COLUMN IF NOT EXISTS license_secret varchar; + +-- TB_CLUSTER LICENSE SECRET END diff --git a/application/src/main/java/org/thingsboard/server/service/community_grant/CommunityGrantLicenseClaimRefusedException.java b/application/src/main/java/org/thingsboard/server/service/community_grant/CommunityGrantLicenseClaimRefusedException.java new file mode 100644 index 0000000000..71fc304165 --- /dev/null +++ b/application/src/main/java/org/thingsboard/server/service/community_grant/CommunityGrantLicenseClaimRefusedException.java @@ -0,0 +1,16 @@ +package org.thingsboard.server.service.community_grant; + +import org.springframework.web.client.HttpStatusCodeException; +import org.springframework.web.client.RestClientException; + +/** + * Thrown by {@link CommunityGrantPortalClient#claimLicense} when the portal will not hand the license key + * over. Terminal, unlike a transport failure: retrying the claim cannot change the answer. + */ +public class CommunityGrantLicenseClaimRefusedException extends RestClientException { + + public CommunityGrantLicenseClaimRefusedException(HttpStatusCodeException cause) { + super(cause.getMessage(), cause); + } + +} diff --git a/application/src/main/java/org/thingsboard/server/service/community_grant/CommunityGrantLicenseClaimRequest.java b/application/src/main/java/org/thingsboard/server/service/community_grant/CommunityGrantLicenseClaimRequest.java new file mode 100644 index 0000000000..364c29f3bb --- /dev/null +++ b/application/src/main/java/org/thingsboard/server/service/community_grant/CommunityGrantLicenseClaimRequest.java @@ -0,0 +1,4 @@ +package org.thingsboard.server.service.community_grant; + +public record CommunityGrantLicenseClaimRequest(String claimToken) { +} diff --git a/application/src/main/java/org/thingsboard/server/service/community_grant/CommunityGrantLicenseClaimResponse.java b/application/src/main/java/org/thingsboard/server/service/community_grant/CommunityGrantLicenseClaimResponse.java new file mode 100644 index 0000000000..1870277deb --- /dev/null +++ b/application/src/main/java/org/thingsboard/server/service/community_grant/CommunityGrantLicenseClaimResponse.java @@ -0,0 +1,8 @@ +package org.thingsboard.server.service.community_grant; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; + +/** {@code secret} is set only once {@code activated} is true. */ +@JsonIgnoreProperties(ignoreUnknown = true) +public record CommunityGrantLicenseClaimResponse(boolean activated, String secret) { +} diff --git a/application/src/main/java/org/thingsboard/server/service/community_grant/CommunityGrantPoller.java b/application/src/main/java/org/thingsboard/server/service/community_grant/CommunityGrantPoller.java index 0b192ad224..a19f4e3163 100644 --- a/application/src/main/java/org/thingsboard/server/service/community_grant/CommunityGrantPoller.java +++ b/application/src/main/java/org/thingsboard/server/service/community_grant/CommunityGrantPoller.java @@ -358,9 +358,7 @@ public class CommunityGrantPoller extends TbApplicationEventListener client.claimLicense(TOKEN)) + .isInstanceOf(CommunityGrantLicenseClaimRefusedException.class); + mockServer.verify(); + } + + @Test + void testClaimLicenseLeavesARetryableAnswerToTheCaller() { + mockServer.expect(requestTo(BASE_URL + "/api/noauth/freeLicense/claim")) + .andRespond(withStatus(HttpStatus.TOO_MANY_REQUESTS)); + mockServer.expect(requestTo(BASE_URL + "/api/noauth/freeLicense/claim")) + .andRespond(withServerError()); + + assertThatThrownBy(() -> client.claimLicense(TOKEN)) + .isInstanceOf(HttpStatusCodeException.class) + .isNotInstanceOf(CommunityGrantLicenseClaimRefusedException.class); + assertThatThrownBy(() -> client.claimLicense(TOKEN)) + .isInstanceOf(HttpStatusCodeException.class) + .isNotInstanceOf(CommunityGrantLicenseClaimRefusedException.class); + mockServer.verify(); + } + @Test void testDownloadChecker() { mockServer.expect(requestTo(BASE_URL + "/api/noauth/communityGrant/checker?os=linux&arch=amd64")) diff --git a/dao/src/main/java/org/thingsboard/server/dao/subscription/TbClusterStore.java b/dao/src/main/java/org/thingsboard/server/dao/subscription/TbClusterStore.java index 44c26e57e9..e8c480447c 100644 --- a/dao/src/main/java/org/thingsboard/server/dao/subscription/TbClusterStore.java +++ b/dao/src/main/java/org/thingsboard/server/dao/subscription/TbClusterStore.java @@ -11,7 +11,10 @@ import org.springframework.stereotype.Component; import java.util.Optional; import java.util.UUID; -/** Accessor for the single {@code tb_cluster} row: the cluster id and the license portal claim token. */ +/** + * Accessor for the single {@code tb_cluster} row: the cluster id, the license portal claim token and the + * license key the portal granted. + */ @Component @Profile("!install") @RequiredArgsConstructor @@ -25,6 +28,14 @@ public class TbClusterStore { rs -> rs.next() ? Optional.ofNullable(rs.getObject("cluster_id", UUID.class)) : Optional.empty()); } + public Optional getLicenseSecret() { + return getColumn("license_secret"); + } + + public void saveLicenseSecret(String secret) { + updateColumn("license_secret", secret, "license secret"); + } + public Optional getLicenseClaimToken() { return getColumn("license_claim_token"); } diff --git a/dao/src/main/resources/sql/schema-entities.sql b/dao/src/main/resources/sql/schema-entities.sql index 711eca9c53..7b86f84231 100644 --- a/dao/src/main/resources/sql/schema-entities.sql +++ b/dao/src/main/resources/sql/schema-entities.sql @@ -7,6 +7,7 @@ CREATE TABLE IF NOT EXISTS tb_cluster ( cluster_id uuid NOT NULL, license_claim_token varchar, + license_secret varchar, CONSTRAINT tb_cluster_pkey PRIMARY KEY (cluster_id) ); diff --git a/dao/src/test/java/org/thingsboard/server/dao/subscription/TbClusterStoreTest.java b/dao/src/test/java/org/thingsboard/server/dao/subscription/TbClusterStoreTest.java index a2002079c8..502f04de8c 100644 --- a/dao/src/test/java/org/thingsboard/server/dao/subscription/TbClusterStoreTest.java +++ b/dao/src/test/java/org/thingsboard/server/dao/subscription/TbClusterStoreTest.java @@ -71,6 +71,33 @@ public class TbClusterStoreTest extends AbstractServiceTest { assertThat(tbClusterStore.getLicenseClaimToken()).contains("token-two"); } + @Test + public void testSaveAndReadLicenseSecret() { + assertThat(tbClusterStore.getLicenseSecret()).isEmpty(); + tbClusterStore.saveLicenseSecret("secret-one"); + assertThat(tbClusterStore.getLicenseSecret()).contains("secret-one"); + tbClusterStore.saveLicenseSecret("secret-two"); + assertThat(tbClusterStore.getLicenseSecret()).contains("secret-two"); + } + + @Test + public void testLicenseSecretAndClaimTokenAreStoredApart() { + tbClusterStore.saveLicenseSecret("secret-one"); + tbClusterStore.saveLicenseClaimToken("token-one"); + tbClusterStore.clearLicenseClaimToken("token-one"); + + assertThat(tbClusterStore.getLicenseSecret()).contains("secret-one"); + assertThat(tbClusterStore.getLicenseClaimToken()).isEmpty(); + } + + @Test + public void testSaveLicenseSecretFailsWhenClusterRowIsMissing() { + jdbcTemplate.update("DELETE FROM tb_cluster"); + assertThatThrownBy(() -> tbClusterStore.saveLicenseSecret("secret-one")) + .isInstanceOf(IllegalStateException.class); + assertThat(tbClusterStore.getLicenseSecret()).isEqualTo(Optional.empty()); + } + @Test public void testClearLicenseClaimToken() { tbClusterStore.saveLicenseClaimToken("token-one"); From ad83124299bee7160f1f2338f5af990f2bb7bbf8 Mon Sep 17 00:00:00 2001 From: Viacheslav Klimov Date: Fri, 25 Sep 2026 16:43:23 +0300 Subject: [PATCH 087/159] Add the license headers to the new community grant claim classes --- .../CommunityGrantLicenseClaimRefusedException.java | 2 ++ .../community_grant/CommunityGrantLicenseClaimRequest.java | 2 ++ .../community_grant/CommunityGrantLicenseClaimResponse.java | 2 ++ 3 files changed, 6 insertions(+) diff --git a/application/src/main/java/org/thingsboard/server/service/community_grant/CommunityGrantLicenseClaimRefusedException.java b/application/src/main/java/org/thingsboard/server/service/community_grant/CommunityGrantLicenseClaimRefusedException.java index 71fc304165..57c68a9fc4 100644 --- a/application/src/main/java/org/thingsboard/server/service/community_grant/CommunityGrantLicenseClaimRefusedException.java +++ b/application/src/main/java/org/thingsboard/server/service/community_grant/CommunityGrantLicenseClaimRefusedException.java @@ -1,3 +1,5 @@ +// SPDX-FileCopyrightText: Copyright The Thingsboard Authors +// SPDX-License-Identifier: Apache-2.0 package org.thingsboard.server.service.community_grant; import org.springframework.web.client.HttpStatusCodeException; diff --git a/application/src/main/java/org/thingsboard/server/service/community_grant/CommunityGrantLicenseClaimRequest.java b/application/src/main/java/org/thingsboard/server/service/community_grant/CommunityGrantLicenseClaimRequest.java index 364c29f3bb..080bc59393 100644 --- a/application/src/main/java/org/thingsboard/server/service/community_grant/CommunityGrantLicenseClaimRequest.java +++ b/application/src/main/java/org/thingsboard/server/service/community_grant/CommunityGrantLicenseClaimRequest.java @@ -1,3 +1,5 @@ +// SPDX-FileCopyrightText: Copyright The Thingsboard Authors +// SPDX-License-Identifier: Apache-2.0 package org.thingsboard.server.service.community_grant; public record CommunityGrantLicenseClaimRequest(String claimToken) { diff --git a/application/src/main/java/org/thingsboard/server/service/community_grant/CommunityGrantLicenseClaimResponse.java b/application/src/main/java/org/thingsboard/server/service/community_grant/CommunityGrantLicenseClaimResponse.java index 1870277deb..77a6ff114b 100644 --- a/application/src/main/java/org/thingsboard/server/service/community_grant/CommunityGrantLicenseClaimResponse.java +++ b/application/src/main/java/org/thingsboard/server/service/community_grant/CommunityGrantLicenseClaimResponse.java @@ -1,3 +1,5 @@ +// SPDX-FileCopyrightText: Copyright The Thingsboard Authors +// SPDX-License-Identifier: Apache-2.0 package org.thingsboard.server.service.community_grant; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; From b8628b0c7562a47b45c38b87119ead9fb4a1aa77 Mon Sep 17 00:00:00 2001 From: Viacheslav Klimov Date: Mon, 28 Sep 2026 12:11:31 +0300 Subject: [PATCH 088/159] Bump io.netty from 4.1.137.Final to 4.1.138.Final to fix CVE-2026-93488, CVE-2026-93491, and 4 others --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index db90bce5f5..304e1874e2 100755 --- a/pom.xml +++ b/pom.xml @@ -69,7 +69,7 @@ entries below once TB migrates its tests off the deprecated @SpyBean/@MockBean to @MockitoSpyBean/@MockitoBean. --> 3.5.13 3.18.0 - 4.1.137.Final + 4.1.138.Final 10.1.59 5.4.3 1.5.38 From b4f24ac998f6a9231585aadbe66da256e13741b8 Mon Sep 17 00:00:00 2001 From: Viacheslav Klimov Date: Mon, 28 Sep 2026 12:11:31 +0300 Subject: [PATCH 089/159] Bump jackson-bom from 2.21.6 to 2.21.7 to fix CVE-2026-89425 and CVE-2026-91777 --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index 304e1874e2..d407c6abdd 100755 --- a/pom.xml +++ b/pom.xml @@ -73,7 +73,7 @@ 10.1.59 5.4.3 1.5.38 - 2.21.6 + 2.21.7 42.7.12 5.34.0 5.6.4 From b3930b66921aeca13a9bedaf42a1e9244001dc14 Mon Sep 17 00:00:00 2001 From: Viacheslav Klimov Date: Mon, 28 Sep 2026 12:11:31 +0300 Subject: [PATCH 090/159] Bump zookeeper from 3.9.5 to 3.9.6 to fix CVE-2026-59969 and CVE-2026-84439 --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index d407c6abdd..31053c56e9 100755 --- a/pom.xml +++ b/pom.xml @@ -98,7 +98,7 @@ 2.0.0-M15 2.0.1 5.6.0 - 3.9.5 + 3.9.6 3.25.5 1.76.0 1.2.10 From c24219461ae6cd050d7e4b12558d2ac65481da65 Mon Sep 17 00:00:00 2001 From: Viacheslav Klimov Date: Mon, 28 Sep 2026 12:11:31 +0300 Subject: [PATCH 091/159] Bump freemarker from 2.3.34 to 2.3.35 to fix CVE-2026-84939 --- pom.xml | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/pom.xml b/pom.xml index 31053c56e9..76920fadeb 100755 --- a/pom.xml +++ b/pom.xml @@ -78,6 +78,7 @@ 5.34.0 5.6.4 1.5.7-14 + 2.3.35 2.4.0-b180830.0359 0.12.5 0.10 @@ -1122,6 +1123,13 @@ ${zstd-jni.version} + + + org.freemarker + freemarker + ${freemarker.version} + + org.springframework.boot spring-boot-dependencies From b844395c32a4e86693acdce866fc2aee4b6199ec Mon Sep 17 00:00:00 2001 From: Viacheslav Klimov Date: Mon, 28 Sep 2026 18:13:22 +0300 Subject: [PATCH 092/159] Remove unused controller --- .../CommunityGrantTestResetController.java | 74 ------------------- 1 file changed, 74 deletions(-) delete mode 100644 application/src/main/java/org/thingsboard/server/controller/CommunityGrantTestResetController.java diff --git a/application/src/main/java/org/thingsboard/server/controller/CommunityGrantTestResetController.java b/application/src/main/java/org/thingsboard/server/controller/CommunityGrantTestResetController.java deleted file mode 100644 index 65a1f61362..0000000000 --- a/application/src/main/java/org/thingsboard/server/controller/CommunityGrantTestResetController.java +++ /dev/null @@ -1,74 +0,0 @@ -// SPDX-FileCopyrightText: Copyright The Thingsboard Authors -// SPDX-License-Identifier: Apache-2.0 -package org.thingsboard.server.controller; - -import lombok.RequiredArgsConstructor; -import lombok.extern.slf4j.Slf4j; -import org.springframework.jdbc.core.JdbcTemplate; -import org.springframework.security.access.prepost.PreAuthorize; -import org.springframework.web.bind.annotation.PostMapping; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestParam; -import org.springframework.web.bind.annotation.ResponseBody; -import org.springframework.web.bind.annotation.RestController; -import org.thingsboard.server.common.data.community_grant.CommunityGrantStateInfo; -import org.thingsboard.server.common.data.id.TenantId; -import org.thingsboard.server.config.annotations.ApiOperation; -import org.thingsboard.server.dao.settings.AdminSettingsService; -import org.thingsboard.server.dao.subscription.TbClusterStore; -import org.thingsboard.server.queue.util.TbCoreComponent; -import org.thingsboard.server.service.community_grant.CommunityGrantFlowStateStore; -import org.thingsboard.server.service.community_grant.CommunityGrantOfflineReportStore; -import org.thingsboard.server.service.community_grant.CommunityGrantPoller; -import org.thingsboard.server.service.community_grant.CommunityGrantService; - -import java.util.UUID; - -/** FIXME: delete this whole class before merge. Test-only reset that makes the enrollment flow re-runnable. */ -@RestController -@TbCoreComponent -@RequestMapping("/api/communityGrant/test") -@RequiredArgsConstructor -@Slf4j -public class CommunityGrantTestResetController extends BaseController { - - private final JdbcTemplate jdbcTemplate; - private final TbClusterStore tbClusterStore; - private final AdminSettingsService adminSettingsService; - private final CommunityGrantOfflineReportStore offlineReportStore; - private final CommunityGrantPoller poller; - private final CommunityGrantService communityGrantService; - - // The poller is stopped first, so a tick in flight cannot write the enrollment back after the reset. - @ApiOperation(value = "Reset the community grant enrollment (testing only)", - notes = "Discards this deployment's claim token, its persisted community grant flow and the last " - + "offline report, and mints a new cluster id so the portal sees an installation it has " - + "never registered. Available for users with 'SYS_ADMIN' authority.") - @PreAuthorize("hasAuthority('SYS_ADMIN')") - @PostMapping("/reset") - @ResponseBody - public CommunityGrantTestResetResult reset(@RequestParam(defaultValue = "true") boolean newClusterId) { - poller.disarm(); - tbClusterStore.forceClearLicenseClaimToken(); - offlineReportStore.clear(); - adminSettingsService.deleteAdminSettingsByTenantIdAndKey(TenantId.SYS_TENANT_ID, - CommunityGrantFlowStateStore.SETTINGS_KEY); - adminSettingsService.deleteAdminSettingsByTenantIdAndKey(TenantId.SYS_TENANT_ID, - CommunityGrantOfflineReportStore.SETTINGS_KEY); - UUID clusterId = newClusterId ? mintClusterId() : tbClusterStore.getClusterId().orElse(null); - log.warn("Community grant enrollment reset by the test endpoint. Cluster id is now {}", clusterId); - return new CommunityGrantTestResetResult(clusterId, communityGrantService.getStateInfo()); - } - - private UUID mintClusterId() { - UUID clusterId = UUID.randomUUID(); - if (jdbcTemplate.update("UPDATE tb_cluster SET cluster_id = ?::uuid", clusterId.toString()) == 0) { - jdbcTemplate.update("INSERT INTO tb_cluster (cluster_id) VALUES (?::uuid)", clusterId.toString()); - } - return clusterId; - } - - public record CommunityGrantTestResetResult(UUID clusterId, CommunityGrantStateInfo state) { - } - -} From f2053b3bd663e721b800b79527534bde013af1c2 Mon Sep 17 00:00:00 2001 From: Nikita Mazurenko Date: Mon, 28 Sep 2026 17:39:48 +0200 Subject: [PATCH 093/159] Persist cloud RPC deletes for offline edges, accept post-TIMEOUT retries and parse edge RPC responses safely --- .../server/controller/RpcV2Controller.java | 2 +- .../processor/device/DeviceEdgeProcessor.java | 36 +++++++++++-------- .../server/service/rpc/TbRpcService.java | 20 ++++++----- .../server/common/data/rpc/RpcStatus.java | 5 +++ 4 files changed, 39 insertions(+), 24 deletions(-) diff --git a/application/src/main/java/org/thingsboard/server/controller/RpcV2Controller.java b/application/src/main/java/org/thingsboard/server/controller/RpcV2Controller.java index fc6e93afe1..fefec61c22 100644 --- a/application/src/main/java/org/thingsboard/server/controller/RpcV2Controller.java +++ b/application/src/main/java/org/thingsboard/server/controller/RpcV2Controller.java @@ -228,7 +228,7 @@ public class RpcV2Controller extends AbstractRpcController { tbClusterService.pushMsgToCore(removeMsg, null); } - tbRpcService.deleteRpc(getTenantId(), rpcId); + tbRpcService.deleteRpc(getTenantId(), rpc); rpc.setStatus(RpcStatus.DELETED); TbMsg msg = TbMsg.newMsg() 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 0362d40e45..7ad1125533 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 @@ -142,33 +142,39 @@ public class DeviceEdgeProcessor extends BaseDeviceProcessor implements DevicePr private ListenableFuture processDeviceRpcStatusFromEdge(TenantId tenantId, Edge edge, DeviceRpcCallMsg deviceRpcCallMsg) { RpcId rpcId = new RpcId(new UUID(deviceRpcCallMsg.getRequestUuidMSB(), deviceRpcCallMsg.getRequestUuidLSB())); + Rpc existingRpc = edgeCtx.getTbRpcService().findRpcById(tenantId, rpcId); + if (existingRpc == null) { + // RPC is unknown to the cloud (edge-originated or already deleted) - nothing to sync + log.debug("[{}][{}] Ignoring RPC status [{}] from edge - RPC not found", tenantId, rpcId, deviceRpcCallMsg.getRpcStatus()); + return Futures.immediateFuture(null); + } if (RpcStatus.DELETED.name().equals(deviceRpcCallMsg.getRpcStatus())) { // RPC v2 (persistent) delete/abort propagation Edge -> Cloud: remove the cloud copy. // Mark the edge-sync context so TbRpcService.deleteRpc does not echo the delete back to edges. - if (edgeCtx.getTbRpcService().findRpcById(tenantId, rpcId) != null) { - try { - edgeSynchronizationManager.getEdgeId().set(edge.getId()); - edgeCtx.getTbRpcService().deleteRpc(tenantId, rpcId); - } finally { - edgeSynchronizationManager.getEdgeId().remove(); - } + try { + edgeSynchronizationManager.getEdgeId().set(edge.getId()); + edgeCtx.getTbRpcService().deleteRpc(tenantId, existingRpc); + } finally { + edgeSynchronizationManager.getEdgeId().remove(); } return Futures.immediateFuture(null); } RpcStatus rpcStatus = RpcStatus.valueOf(deviceRpcCallMsg.getRpcStatus()); - Rpc existingRpc = edgeCtx.getTbRpcService().findRpcById(tenantId, rpcId); - if (existingRpc == null) { - return Futures.immediateFuture(null); - } - if (!existingRpc.getStatus().isIntermediate() && rpcStatus.isIntermediate()) { - // guard against out-of-order status uplinks regressing a terminal RPC (e.g. stale DELIVERED after SUCCESSFUL) - log.debug("[{}][{}] Ignoring stale RPC status [{}] - RPC is already terminal [{}]", + if (!existingRpc.getStatus().isIntermediate() && existingRpc.getStatus() != RpcStatus.TIMEOUT && rpcStatus.isIntermediate()) { + // guard against a final RPC regressing to an intermediate status (e.g. stale DELIVERED after SUCCESSFUL). + // TIMEOUT is not final - the device actor retries the delivery (TIMEOUT -> SENT/DELIVERED/QUEUED). + log.debug("[{}][{}] Ignoring stale RPC status [{}] - RPC is already final [{}]", tenantId, rpcId, rpcStatus, existingRpc.getStatus()); return Futures.immediateFuture(null); } JsonNode response = null; if (deviceRpcCallMsg.hasResponseMsg() && !StringUtils.isEmpty(deviceRpcCallMsg.getResponseMsg().getResponse())) { - response = JacksonUtil.toJsonNode(deviceRpcCallMsg.getResponseMsg().getResponse()); + String payload = deviceRpcCallMsg.getResponseMsg().getResponse(); + try { + response = JacksonUtil.toJsonNode(payload); + } catch (IllegalArgumentException e) { + response = JacksonUtil.newObjectNode().put("error", payload); + } } edgeCtx.getTbRpcService().save(tenantId, rpcId, rpcStatus, response); return Futures.immediateFuture(null); diff --git a/application/src/main/java/org/thingsboard/server/service/rpc/TbRpcService.java b/application/src/main/java/org/thingsboard/server/service/rpc/TbRpcService.java index 57322f5600..b0a6a490ee 100644 --- a/application/src/main/java/org/thingsboard/server/service/rpc/TbRpcService.java +++ b/application/src/main/java/org/thingsboard/server/service/rpc/TbRpcService.java @@ -24,7 +24,7 @@ import org.thingsboard.server.common.data.rpc.Rpc; import org.thingsboard.server.common.data.rpc.RpcStatus; import org.thingsboard.server.common.msg.TbMsg; import org.thingsboard.server.common.msg.TbMsgMetaData; -import org.thingsboard.server.common.msg.edge.EdgeHighPriorityMsg; +import org.thingsboard.server.dao.edge.EdgeEventService; import org.thingsboard.server.dao.edge.EdgeService; import org.thingsboard.server.dao.edge.EdgeSynchronizationManager; import org.thingsboard.server.dao.rpc.RpcService; @@ -40,6 +40,7 @@ public class TbRpcService { private final RpcService rpcService; private final TbClusterService tbClusterService; private final EdgeService edgeService; + private final EdgeEventService edgeEventService; private final EdgeSynchronizationManager edgeSynchronizationManager; public Rpc save(TenantId tenantId, Rpc rpc) { @@ -80,12 +81,14 @@ public class TbRpcService { return rpcService.findAllByDeviceIdAndStatus(tenantId, deviceId, rpcStatus, pageLink); } - public void deleteRpc(TenantId tenantId, RpcId rpcId) { - Rpc rpc = rpcService.findById(tenantId, rpcId); - rpcService.deleteRpc(tenantId, rpcId); - // RPC v2 (persistent) delete/abort propagation Cloud -> Edge for ANY status. - // Skipped when the delete originated from an edge (edge-sync context) so it is not echoed back. - if (rpc != null && edgeSynchronizationManager.getEdgeId().get() == null) { + /** + * The only edge-aware RPC delete: propagates the delete to related edges (Cloud -> Edge) for ANY status. + * Other delete paths (RpcService.deleteRpc, TTL clean-up) intentionally do not sync, so each side expires its own copies. + */ + public void deleteRpc(TenantId tenantId, Rpc rpc) { + rpcService.deleteRpc(tenantId, rpc.getId()); + // skipped when the delete originated from an edge (edge-sync context) so it is not echoed back + if (edgeSynchronizationManager.getEdgeId().get() == null) { pushRpcDeleteToEdges(tenantId, rpc); } } @@ -99,9 +102,10 @@ public class TbRpcService { body.put("requestUUID", rpc.getId().getId().toString()); body.put("rpcStatus", RpcStatus.DELETED.name()); for (EdgeId edgeId : relatedEdgeIds) { + // persisted (not high-priority) so the delete is replayed when the edge reconnects EdgeEvent edgeEvent = EdgeUtils.constructEdgeEvent(tenantId, edgeId, EdgeEventType.DEVICE, EdgeEventActionType.RPC_CALL, rpc.getDeviceId(), body); - tbClusterService.onEdgeHighPriorityMsg(new EdgeHighPriorityMsg(tenantId, edgeEvent)); + edgeEventService.saveAsync(edgeEvent); } } diff --git a/common/data/src/main/java/org/thingsboard/server/common/data/rpc/RpcStatus.java b/common/data/src/main/java/org/thingsboard/server/common/data/rpc/RpcStatus.java index f80ad59c35..5a6b04f1ac 100644 --- a/common/data/src/main/java/org/thingsboard/server/common/data/rpc/RpcStatus.java +++ b/common/data/src/main/java/org/thingsboard/server/common/data/rpc/RpcStatus.java @@ -15,6 +15,11 @@ public enum RpcStatus { FAILED(false), DELETED(false); + /** + * {@code true} while the RPC is still pending in the device actor (not yet delivered/answered). + * Note: TIMEOUT is not intermediate, but it is not final either - the device actor may retry + * the delivery (TIMEOUT -> SENT/DELIVERED/QUEUED) until retries are exhausted (then FAILED). + */ @Getter private final boolean intermediate; From 45102bc728d429cba6b031328c24aa73969662cb Mon Sep 17 00:00:00 2001 From: Nikita Mazurenko Date: Mon, 28 Sep 2026 17:39:48 +0200 Subject: [PATCH 094/159] Add edge tests for persistent RPC status and delete sync --- .../server/edge/DeviceEdgeTest.java | 119 ++++++++++++++++++ 1 file changed, 119 insertions(+) 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 070eda60d5..9137724ef8 100644 --- a/application/src/test/java/org/thingsboard/server/edge/DeviceEdgeTest.java +++ b/application/src/test/java/org/thingsboard/server/edge/DeviceEdgeTest.java @@ -38,14 +38,18 @@ import org.thingsboard.server.common.data.id.CustomerId; import org.thingsboard.server.common.data.id.DeviceId; import org.thingsboard.server.common.data.id.EdgeId; import org.thingsboard.server.common.data.id.EntityId; +import org.thingsboard.server.common.data.id.RpcId; import org.thingsboard.server.common.data.ota.OtaPackageType; import org.thingsboard.server.common.data.page.PageData; import org.thingsboard.server.common.data.page.PageLink; +import org.thingsboard.server.common.data.rpc.Rpc; +import org.thingsboard.server.common.data.rpc.RpcStatus; import org.thingsboard.server.common.data.security.DeviceCredentials; import org.thingsboard.server.common.data.security.DeviceCredentialsType; import org.thingsboard.server.common.data.tenant.profile.DefaultTenantProfileConfiguration; import org.thingsboard.server.common.msg.session.FeatureType; import org.thingsboard.server.dao.edge.EdgeService; +import org.thingsboard.server.dao.rpc.RpcService; import org.thingsboard.server.dao.service.DaoSqlTest; import org.thingsboard.server.gen.edge.v1.AttributesRequestMsg; import org.thingsboard.server.gen.edge.v1.DeviceCredentialsRequestMsg; @@ -94,6 +98,9 @@ public class DeviceEdgeTest extends AbstractEdgeTest { @Autowired protected EdgeService edgeService; + @Autowired + protected RpcService rpcService; + @Test public void testDevices() throws Exception { // create device and assign to edge; update device @@ -657,6 +664,118 @@ public class DeviceEdgeTest extends AbstractEdgeTest { Assert.assertEquals(2, latestDeviceRpcCallMsg.getRetries()); } + @Test + public void testRpcV2StatusUpdateFromEdge() throws Exception { + Device device = findDeviceByName("Edge Device 1"); + Rpc rpc = savePersistentRpc(device, RpcStatus.QUEUED); + + sendRpcStatusUplink(device, rpc.getId(), RpcStatus.DELIVERED, null); + Assert.assertEquals(RpcStatus.DELIVERED, getPersistentRpc(rpc.getId()).getStatus()); + + sendRpcStatusUplink(device, rpc.getId(), RpcStatus.SUCCESSFUL, "{\"result\":\"ok\"}"); + Rpc successful = getPersistentRpc(rpc.getId()); + Assert.assertEquals(RpcStatus.SUCCESSFUL, successful.getStatus()); + Assert.assertEquals("ok", successful.getResponse().get("result").asText()); + + // stale intermediate status must not regress a final RPC + sendRpcStatusUplink(device, rpc.getId(), RpcStatus.DELIVERED, null); + Assert.assertEquals(RpcStatus.SUCCESSFUL, getPersistentRpc(rpc.getId()).getStatus()); + } + + @Test + public void testRpcV2StatusRetryAfterTimeoutFromEdge() throws Exception { + Device device = findDeviceByName("Edge Device 1"); + Rpc rpc = savePersistentRpc(device, RpcStatus.SENT); + + // TIMEOUT with retries left is followed by a re-delivery + sendRpcStatusUplink(device, rpc.getId(), RpcStatus.TIMEOUT, null); + Assert.assertEquals(RpcStatus.TIMEOUT, getPersistentRpc(rpc.getId()).getStatus()); + + sendRpcStatusUplink(device, rpc.getId(), RpcStatus.SENT, null); + Assert.assertEquals(RpcStatus.SENT, getPersistentRpc(rpc.getId()).getStatus()); + } + + @Test + public void testRpcV2NonJsonResponseFromEdge() throws Exception { + Device device = findDeviceByName("Edge Device 1"); + Rpc rpc = savePersistentRpc(device, RpcStatus.DELIVERED); + + sendRpcStatusUplink(device, rpc.getId(), RpcStatus.SUCCESSFUL, "not a json"); + Rpc successful = getPersistentRpc(rpc.getId()); + Assert.assertEquals(RpcStatus.SUCCESSFUL, successful.getStatus()); + Assert.assertEquals("not a json", successful.getResponse().get("error").asText()); + } + + @Test + public void testRpcV2StatusForUnknownRpcFromEdge() throws Exception { + Device device = findDeviceByName("Edge Device 1"); + RpcId unknownRpcId = new RpcId(Uuids.timeBased()); + + sendRpcStatusUplink(device, unknownRpcId, RpcStatus.DELIVERED, null); + doGet("/api/rpc/persistent/" + unknownRpcId.getId()).andExpect(status().isNotFound()); + } + + @Test + public void testRpcV2DeleteFromEdge() throws Exception { + Device device = findDeviceByName("Edge Device 1"); + Rpc rpc = savePersistentRpc(device, RpcStatus.DELIVERED); + + edgeImitator.expectMessageAmount(1); + sendRpcStatusUplink(device, rpc.getId(), RpcStatus.DELETED, null); + doGet("/api/rpc/persistent/" + rpc.getUuidId()).andExpect(status().isNotFound()); + // delete originated from the edge must not be echoed back + Assert.assertFalse(edgeImitator.waitForMessages(1)); + } + + @Test + public void testRpcV2DeleteFromCloud() throws Exception { + Device device = findDeviceByName("Edge Device 1"); + Rpc rpc = savePersistentRpc(device, RpcStatus.SUCCESSFUL); + + edgeImitator.expectMessageAmount(1); + doDelete("/api/rpc/persistent/" + rpc.getUuidId()).andExpect(status().isOk()); + Assert.assertTrue(edgeImitator.waitForMessages()); + + AbstractMessage latestMessage = edgeImitator.getLatestMessage(); + Assert.assertTrue(latestMessage instanceof DeviceRpcCallMsg); + DeviceRpcCallMsg deviceRpcCallMsg = (DeviceRpcCallMsg) latestMessage; + Assert.assertEquals(RpcStatus.DELETED.name(), deviceRpcCallMsg.getRpcStatus()); + Assert.assertEquals(rpc.getUuidId(), new UUID(deviceRpcCallMsg.getRequestUuidMSB(), deviceRpcCallMsg.getRequestUuidLSB())); + Assert.assertFalse(deviceRpcCallMsg.hasRequestMsg()); + Assert.assertFalse(deviceRpcCallMsg.hasResponseMsg()); + } + + private Rpc savePersistentRpc(Device device, RpcStatus status) { + Rpc rpc = new Rpc(new RpcId(Uuids.timeBased())); + rpc.setTenantId(tenantId); + rpc.setDeviceId(device.getId()); + rpc.setExpirationTime(System.currentTimeMillis() + TimeUnit.MINUTES.toMillis(1)); + rpc.setRequest(JacksonUtil.newObjectNode().put("method", "test_method")); + rpc.setStatus(status); + return rpcService.save(rpc); + } + + private Rpc getPersistentRpc(RpcId rpcId) throws Exception { + return doGet("/api/rpc/persistent/" + rpcId.getId(), Rpc.class); + } + + private void sendRpcStatusUplink(Device device, RpcId rpcId, RpcStatus rpcStatus, String response) throws Exception { + DeviceRpcCallMsg.Builder builder = DeviceRpcCallMsg.newBuilder() + .setDeviceIdMSB(device.getUuidId().getMostSignificantBits()) + .setDeviceIdLSB(device.getUuidId().getLeastSignificantBits()) + .setRequestUuidMSB(rpcId.getId().getMostSignificantBits()) + .setRequestUuidLSB(rpcId.getId().getLeastSignificantBits()) + .setRpcStatus(rpcStatus.name()); + if (response != null) { + builder.setResponseMsg(RpcResponseMsg.newBuilder().setResponse(response).build()); + } + UplinkMsg uplinkMsg = UplinkMsg.newBuilder().addDeviceRpcCallMsg(builder.build()).build(); + + edgeImitator.expectResponsesAmount(1); + edgeImitator.sendUplinkMsg(uplinkMsg); + Assert.assertTrue(edgeImitator.waitForResponses()); + } + private void sendAttributesRequestAndVerify(Device device, String scope, String attributesDataStr, String expectedKey, String expectedValue) throws Exception { JsonNode attributesData = JacksonUtil.toJsonNode(attributesDataStr); From 24c294fa357c813e1f4baa24b412bebc5592d89b Mon Sep 17 00:00:00 2001 From: Dmytro Skarzhynets Date: Tue, 29 Sep 2026 12:41:46 +0300 Subject: [PATCH 095/159] chore: move license header template out of repository root --- pom.xml | 2 +- .../main/python/license-headers/templates/license-header.txt | 0 2 files changed, 1 insertion(+), 1 deletion(-) rename license-header.txt => tools/src/main/python/license-headers/templates/license-header.txt (100%) diff --git a/pom.xml b/pom.xml index 76920fadeb..e8f42b3243 100755 --- a/pom.xml +++ b/pom.xml @@ -891,7 +891,7 @@ -
    ${main.dir}/license-header.txt
    +
    ${main.dir}/tools/src/main/python/license-headers/templates/license-header.txt
    **/.env **/*.env diff --git a/license-header.txt b/tools/src/main/python/license-headers/templates/license-header.txt similarity index 100% rename from license-header.txt rename to tools/src/main/python/license-headers/templates/license-header.txt From ca95ecd4423292cae76372f3259bef6d22ae3df0 Mon Sep 17 00:00:00 2001 From: dshvaika Date: Tue, 29 Sep 2026 13:40:19 +0300 Subject: [PATCH 096/159] feat(iot-hub): show the search popup as one ranked list MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The popup asked /api/versions/published/grouped and rendered one section per item type, so a query answered best by a widget still opened on devices. It now asks for page 0 of the flat read the search page makes (relevance sort, 10 rows) and renders those rows in the server's order, so the best match leads whatever its type. - Each row names its type before the author ("Widget · pinkevych.d"), in the type's colour with its itemTypeIcons icon. The verified mark moves in front of the author like on the item cards; an unverified author keeps the person icon. - Items without a screenshot (calculated fields, alarm rules, rule chains) sit in the same 99x56 frame as a screenshot with a 36px coloured tile inside, so names line up down the list. - The footer says "See all N results for ..." when the search matched more than the popup shows; N discounts the rows this page dropped (dashboards). - itemTypeColors joins itemTypeIcons as the one type palette; the hero reads it instead of repeating the six colours. Removes getPublishedVersionsGrouped, MpItemVersionGroupedQuery, MpItemVersionSection and the iot-hub.section-more key. --- .../src/app/core/http/iot-hub-api.service.ts | 16 --- .../pages/iot-hub/iot-hub-home.component.html | 67 ++++++----- .../pages/iot-hub/iot-hub-home.component.scss | 112 +++++++++--------- .../pages/iot-hub/iot-hub-home.component.ts | 100 +++++++--------- .../models/iot-hub/iot-hub-item.models.ts | 15 +++ .../models/iot-hub/iot-hub-version.models.ts | 38 ------ .../assets/locale/locale.constant-en_US.json | 2 +- 7 files changed, 151 insertions(+), 199 deletions(-) diff --git a/ui-ngx/src/app/core/http/iot-hub-api.service.ts b/ui-ngx/src/app/core/http/iot-hub-api.service.ts index 7f3b299962..c5037048fb 100644 --- a/ui-ngx/src/app/core/http/iot-hub-api.service.ts +++ b/ui-ngx/src/app/core/http/iot-hub-api.service.ts @@ -7,10 +7,8 @@ import { Observable } from 'rxjs'; import { PageData } from '@shared/models/page/page-data'; import { PageLink } from '@shared/models/page/page-link'; import { - MpItemVersionGroupedQuery, MpItemVersionQuery, MpItemVersionQueryOptions, - MpItemVersionSection, MpItemVersionView } from '@shared/models/iot-hub/iot-hub-version.models'; import { CreatorView } from '@shared/models/iot-hub/iot-hub-creator.models'; @@ -82,20 +80,6 @@ export class IotHubApiService { ); } - /** - * The sectioned answer: one section per item type, in the server's order, each capped by the - * server and carrying the total behind that cap. Its own endpoint, which takes no page, page - * size or sort direction. - */ - public getPublishedVersionsGrouped(query: MpItemVersionGroupedQuery, - config?: IotHubRequestConfig): Observable { - this.applyPlatformFilters(query.options); - return this.http.get( - `${this.baseUrl}/api/versions/published/grouped${query.toQuery()}`, - { params: this.buildParams(config) } - ); - } - /** * What this platform can install, filled in for a caller that did not say: items built for a * newer ThingsBoard, and PE-only items on a CE instance, cannot be installed from here. diff --git a/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-home.component.html b/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-home.component.html index 564f89ca46..5963c9e536 100644 --- a/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-home.component.html +++ b/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-home.component.html @@ -72,7 +72,7 @@ - } @else if (searchResultGroups.length === 0 && searchLoaded) { + } @else if (searchResults.length === 0 && searchLoaded) {
    search_off @@ -84,48 +84,53 @@
    } @else { - @for (group of searchResultGroups; track group.type) { - - {{ getSearchGroupLabel(group.type) }} - @if (group.remaining > 0) { - - {{ 'iot-hub.section-more' | translate:{ count: group.remaining } }} - chevron_right - - } - - @for (item of group.items; track item.id) { - + @for (item of searchResults; track item.id) { + + +
    @if (isCompactType(item.type)) {
    {{ getCompactIcon(item) }}
    + } @else if (getItemImage(item); as imgUrl) { + } @else { -
    - @if (getItemImage(item); as imgUrl) { - - } @else { - {{ getItemTypeIcon(item.type) }} - } -
    + {{ getItemTypeIcon(item.type) }} } -
    - {{ item.name }} - - person - {{ item.creatorDisplayName }} +
    +
    + {{ item.name }} + + + + {{ getItemTypeIcon(item.type) }} + {{ getItemTypeLabel(item.type) }} -
    - - } + @if (item.creatorDisplayName) { + + @if (item.creatorVerified) { + verified + } @else { + person + } + {{ item.creatorDisplayName }} + + } + +
    +
    } } @if (searchText?.trim(); as query) { - {{ 'iot-hub.see-results-for' | translate:{ search: query } }} + @if (searchTotal > searchResults.length) { + {{ 'iot-hub.see-all-results-for' | translate:{ count: searchTotal, search: query } }} + } @else { + {{ 'iot-hub.see-results-for' | translate:{ search: query } }} + } } @else { {{ 'iot-hub.see-all-results' | translate }} } diff --git a/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-home.component.scss b/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-home.component.scss index 8a89ebae44..157d6e1faf 100644 --- a/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-home.component.scss +++ b/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-home.component.scss @@ -241,53 +241,6 @@ } } - // Section header — an option like every other row, not a button beside them, so the arrow keys - // reach it and a screen reader reads it in the list. It IS the way into the type page: title - // left, how much is not shown plus a chevron right. There is deliberately no per-section - // "see all" row under the items; six of those on one panel is what this variant avoids. - // Design: 14px Medium, 0.25 tracking, black-tertiary, 4px V / 16px H, 12px above each section. - .mat-mdc-option.tb-search-popup-group-header { - padding: 4px 16px; - min-height: 28px; - margin-top: 12px; - - &:first-child { - margin-top: 0; - } - - .mdc-list-item__primary-text { - justify-content: space-between; - } - } - - .tb-search-popup-group-label { - font-size: 14px; - font-weight: 500; - line-height: 20px; - letter-spacing: 0.25px; - color: rgba(0, 0, 0, 0.54); - white-space: nowrap; - } - - .tb-search-popup-group-more { - display: flex; - align-items: center; - gap: 2px; - flex-shrink: 0; - font-size: 12px; - font-weight: 500; - line-height: 16px; - letter-spacing: 0.25px; - color: $tb-primary-color; - - .mat-icon { - width: 18px; - height: 18px; - font-size: 18px; - line-height: 18px; - } - } - // Item row — Design: 8px V / 16px H, 16px gap, centered .mat-mdc-option.tb-search-popup-item { padding: 8px 16px; @@ -322,11 +275,11 @@ color: rgba(0, 0, 0, 0.38); } - // Icon square — Design: 56x56, 4.667px radius, colored bg + // Icon tile for an item with no screenshot, centred in the thumbnail frame: 36x36, colored bg .tb-search-popup-icon-square { - width: 56px; - height: 56px; - border-radius: 4.667px; + width: 36px; + height: 36px; + border-radius: 6px; flex-shrink: 0; display: flex; align-items: center; @@ -334,9 +287,9 @@ } .tb-search-popup-icon-inner { - font-size: 28px; - width: 28px; - height: 28px; + font-size: 22px; + width: 22px; + height: 22px; color: white !important; --tb-icon-color: white; } @@ -373,13 +326,64 @@ letter-spacing: 0.25px; color: rgba(0, 0, 0, 0.54); white-space: nowrap; + min-width: 0; mat-icon { + flex-shrink: 0; font-size: 16px; width: 16px; height: 16px; margin-right: 0; color: rgba(0, 0, 0, 0.54); + + // Same teal the IoT Hub item cards give a verified creator. + &.tb-search-popup-verified { + color: #00695c; + } + } + } + + // Shares the meta row with the item type, so a long name is cut rather than overflowing. + .tb-search-popup-author-name { + overflow: hidden; + text-overflow: ellipsis; + } + + // Meta row: the item type, a middle dot, then the author - "Widget · pinkevych.d". + .tb-search-popup-meta { + display: flex; + align-items: center; + gap: 4px; + min-width: 0; + } + + // Item type in its own colour, darkened so the paler ones (rule chain, calculated field) stay + // legible as text. + .tb-search-popup-type { + display: flex; + align-items: center; + gap: 4px; + flex-shrink: 0; + font-size: 12px; + font-weight: 500; + line-height: 16px; + letter-spacing: 0.25px; + color: color-mix(in srgb, var(--tb-search-popup-type-color, #5f6368) 75%, #000); + white-space: nowrap; + + tb-icon { + font-size: 14px; + width: 14px; + height: 14px; + line-height: 14px; + color: inherit; + } + + // No author, nothing to separate from. + &:not(:last-child)::after { + content: '·'; + font-weight: 700; + color: rgba(0, 0, 0, 0.54); } } diff --git a/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-home.component.ts b/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-home.component.ts index cf242faeb3..c7c6a9ad07 100644 --- a/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-home.component.ts +++ b/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-home.component.ts @@ -10,16 +10,14 @@ import { catchError, debounceTime, distinctUntilChanged, switchMap } from 'rxjs/ import { MediaBreakpoints } from '@shared/models/constants'; import { PageLink } from '@shared/models/page/page-link'; import { Direction, SortOrder } from '@shared/models/page/sort-order'; -import { - MpItemVersionGroupedQuery, - MpItemVersionQuery, - MpItemVersionSection, - MpItemVersionView -} from '@shared/models/iot-hub/iot-hub-version.models'; +import { PageData } from '@shared/models/page/page-data'; +import { MpItemVersionQuery, MpItemVersionView } from '@shared/models/iot-hub/iot-hub-version.models'; import { CROSS_TYPE_ITEM_TYPES, + getItemTypeColor, getItemTypeIcon, ItemType, + itemTypeColors, itemTypeTranslations, RELEVANCE_SORT_PROPERTY } from '@shared/models/iot-hub/iot-hub-item.models'; @@ -44,12 +42,11 @@ interface HeroTypeConfig { icon: string; } -interface SearchResultGroup { - type: ItemType; - items: MpItemVersionView[]; - /** How many rows of this type the header offers beyond the ones shown. Zero renders no "+N more". */ - remaining: number; -} +/** + * Rows the search popup shows: the first page of the search page's own request, so the popup is + * a preview of what "See results for ..." opens on. + */ +const SEARCH_POPUP_PAGE_SIZE = 10; @Component({ selector: 'tb-iot-hub-home', @@ -62,7 +59,13 @@ export class TbIotHubHomeComponent implements OnInit, OnDestroy { readonly ItemType = ItemType; searchText = ''; - searchResultGroups: SearchResultGroup[] = []; + searchResults: MpItemVersionView[] = []; + /** + * What the footer's "See all N results" counts: the matches less the rows this page dropped, so + * a panel that shows everything it can open never claims more. Rows beyond this page that the + * panel could not show are still counted - only this page's drops are known. + */ + searchTotal = 0; searchLoaded = false; searchLoading = false; @ViewChild(MatAutocompleteTrigger) searchAutoTrigger: MatAutocompleteTrigger; @@ -74,27 +77,27 @@ export class TbIotHubHomeComponent implements OnInit, OnDestroy { heroTypes: HeroTypeConfig[] = [ { - type: ItemType.DEVICE, labelKey: 'item.type-device-plural', color: '#4b63cc', + type: ItemType.DEVICE, labelKey: 'item.type-device-plural', color: itemTypeColors[ItemType.DEVICE], icon: 'assets/iot-hub/hero-device-cluster.svg' }, { - type: ItemType.SOLUTION_TEMPLATE, labelKey: 'item.type-solution-template-plural', color: '#2b6bb4', + type: ItemType.SOLUTION_TEMPLATE, labelKey: 'item.type-solution-template-plural', color: itemTypeColors[ItemType.SOLUTION_TEMPLATE], icon: 'assets/iot-hub/hero-solution-template-cluster.svg' }, { - type: ItemType.WIDGET, labelKey: 'item.type-widget-plural', color: '#2c9755', + type: ItemType.WIDGET, labelKey: 'item.type-widget-plural', color: itemTypeColors[ItemType.WIDGET], icon: 'assets/iot-hub/hero-widget-cluster.svg' }, { - type: ItemType.CALCULATED_FIELD, labelKey: 'item.type-calculated-field-plural', color: '#3cb4e0', + type: ItemType.CALCULATED_FIELD, labelKey: 'item.type-calculated-field-plural', color: itemTypeColors[ItemType.CALCULATED_FIELD], icon: 'assets/iot-hub/hero-calculated-field-cluster.svg' }, { - type: ItemType.ALARM_RULE, labelKey: 'item.type-alarm-rule-plural', color: '#d66f2e', + type: ItemType.ALARM_RULE, labelKey: 'item.type-alarm-rule-plural', color: itemTypeColors[ItemType.ALARM_RULE], icon: 'assets/iot-hub/hero-alarm-rule-cluster.svg' }, { - type: ItemType.RULE_CHAIN, labelKey: 'item.type-rule-chain-plural', color: '#a95ae2', + type: ItemType.RULE_CHAIN, labelKey: 'item.type-rule-chain-plural', color: itemTypeColors[ItemType.RULE_CHAIN], icon: 'assets/iot-hub/hero-rule-chain-cluster.svg' } ]; @@ -166,18 +169,26 @@ export class TbIotHubHomeComponent implements OnInit, OnDestroy { switchMap(text => { this.searchLoading = true; const trimmed = text.trim(); + // One flat list ranked across every type, so the best match leads whatever its type. // Relevance in both states, the same value every other IoT Hub surface sends: with an // empty field the backend serves the install count under this key, so the panel opens on // popularity without this component having to know it. - const query = new MpItemVersionGroupedQuery({}, trimmed, RELEVANCE_SORT_PROPERTY); + const sortOrder: SortOrder = { property: RELEVANCE_SORT_PROPERTY, direction: Direction.DESC }; + const pageLink = new PageLink(SEARCH_POPUP_PAGE_SIZE, 0, trimmed || null, sortOrder); + const query = new MpItemVersionQuery(pageLink); // A failed request must not end the subscription: the interceptor reports it, and the // panel goes back to an empty answer the next keystroke can replace. - return this.iotHubApiService.getPublishedVersionsGrouped(query, { ignoreLoading: true }).pipe( - catchError(() => of([] as MpItemVersionSection[])) + return this.iotHubApiService.getPublishedVersions(query, { ignoreLoading: true }).pipe( + catchError(() => of({ data: [], totalElements: 0 } as PageData)) ); }) - ).subscribe(sections => { - this.searchResultGroups = this.toResultGroups(sections); + ).subscribe(page => { + // The platform publishes no dashboards, so a type this panel has no layout for is dropped; + // the popup then shows fewer rows rather than asking for more. + const data = page.data ?? []; + this.searchResults = data.filter(item => CROSS_TYPE_ITEM_TYPES.includes(item.type)); + this.searchTotal = Math.max(this.searchResults.length, + (page.totalElements ?? 0) - (data.length - this.searchResults.length)); this.searchLoaded = true; this.searchLoading = false; }); @@ -285,17 +296,6 @@ export class TbIotHubHomeComponent implements OnInit, OnDestroy { void this.router.navigate(['/iot-hub/search'], { queryParams: { search } }); } - /** - * The section header is the way into the rest of a type - the panel carries no per-section - * "see all" row, which would put six identical calls to action on one panel. The query goes - * with it, so the type page opens on the same search rather than on the whole type. - */ - navigateToSection(type: ItemType): void { - this.searchAutoTrigger?.closePanel(); - const search = this.searchText?.trim() || undefined; - void this.router.navigate(['/iot-hub', this.getTypeRoute(type)], { queryParams: { search } }); - } - isCompactType(type: ItemType): boolean { return type === ItemType.CALCULATED_FIELD || type === ItemType.ALARM_RULE @@ -314,9 +314,13 @@ export class TbIotHubHomeComponent implements OnInit, OnDestroy { return getItemTypeIcon(type); } - getSearchGroupLabel(type: ItemType): string { + getItemTypeColor(type: ItemType): string { + return getItemTypeColor(type); + } + + getItemTypeLabel(type: ItemType): string { const key = itemTypeTranslations.get(type); - return key ? this.translate.instant(key + '-plural') : type; + return key ? this.translate.instant(key) : type; } navigateToBrowse(type: ItemType): void { @@ -582,26 +586,4 @@ export class TbIotHubHomeComponent implements OnInit, OnDestroy { }); } - /** - * Reads the sections the server built: they arrive capped and in the order to render them, so - * this only drops the types this panel has no layout for - the platform publishes no dashboards - * - and works out each header's "+N more". - * - * `items` is defaulted because the response is an unvalidated cast of a new endpoint, and a - * throw here lands in a subscribe callback, where it would leave the panel on its spinner - * rather than reaching the catchError upstream. - */ - private toResultGroups(sections: MpItemVersionSection[]): SearchResultGroup[] { - return sections - .filter(section => CROSS_TYPE_ITEM_TYPES.includes(section.itemType)) - .map(section => { - const items = section.items ?? []; - return { - type: section.itemType, - items, - remaining: Math.max(0, section.total - items.length) - }; - }); - } - } diff --git a/ui-ngx/src/app/shared/models/iot-hub/iot-hub-item.models.ts b/ui-ngx/src/app/shared/models/iot-hub/iot-hub-item.models.ts index 8fbe84440b..e21582ea1a 100644 --- a/ui-ngx/src/app/shared/models/iot-hub/iot-hub-item.models.ts +++ b/ui-ngx/src/app/shared/models/iot-hub/iot-hub-item.models.ts @@ -41,6 +41,21 @@ export const itemTypeIcons: Record = { export const getItemTypeIcon = (type?: string | null): string => type && itemTypeIcons[type] ? itemTypeIcons[type] : 'category'; +// Canonical colour per item type - the IoT Hub home's type palette - for anything that marks an +// item's type with a colour: the hero's type cycle and the search popup's type label. +export const itemTypeColors: Record = { + [ItemType.WIDGET]: '#2c9755', + [ItemType.DASHBOARD]: '#5f6368', + [ItemType.SOLUTION_TEMPLATE]: '#2b6bb4', + [ItemType.CALCULATED_FIELD]: '#3cb4e0', + [ItemType.RULE_CHAIN]: '#a95ae2', + [ItemType.ALARM_RULE]: '#d66f2e', + [ItemType.DEVICE]: '#4b63cc' +}; + +export const getItemTypeColor = (type?: string | null): string => + type && itemTypeColors[type] ? itemTypeColors[type] : '#5f6368'; + /** * Item types discoverable to creators in the marketplace UI. * DASHBOARD is intentionally absent (IoT Hub no longer accepts Dashboard contributions). diff --git a/ui-ngx/src/app/shared/models/iot-hub/iot-hub-version.models.ts b/ui-ngx/src/app/shared/models/iot-hub/iot-hub-version.models.ts index a5afaea23c..685fc27cb1 100644 --- a/ui-ngx/src/app/shared/models/iot-hub/iot-hub-version.models.ts +++ b/ui-ngx/src/app/shared/models/iot-hub/iot-hub-version.models.ts @@ -108,17 +108,6 @@ export interface MpItemVersionView { checksum?: string; } -/** - * One item type's share of a grouped search: the rows to show and how many exist behind them. - * A grouped answer is a list of these, in the server's section order, and a type nothing matched - * has no section — so a "+N more" header is `total - items.length`. - */ -export interface MpItemVersionSection { - itemType: ItemType; - total: number; - items: MpItemVersionView[]; -} - // 404 body shapes returned by the public listing item-version endpoint // (GET /api/listings/public/by-slug/{slug}/item-version) when no // version matches the caller's edition / platform combination. @@ -208,30 +197,3 @@ export class MpItemVersionQuery { return this.pageLink.toQuery() + filtersToQuery(this.options); } } - -/** - * A sectioned read: the filters, what to search for, and which key orders a section. - * - * No `PageLink`, because the grouped endpoint takes no page and no page size - it sizes its own - * answer from the section limit - and no sort direction either, each key's direction being fixed - * by the chain the server switches on. A page link here could only carry values nobody sends. - */ -export class MpItemVersionGroupedQuery { - constructor(public options: MpItemVersionQueryOptions = {}, - public textSearch?: string, - public sortProperty?: string) {} - - public toQuery(): string { - const parts: string[] = []; - const text = this.textSearch?.trim(); - if (text?.length) { - parts.push(`textSearch=${encodeURIComponent(text)}`); - } - if (this.sortProperty) { - parts.push(`sortProperty=${this.sortProperty}`); - } - // filtersToQuery() emits leading ampersands, which is what a page link needs in front of it; - // here they may be the whole query string, so the first one is dropped. - return `?${`${parts.join('&')}${filtersToQuery(this.options)}`.replace(/^&/, '')}`; - } -} diff --git a/ui-ngx/src/assets/locale/locale.constant-en_US.json b/ui-ngx/src/assets/locale/locale.constant-en_US.json index e19cb64cff..f3818e8179 100644 --- a/ui-ngx/src/assets/locale/locale.constant-en_US.json +++ b/ui-ngx/src/assets/locale/locale.constant-en_US.json @@ -3708,6 +3708,7 @@ "search": "Search...", "search-published-items": "Search published items...", "see-all-results": "See all results", + "see-all-results-for": "See all {{ count }} results for \"{{ search }}\"", "see-results-for": "See results for \"{{ search }}\"", "no-search-results": "No results found for '{{ search }}'", "no-items-available": "No items available", @@ -3780,7 +3781,6 @@ "sort-most-installed": "Most installed", "sort-newest": "Newest", "sort-name": "Name (A-Z)", - "section-more": "{ count, plural, =1 {+1 more} other {+# more} }", "type-filter-label": "Type", "category": "Category", "use-case": "Use case", From 368d6fd94d5a9c01998c0442c8527a7f32ccdb5f Mon Sep 17 00:00:00 2001 From: dshvaika Date: Tue, 29 Sep 2026 17:16:06 +0300 Subject: [PATCH 097/159] refactor(iot-hub): one source for the platform scope and the type palette's default From the review: - iot-hub-api.service builds peOnly/tbVersion from one platformScope(), used by applyPlatformFilters and by the reads that wrote the pair into the URL by hand (filterInfo, widgetCategories, the listing item-version lookup). - DEFAULT_ITEM_TYPE_COLOR names the grey the palette falls back to; the alarm-rules-unavailable page reads itemTypeColors instead of its own copy. - isCompactItemType() next to CROSS_TYPE_ITEM_TYPES, used by the item card and the popup. - A stale "shared by both query shapes" comment left from the grouped query, and other comments, trimmed to the non-obvious intent. --- .../src/app/core/http/iot-hub-api.service.ts | 34 +++++++++---------- .../components/iot-hub/_iot-hub-common.scss | 8 +---- .../iot-hub/iot-hub-item-card.component.html | 3 +- .../iot-hub/iot-hub-item-card.component.ts | 15 +++----- ...-alarm-rules-unavailable-page.component.ts | 4 +-- .../iot-hub-creator-profile.component.html | 2 -- .../models/iot-hub/iot-hub-item.models.ts | 33 +++++++----------- .../models/iot-hub/iot-hub-version.models.ts | 9 ++--- 8 files changed, 40 insertions(+), 68 deletions(-) diff --git a/ui-ngx/src/app/core/http/iot-hub-api.service.ts b/ui-ngx/src/app/core/http/iot-hub-api.service.ts index c5037048fb..fe579b5b88 100644 --- a/ui-ngx/src/app/core/http/iot-hub-api.service.ts +++ b/ui-ngx/src/app/core/http/iot-hub-api.service.ts @@ -80,31 +80,31 @@ export class IotHubApiService { ); } - /** - * What this platform can install, filled in for a caller that did not say: items built for a - * newer ThingsBoard, and PE-only items on a CE instance, cannot be installed from here. - */ + /** What this platform can install: no PE-only items, nothing built for a newer ThingsBoard. */ + private platformScope(): { peOnly: boolean; tbVersion: number } { + return { peOnly: false, tbVersion: tbVersionToInt(env.tbVersion) }; + } + + /** Fills in the platform scope wherever the caller did not set it. */ private applyPlatformFilters(options: MpItemVersionQueryOptions): void { - if (options.tbVersion == null) { - options.tbVersion = tbVersionToInt(env.tbVersion); - } - if (options.peOnly == null) { - options.peOnly = false; - } + const scope = this.platformScope(); + options.tbVersion ??= scope.tbVersion; + options.peOnly ??= scope.peOnly; + } + + private platformScopeParams(): string[] { + const scope = this.platformScope(); + return [`peOnly=${scope.peOnly}`, `tbVersion=${scope.tbVersion}`]; } public getFilterInfo(itemType: ItemType, config?: IotHubRequestConfig): Observable { - const url = `${this.baseUrl}/api/item-listing/filterInfo/${itemType}` - + `?peOnly=false&tbVersion=${tbVersionToInt(env.tbVersion)}`; + const url = `${this.baseUrl}/api/item-listing/filterInfo/${itemType}?${this.platformScopeParams().join('&')}`; return this.http.get(url, { params: this.buildParams(config) }); } public getWidgetCategories(textSearch?: string, scadaFirst?: boolean, config?: IotHubRequestConfig): Observable { - const queryParams: string[] = [ - `peOnly=false`, - `tbVersion=${tbVersionToInt(env.tbVersion)}` - ]; + const queryParams: string[] = this.platformScopeParams(); if (textSearch?.trim()) { queryParams.push(`textSearch=${encodeURIComponent(textSearch.trim())}`); } @@ -144,7 +144,7 @@ export class IotHubApiService { public getListingItemVersion(slug: string, config?: IotHubRequestConfig): Observable { const queryParams = [ 'ce=true', - `tbVersion=${tbVersionToInt(env.tbVersion)}` + `tbVersion=${this.platformScope().tbVersion}` ]; return this.http.get( `${this.baseUrl}/api/listings/public/by-slug/${encodeURIComponent(slug)}/item-version?${queryParams.join('&')}`, diff --git a/ui-ngx/src/app/modules/home/components/iot-hub/_iot-hub-common.scss b/ui-ngx/src/app/modules/home/components/iot-hub/_iot-hub-common.scss index 96697ebe74..b6264d6ce3 100644 --- a/ui-ngx/src/app/modules/home/components/iot-hub/_iot-hub-common.scss +++ b/ui-ngx/src/app/modules/home/components/iot-hub/_iot-hub-common.scss @@ -120,13 +120,7 @@ } } -// Scroll area that shows its thumb only while the container is hovered — the filter panels' -// own treatment, kept here so the two that use it cannot drift apart. -// -// Not the app-wide one: theme.scss keeps its thumb permanently visible. Whether these panels -// should do the same, and whether to add the standardised scrollbar-width / scrollbar-color -// that Firefox reads, is a question for the IoT Hub filter UI as a whole rather than for one -// panel; iot-hub-browse and dashboard-widget-select carry copies of this same treatment. +// Scroll area whose thumb shows only while the container is hovered (the filter panels'). @mixin tb-iot-hub-hover-scrollbar { &::-webkit-scrollbar { width: 6px; diff --git a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-item-card.component.html b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-item-card.component.html index 16bca59bf7..4a73740979 100644 --- a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-item-card.component.html +++ b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-item-card.component.html @@ -78,8 +78,7 @@ } @else {
    - + {{ getPlaceholderIcon() }}
    } diff --git a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-item-card.component.ts b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-item-card.component.ts index f57582fb29..123de28c3f 100644 --- a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-item-card.component.ts +++ b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-item-card.component.ts @@ -2,7 +2,7 @@ // SPDX-License-Identifier: Apache-2.0 import { Component, EventEmitter, Input, Output } from '@angular/core'; import { MpItemVersionView, cfTypeTranslations, cfTypeIcons, ruleChainTypeTranslations, widgetTypeTranslations } from '@shared/models/iot-hub/iot-hub-version.models'; -import { getItemTypeIcon, ItemType } from '@shared/models/iot-hub/iot-hub-item.models'; +import { getItemTypeIcon, isCompactItemType, ItemType } from '@shared/models/iot-hub/iot-hub-item.models'; import { IotHubInstalledItem } from '@shared/models/iot-hub/iot-hub-installed-item.models'; import { TranslateService } from '@ngx-translate/core'; import { IotHubApiService } from '@core/http/iot-hub-api.service'; @@ -24,13 +24,8 @@ export class TbIotHubItemCardComponent { @Input() showSubtype = false; @Input() mode: 'default' | 'add' = 'default'; /** - * `auto` lets the item's type choose, which is what a single-type grid wants: calculated - * fields, alarm rules and rule chains have nothing to preview, so they get a compact row and - * the grid gives them wider cells. - * - * `preview` forces the tall card on every type. A grid that mixes types cannot widen its - * cells for some rows only, and a horizontal row squeezed into a cell sized for a preview - * truncates its own title and leaves the rest of the cell empty. + * `auto`: compact row for the types with nothing to preview (single-type grids widen their + * cells for it). `preview`: the tall card for every type, for grids that mix types. */ @Input() layout: 'auto' | 'preview' = 'auto'; @Output() cardClick = new EventEmitter(); @@ -60,9 +55,7 @@ export class TbIotHubItemCardComponent { if (this.layout === 'preview') { return false; } - return this.item.type === ItemType.CALCULATED_FIELD - || this.item.type === ItemType.ALARM_RULE - || this.item.type === ItemType.RULE_CHAIN; + return isCompactItemType(this.item.type); } getPreviewUrl(): string | null { diff --git a/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-alarm-rules-unavailable-page.component.ts b/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-alarm-rules-unavailable-page.component.ts index c648eeb14a..f8ec79e525 100644 --- a/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-alarm-rules-unavailable-page.component.ts +++ b/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-alarm-rules-unavailable-page.component.ts @@ -3,6 +3,7 @@ import { Component } from '@angular/core'; import { Router } from '@angular/router'; import { environment as env } from '@env/environment'; +import { ItemType, itemTypeColors } from '@shared/models/iot-hub/iot-hub-item.models'; @Component({ selector: 'tb-iot-hub-alarm-rules-unavailable-page', @@ -12,8 +13,7 @@ import { environment as env } from '@env/environment'; }) export class TbIotHubAlarmRulesUnavailablePageComponent { - // Same colour as the ALARM_RULE HeroTypeConfig entry on the home page. - readonly alarmRulesColor = '#d66f2e'; + readonly alarmRulesColor = itemTypeColors[ItemType.ALARM_RULE]; readonly currentTbVersion: string = env.tbVersion; diff --git a/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-creator-profile.component.html b/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-creator-profile.component.html index 51d834e8ed..42f92fc3d1 100644 --- a/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-creator-profile.component.html +++ b/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-creator-profile.component.html @@ -96,8 +96,6 @@
    -

    diff --git a/ui-ngx/src/app/shared/models/iot-hub/iot-hub-item.models.ts b/ui-ngx/src/app/shared/models/iot-hub/iot-hub-item.models.ts index e21582ea1a..ea2077e634 100644 --- a/ui-ngx/src/app/shared/models/iot-hub/iot-hub-item.models.ts +++ b/ui-ngx/src/app/shared/models/iot-hub/iot-hub-item.models.ts @@ -41,11 +41,13 @@ export const itemTypeIcons: Record = { export const getItemTypeIcon = (type?: string | null): string => type && itemTypeIcons[type] ? itemTypeIcons[type] : 'category'; -// Canonical colour per item type - the IoT Hub home's type palette - for anything that marks an -// item's type with a colour: the hero's type cycle and the search popup's type label. +/** Colour for a type with no colour of its own. */ +export const DEFAULT_ITEM_TYPE_COLOR = '#5f6368'; + +/** Colour per item type, wherever an item's type is marked with one. */ export const itemTypeColors: Record = { [ItemType.WIDGET]: '#2c9755', - [ItemType.DASHBOARD]: '#5f6368', + [ItemType.DASHBOARD]: DEFAULT_ITEM_TYPE_COLOR, [ItemType.SOLUTION_TEMPLATE]: '#2b6bb4', [ItemType.CALCULATED_FIELD]: '#3cb4e0', [ItemType.RULE_CHAIN]: '#a95ae2', @@ -54,7 +56,7 @@ export const itemTypeColors: Record = { }; export const getItemTypeColor = (type?: string | null): string => - type && itemTypeColors[type] ? itemTypeColors[type] : '#5f6368'; + type && itemTypeColors[type] ? itemTypeColors[type] : DEFAULT_ITEM_TYPE_COLOR; /** * Item types discoverable to creators in the marketplace UI. @@ -71,11 +73,7 @@ export const CREATOR_VISIBLE_ITEM_TYPES: ItemType[] = [ ItemType.RULE_CHAIN, ]; -/** - * Item types a surface that mixes them lays out, in the order they are shown. Distinct from - * CREATOR_VISIBLE_ITEM_TYPES, which is the same six as a membership test and carries the type - * tabs' own order: here DEVICE leads, matching the hero popup's sections and the website. - */ +/** Item types a cross-type surface (search page, popup) shows, in display order. */ export const CROSS_TYPE_ITEM_TYPES: ItemType[] = [ ItemType.DEVICE, ItemType.SOLUTION_TEMPLATE, @@ -85,6 +83,10 @@ export const CROSS_TYPE_ITEM_TYPES: ItemType[] = [ ItemType.RULE_CHAIN, ]; +/** Types drawn as a coloured icon tile rather than a screenshot. */ +export const isCompactItemType = (type?: string | null): boolean => + type === ItemType.CALCULATED_FIELD || type === ItemType.ALARM_RULE || type === ItemType.RULE_CHAIN; + /** Sort property served by relevance ranking. */ export const RELEVANCE_SORT_PROPERTY = 'relevance'; @@ -95,17 +97,8 @@ export interface SortOption { } /** - * The sort menu every IoT Hub surface carrying a search field offers, and the order it offers - * them in: the first entry is the default each surface opens on. - * - * Relevance is that default with or without text. With text it ranks the answer; with none the - * backend serves the install count under the same key, so a surface opens on the order it opened - * on before and nothing here switches on the field state. The cost is a menu reading "Most - * relevant" over an install-ordered list until the user types; the alternative - flipping the - * selector once text appears - moves a control the user did not touch and reorders nothing. - * - * One list rather than one per surface: a new key must reach all of them, and the surface that - * missed it would keep a different default without failing. + * The sort menu of every IoT Hub surface with a search field; the first entry is the default. + * Relevance stays the default with an empty field, where it orders by install count. */ export const IOT_HUB_SORT_OPTIONS: SortOption[] = [ { value: RELEVANCE_SORT_PROPERTY, label: 'iot-hub.sort-most-relevant', direction: Direction.DESC }, diff --git a/ui-ngx/src/app/shared/models/iot-hub/iot-hub-version.models.ts b/ui-ngx/src/app/shared/models/iot-hub/iot-hub-version.models.ts index 685fc27cb1..8ba587342c 100644 --- a/ui-ngx/src/app/shared/models/iot-hub/iot-hub-version.models.ts +++ b/ui-ngx/src/app/shared/models/iot-hub/iot-hub-version.models.ts @@ -120,12 +120,7 @@ export interface ListingItemVersionNotFound { export interface MpItemVersionQueryOptions { /** Single item type, for a surface pinned to one (the type pages, the add-item dialog). */ type?: string; - /** - * Several item types at once, for a cross-type surface whose Type facet is multi-select. - * Emitted as a repeated `type` parameter, which is the shape the backend reads - * (`@RequestParam List type`). Kept separate from `type` rather than widening it, - * so a caller that means "exactly this type" cannot be handed an array by accident. - */ + /** Several item types at once, sent as a repeated `type` parameter. */ types?: string[]; peOnly?: boolean; creatorId?: string; @@ -141,7 +136,7 @@ export interface MpItemVersionQueryOptions { scadaFirst?: boolean; } -/** Every filter, as `&name=value` pairs - shared by both query shapes below. */ +/** Every filter, as `&name=value` pairs. */ function filtersToQuery(o: MpItemVersionQueryOptions): string { let query = ''; if (o.type) { From 6fc35a4d0ede33a6d977ce2a82adfde02974f1b9 Mon Sep 17 00:00:00 2001 From: dshvaika Date: Tue, 29 Sep 2026 17:16:06 +0300 Subject: [PATCH 098/159] fix(iot-hub): offer no relevance sort on the widget picker's Installed list That list is sorted in the browser, and relevance is a score only the Hub computes: sortInstalledVersions read a 'relevance' field no row has, so "Most relevant" left the list unsorted under a label saying otherwise. The Installed list now offers the other three keys, and a relevance choice made on the IoT Hub list falls back to the first of them there. The sort is kept by value rather than by menu index, since the two lists differ in length. --- .../dashboard-widget-select.component.html | 6 ++-- .../dashboard-widget-select.component.ts | 32 ++++++++++++------- 2 files changed, 24 insertions(+), 14 deletions(-) diff --git a/ui-ngx/src/app/modules/home/components/dashboard-page/dashboard-widget-select.component.html b/ui-ngx/src/app/modules/home/components/dashboard-page/dashboard-widget-select.component.html index aa5c1deb90..c75165d122 100644 --- a/ui-ngx/src/app/modules/home/components/dashboard-page/dashboard-widget-select.component.html +++ b/ui-ngx/src/app/modules/home/components/dashboard-page/dashboard-widget-select.component.html @@ -80,12 +80,12 @@ } @if (selectWidgetMode === 'iotHub' && iotHubSubMode !== 'default') { - @for (option of iotHubSortOptions; track option.value; let i = $index) { - + @for (option of iotHubSortOptions; track option.value) { + } } diff --git a/ui-ngx/src/app/modules/home/components/dashboard-page/dashboard-widget-select.component.ts b/ui-ngx/src/app/modules/home/components/dashboard-page/dashboard-widget-select.component.ts index 7cb0eddd2b..7132063ed2 100644 --- a/ui-ngx/src/app/modules/home/components/dashboard-page/dashboard-widget-select.component.ts +++ b/ui-ngx/src/app/modules/home/components/dashboard-page/dashboard-widget-select.component.ts @@ -25,8 +25,13 @@ import { FilterParamInfo, IOT_HUB_SORT_OPTIONS, ItemType, + RELEVANCE_SORT_PROPERTY, + SortOption, WidgetCategory } from '@shared/models/iot-hub/iot-hub-item.models'; + +/** The Installed list is sorted locally, and only the Hub can rank by relevance. */ +const INSTALLED_SORT_OPTIONS = IOT_HUB_SORT_OPTIONS.filter(o => o.value !== RELEVANCE_SORT_PROPERTY); import { IotHubInstalledItem } from '@shared/models/iot-hub/iot-hub-installed-item.models'; import { IotHubApiService } from '@core/http/iot-hub-api.service'; import { IotHubActionsService } from '@home/components/iot-hub/iot-hub-actions.service'; @@ -87,12 +92,7 @@ export class DashboardWidgetSelectComponent { includeDeprecated = false; searchFocused = false; - /** - * scadaFirst is unaffected by the sort: the backend prepends it ahead of the caller's key AND - * ahead of relevance, so a SCADA context still lists SCADA widgets first. - */ - readonly iotHubSortOptions = IOT_HUB_SORT_OPTIONS; - iotHubSelectedSortIndex = 0; + private iotHubSelectedSortValue = IOT_HUB_SORT_OPTIONS[0].value; @Input() aliasController: IAliasController; @@ -302,7 +302,7 @@ export class DashboardWidgetSelectComponent { this.iotHubWidgetsFetchFunction = (pageSize, page, filter) => { const search = typeof filter === 'string' ? filter.split('|')[0] : filter; - const sort = this.iotHubSortOptions[this.iotHubSelectedSortIndex]; + const sort = this.iotHubSelectedSort; const sortOrder: SortOrder = { property: sort.value, direction: sort.direction }; const pageLink = new PageLink(pageSize, page, search || null, sortOrder); const effectiveCategories = this.iotHubSelectedCategory @@ -569,9 +569,19 @@ export class DashboardWidgetSelectComponent { this.reloadIotHubWidgets(); } - onIotHubSortChange(index: number): void { - if (this.iotHubSelectedSortIndex !== index) { - this.iotHubSelectedSortIndex = index; + get iotHubSortOptions(): SortOption[] { + return this.iotHubSubMode === 'installed' ? INSTALLED_SORT_OPTIONS : IOT_HUB_SORT_OPTIONS; + } + + /** The chosen sort, or the list's first option where the chosen one is not offered. */ + get iotHubSelectedSort(): SortOption { + const options = this.iotHubSortOptions; + return options.find(o => o.value === this.iotHubSelectedSortValue) ?? options[0]; + } + + onIotHubSortChange(option: SortOption): void { + if (this.iotHubSelectedSort.value !== option.value) { + this.iotHubSelectedSortValue = option.value; this.installedWidgetVersions = null; this.reloadIotHubWidgets(); } @@ -844,7 +854,7 @@ export class DashboardWidgetSelectComponent { } private sortInstalledVersions(versions: MpItemVersionView[]): MpItemVersionView[] { - const sort = this.iotHubSortOptions[this.iotHubSelectedSortIndex]; + const sort = this.iotHubSelectedSort; const sign = sort.direction === Direction.ASC ? 1 : -1; const copy = [...versions]; copy.sort((a, b) => { From 3b4dc3198576a0c3c17807ced1c10d2b21e4d1c5 Mon Sep 17 00:00:00 2001 From: dshvaika Date: Tue, 29 Sep 2026 17:16:06 +0300 Subject: [PATCH 099/159] refactor(iot-hub): handle Enter in the popup on keydown, with no cross-event flag Enter in the field opens the search page unless the autocomplete has just used the press to select a highlighted row, which it marks with preventDefault in its own keydown handler, registered before the field's. The field now listens on keydown.enter and checks event.defaultPrevented, which replaces the enterHandledByRow flag, the four places that reset it, and the read of the trigger's activeOption at one exact moment. Checked in a browser: arrow + Enter on a row opens the row only, Enter in the field opens the search page, click a row / close the dialog / click the magnifier opens the search page, and arrow to the footer + Enter opens it once. Also from the review: - The popup asks for the six cross-type types rather than filtering dashboards out afterwards, so totalElements is exact and "See all N" needs no arithmetic. - Row and footer selection go through onRowSelected / onFooterSelected instead of a side-effecting predicate in the template. - isCompactType delegates to the shared isCompactItemType; comments trimmed. --- .../pages/iot-hub/iot-hub-home.component.html | 12 ++- .../pages/iot-hub/iot-hub-home.component.scss | 9 +-- .../pages/iot-hub/iot-hub-home.component.ts | 78 ++++++------------- 3 files changed, 32 insertions(+), 67 deletions(-) diff --git a/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-home.component.html b/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-home.component.html index 5963c9e536..d244bbe06a 100644 --- a/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-home.component.html +++ b/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-home.component.html @@ -54,13 +54,13 @@ [matAutocomplete]="searchAuto" (input)="onSearchInput()" (focus)="onSearchFocus()" - (keyup.enter)="onSearch()"> + (keydown.enter)="onSearchEnter($event)"> @if (searchText) { } - @@ -86,9 +86,8 @@ } @else { @for (item of searchResults; track item.id) { - + (onSelectionChange)="onRowSelected($event, item)"> +
    @if (isCompactType(item.type)) {
    @@ -102,7 +101,6 @@
    {{ item.name }} - {{ getItemTypeIcon(item.type) }} @@ -124,7 +122,7 @@ } } + (onSelectionChange)="onFooterSelected($event)"> @if (searchText?.trim(); as query) { @if (searchTotal > searchResults.length) { {{ 'iot-hub.see-all-results-for' | translate:{ count: searchTotal, search: query } }} diff --git a/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-home.component.scss b/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-home.component.scss index 157d6e1faf..7440403390 100644 --- a/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-home.component.scss +++ b/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-home.component.scss @@ -220,9 +220,7 @@ 0 114px 46px 0 rgba(0, 0, 0, 0.01), 0 178px 50px 0 rgba(0, 0, 0, 0); - // Every row of the panel shares the flex line and the highlight; the boxes differ per kind - // below. Each kind is selected by its own class rather than by leaning on source order, since - // .mat-mdc-option. and .mat-mdc-option:not(...) tie on specificity. + // Shared by every row; each row kind below is selected by its own class. .mat-mdc-option { .mdc-list-item__primary-text { display: flex; @@ -357,8 +355,7 @@ min-width: 0; } - // Item type in its own colour, darkened so the paler ones (rule chain, calculated field) stay - // legible as text. + // Item type in its colour, darkened so the paler ones stay legible. .tb-search-popup-type { display: flex; align-items: center; @@ -368,7 +365,7 @@ font-weight: 500; line-height: 16px; letter-spacing: 0.25px; - color: color-mix(in srgb, var(--tb-search-popup-type-color, #5f6368) 75%, #000); + color: color-mix(in srgb, var(--tb-search-popup-type-color) 75%, #000); white-space: nowrap; tb-icon { diff --git a/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-home.component.ts b/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-home.component.ts index c7c6a9ad07..8f44ec2c30 100644 --- a/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-home.component.ts +++ b/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-home.component.ts @@ -15,6 +15,7 @@ import { MpItemVersionQuery, MpItemVersionView } from '@shared/models/iot-hub/io import { CROSS_TYPE_ITEM_TYPES, getItemTypeColor, + isCompactItemType, getItemTypeIcon, ItemType, itemTypeColors, @@ -42,10 +43,7 @@ interface HeroTypeConfig { icon: string; } -/** - * Rows the search popup shows: the first page of the search page's own request, so the popup is - * a preview of what "See results for ..." opens on. - */ +/** Rows the search popup shows: page 0 of the search page's own request. */ const SEARCH_POPUP_PAGE_SIZE = 10; @Component({ @@ -60,17 +58,12 @@ export class TbIotHubHomeComponent implements OnInit, OnDestroy { searchText = ''; searchResults: MpItemVersionView[] = []; - /** - * What the footer's "See all N results" counts: the matches less the rows this page dropped, so - * a panel that shows everything it can open never claims more. Rows beyond this page that the - * panel could not show are still counted - only this page's drops are known. - */ + /** Everything the search matched, for the footer's "See all N results". */ searchTotal = 0; searchLoaded = false; searchLoading = false; @ViewChild(MatAutocompleteTrigger) searchAutoTrigger: MatAutocompleteTrigger; @ViewChild('searchInput', {read: ElementRef}) searchInputRef: ElementRef; - private enterHandledByRow = false; private searchSubject = new Subject(); private searchSubscription: Subscription; @@ -169,26 +162,19 @@ export class TbIotHubHomeComponent implements OnInit, OnDestroy { switchMap(text => { this.searchLoading = true; const trimmed = text.trim(); - // One flat list ranked across every type, so the best match leads whatever its type. - // Relevance in both states, the same value every other IoT Hub surface sends: with an - // empty field the backend serves the install count under this key, so the panel opens on - // popularity without this component having to know it. + // One list ranked across every type the platform surfaces. With an empty field relevance + // is served as the install count. const sortOrder: SortOrder = { property: RELEVANCE_SORT_PROPERTY, direction: Direction.DESC }; const pageLink = new PageLink(SEARCH_POPUP_PAGE_SIZE, 0, trimmed || null, sortOrder); - const query = new MpItemVersionQuery(pageLink); - // A failed request must not end the subscription: the interceptor reports it, and the - // panel goes back to an empty answer the next keystroke can replace. + const query = new MpItemVersionQuery(pageLink, { types: CROSS_TYPE_ITEM_TYPES }); + // A failure must not end the subscription; the next keystroke replaces the empty answer. return this.iotHubApiService.getPublishedVersions(query, { ignoreLoading: true }).pipe( catchError(() => of({ data: [], totalElements: 0 } as PageData)) ); }) ).subscribe(page => { - // The platform publishes no dashboards, so a type this panel has no layout for is dropped; - // the popup then shows fewer rows rather than asking for more. - const data = page.data ?? []; - this.searchResults = data.filter(item => CROSS_TYPE_ITEM_TYPES.includes(item.type)); - this.searchTotal = Math.max(this.searchResults.length, - (page.totalElements ?? 0) - (data.length - this.searchResults.length)); + this.searchResults = page.data ?? []; + this.searchTotal = page.totalElements ?? 0; this.searchLoaded = true; this.searchLoading = false; }); @@ -230,13 +216,11 @@ export class TbIotHubHomeComponent implements OnInit, OnDestroy { } onSearchInput(): void { - this.enterHandledByRow = false; this.searchLoading = true; this.searchSubject.next(this.searchText || ''); } onSearchFocus(): void { - this.enterHandledByRow = false; if (!this.searchLoaded) { this.searchLoading = true; this.searchSubject.next(this.searchText || ''); @@ -248,43 +232,30 @@ export class TbIotHubHomeComponent implements OnInit, OnDestroy { }; clearSearch(): void { - this.enterHandledByRow = false; this.searchText = ''; this.searchSubject.next(''); this.searchInputRef?.nativeElement?.focus(); setTimeout(() => this.searchAutoTrigger?.openPanel()); } - /** - * Gate on every row's selection: false for the panel's own bookkeeping, true when the user - * picked the row - and then it records whether a keyup is still coming for it. - * - * One Enter reaches two handlers. The autocomplete trigger acts on keydown, the field's own - * handler on keyup, and preventDefault on the first does not stop the second. Only the - * keyboard leaves that second half to deal with, so only the keyboard arms the flag: a pointer - * selection is finished when it returns, and a flag left standing there would swallow the next - * onSearch - which the magnifier button can raise with no keystroke at all. - * - * activeOption is what tells the two apart, and it is readable only here: the trigger holds it - * while it calls _selectViaInteraction and clears it on the next line of its own handler, so by - * keyup it reads empty either way. A pointer never sets it. - */ - rowSelectedByUser(event: MatOptionSelectionChange): boolean { - if (!event.isUserInput) { - return false; + onRowSelected(event: MatOptionSelectionChange, item: MpItemVersionView): void { + if (event.isUserInput) { + this.openItemDetail(item); + } + } + + onFooterSelected(event: MatOptionSelectionChange): void { + if (event.isUserInput) { + this.seeAllResults(); } - this.enterHandledByRow = !!this.searchAutoTrigger?.activeOption; - return true; } /** - * Enter in the field opens the search page, unless a row has just acted on this same press. - * Every path that re-enters the field clears the flag too, so nothing survives the keystroke - * it belongs to - including an arrow-then-click, the one selection that arms it by pointer. + * Enter in the field opens the search page - unless the autocomplete has just used this press + * to select a highlighted row, which it marks with preventDefault before this handler runs. */ - onSearch(): void { - if (this.enterHandledByRow) { - this.enterHandledByRow = false; + onSearchEnter(event: KeyboardEvent): void { + if (event.defaultPrevented || event.isComposing) { return; } this.seeAllResults(); @@ -297,11 +268,10 @@ export class TbIotHubHomeComponent implements OnInit, OnDestroy { } isCompactType(type: ItemType): boolean { - return type === ItemType.CALCULATED_FIELD - || type === ItemType.ALARM_RULE - || type === ItemType.RULE_CHAIN; + return isCompactItemType(type); } + getCompactIcon(item: MpItemVersionView): string { return item.icon || getItemTypeIcon(item.type); } From a427a6a3d20cba5802896efbaa53b9a1bb33a664 Mon Sep 17 00:00:00 2001 From: dshvaika Date: Tue, 29 Sep 2026 17:16:06 +0300 Subject: [PATCH 100/159] fix(iot-hub): scope the search page to the cross-type types, and let a newer load win From the review of the search page: - No Type facet selected now sends the six types the platform surfaces, as the popup does, instead of every type the Hub holds: without the old grouping step a published dashboard would have rendered as a card and been counted. - Every reload goes through one Subject + switchMap, so a newer request cancels an older one; toggling two facets quickly can no longer leave the grid on the first answer. - The ResizeObserver callback runs inside NgZone.run, as in TbIotHubBrowseComponent; zone.js does not patch ResizeObserver, so a reload started from it did not render. Checked: widening the window reloads with the larger page size and renders it with no other event. - The facet list takes option keys (string[]) and computes its visible list once per change instead of on every change-detection pass; the Type facet's placeholder zero counts and the facet count summing are gone. - Shared in iot-hub-utils: filterByLabel (behind filterIotHubItemsBySearch), measureGridColumns (used by this component and the browse page), and IOT_HUB_FILTER_SCROLL_THRESHOLD in place of the literal 8 in both panels. - The page padding and the component's pull-out margin derive from one --tb-search-page-pad per breakpoint. Resize fields sit with the other state. - Comments trimmed to the non-obvious intent. --- .../iot-hub/iot-hub-browse.component.html | 24 +-- .../iot-hub/iot-hub-browse.component.ts | 21 ++- .../iot-hub/iot-hub-facet-list.component.html | 10 +- .../iot-hub/iot-hub-facet-list.component.scss | 10 +- .../iot-hub/iot-hub-facet-list.component.ts | 64 +++----- .../iot-hub/iot-hub-search.component.html | 8 +- .../iot-hub/iot-hub-search.component.scss | 33 ++-- .../iot-hub/iot-hub-search.component.ts | 147 +++++++----------- .../home/components/iot-hub/iot-hub-utils.ts | 24 ++- .../iot-hub-search-page.component.scss | 34 ++-- 10 files changed, 150 insertions(+), 225 deletions(-) diff --git a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-browse.component.html b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-browse.component.html index 40ffca34c8..dbc1c3c811 100644 --- a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-browse.component.html +++ b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-browse.component.html @@ -43,8 +43,8 @@ }
    } -
    @for (opt of getFilteredItems(subtypeOptions, 'subtype'); track opt.key) { } -
    @for (group of getGroupedFilterItems(vendorOptions, 'vendor'); track group.label) { @if (group.label) { @@ -114,8 +114,8 @@ }
    } -
    @for (ht of getFilteredItems(hardwareTypeOptions, 'hardwareType'); track ht.key) { } -
    @for (group of getFilteredConnectivityGroups('connectivity'); track group.group) {
    {{ group.group }}
    @@ -182,8 +182,8 @@ }
    } -
    @for (cat of getFilteredItems(categoryOptions, 'category'); track cat.key) { } -
    @for (group of getGroupedFilterItems(useCaseOptions, 'useCase'); track group.label) { @if (group.label) { diff --git a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-browse.component.ts b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-browse.component.ts index 2be0408826..40276cd769 100644 --- a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-browse.component.ts +++ b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-browse.component.ts @@ -19,7 +19,13 @@ import { IotHubApiService } from '@core/http/iot-hub-api.service'; import { TranslateService } from '@ngx-translate/core'; import { ActivatedRoute, Router } from '@angular/router'; import { IotHubActionsService } from '@home/components/iot-hub/iot-hub-actions.service'; -import { filterIotHubItemsBySearch, groupIotHubFilterItems, IotHubFilterGroup } from '@home/components/iot-hub/iot-hub-utils'; +import { + filterIotHubItemsBySearch, + groupIotHubFilterItems, + IOT_HUB_FILTER_SCROLL_THRESHOLD, + IotHubFilterGroup, + measureGridColumns +} from '@home/components/iot-hub/iot-hub-utils'; @Component({ selector: 'tb-iot-hub-browse', @@ -43,6 +49,7 @@ export class TbIotHubBrowseComponent implements OnInit, AfterViewInit, OnDestroy } readonly ItemType = ItemType; + readonly scrollThreshold = IOT_HUB_FILTER_SCROLL_THRESHOLD; @Input() creatorId: string; @Input() embedded = false; @@ -212,17 +219,7 @@ export class TbIotHubBrowseComponent implements OnInit, AfterViewInit, OnDestroy if (!el) { return this.probeCols; } - // Force layout so `grid-template-columns` resolves to pixel tracks, not `repeat(...)`. - void el.offsetWidth; - const tracks = getComputedStyle(el).gridTemplateColumns; - if (!tracks || tracks === 'none') { - return 1; - } - if (tracks.startsWith('repeat(')) { - const match = tracks.match(/^repeat\(\s*(\d+)\s*,/); - return match ? parseInt(match[1], 10) : 1; - } - return Math.max(1, tracks.trim().split(/\s+/).filter(t => t.length > 0).length); + return measureGridColumns(el); } private adjustPageSize(): void { diff --git a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-facet-list.component.html b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-facet-list.component.html index 8468ddc04b..658ed108df 100644 --- a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-facet-list.component.html +++ b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-facet-list.component.html @@ -12,9 +12,9 @@ @if (searchable) {