Browse Source

Merge remote-tracking branch 'upstream/lts-4.3' into fix/edge-activity-state-guard-followups-lts-4.3

# Conflicts:
#	application/src/main/java/org/thingsboard/server/service/edge/rpc/EdgeGrpcService.java
pull/16163/head
Nikita Mazurenko 1 month ago
parent
commit
53a02aee86
  1. 4
      TEST_FAST.md
  2. 2
      application/pom.xml
  3. 2
      application/src/main/data/upgrade/basic/schema_update.sql
  4. 29
      application/src/main/data/upgrade/lts/4.3.1.6/schema_update.sql
  5. 4
      application/src/main/java/org/thingsboard/server/actors/tenant/TenantActor.java
  6. 11
      application/src/main/java/org/thingsboard/server/config/ThingsboardSecurityConfiguration.java
  7. 213
      application/src/main/java/org/thingsboard/server/controller/CommunityGrantController.java
  8. 9
      application/src/main/java/org/thingsboard/server/controller/RpcV2Controller.java
  9. 17
      application/src/main/java/org/thingsboard/server/controller/plugin/TbWebSocketHandler.java
  10. 3
      application/src/main/java/org/thingsboard/server/install/ThingsboardInstallService.java
  11. 10
      application/src/main/java/org/thingsboard/server/service/cf/AbstractCalculatedFieldProcessingService.java
  12. 4
      application/src/main/java/org/thingsboard/server/service/cf/ctx/state/alarm/AlarmRuleState.java
  13. 34
      application/src/main/java/org/thingsboard/server/service/community_grant/CommunityGrantBundleFormatException.java
  14. 23
      application/src/main/java/org/thingsboard/server/service/community_grant/CommunityGrantCheckerInput.java
  15. 17
      application/src/main/java/org/thingsboard/server/service/community_grant/CommunityGrantCheckerTooLargeException.java
  16. 9
      application/src/main/java/org/thingsboard/server/service/community_grant/CommunityGrantClusterStatus.java
  17. 122
      application/src/main/java/org/thingsboard/server/service/community_grant/CommunityGrantFlowStateStore.java
  18. 77
      application/src/main/java/org/thingsboard/server/service/community_grant/CommunityGrantLibpqDsn.java
  19. 18
      application/src/main/java/org/thingsboard/server/service/community_grant/CommunityGrantLicenseClaimRefusedException.java
  20. 6
      application/src/main/java/org/thingsboard/server/service/community_grant/CommunityGrantLicenseClaimRequest.java
  21. 10
      application/src/main/java/org/thingsboard/server/service/community_grant/CommunityGrantLicenseClaimResponse.java
  22. 314
      application/src/main/java/org/thingsboard/server/service/community_grant/CommunityGrantOfflineBundle.java
  23. 155
      application/src/main/java/org/thingsboard/server/service/community_grant/CommunityGrantOfflineReportStore.java
  24. 61
      application/src/main/java/org/thingsboard/server/service/community_grant/CommunityGrantPlatform.java
  25. 547
      application/src/main/java/org/thingsboard/server/service/community_grant/CommunityGrantPoller.java
  26. 294
      application/src/main/java/org/thingsboard/server/service/community_grant/CommunityGrantPortalClient.java
  27. 16
      application/src/main/java/org/thingsboard/server/service/community_grant/CommunityGrantPortalStatus.java
  28. 212
      application/src/main/java/org/thingsboard/server/service/community_grant/CommunityGrantReleaseSignatureVerifier.java
  29. 6
      application/src/main/java/org/thingsboard/server/service/community_grant/CommunityGrantReportRequest.java
  30. 9
      application/src/main/java/org/thingsboard/server/service/community_grant/CommunityGrantReportResponse.java
  31. 383
      application/src/main/java/org/thingsboard/server/service/community_grant/CommunityGrantReportRunner.java
  32. 35
      application/src/main/java/org/thingsboard/server/service/community_grant/CommunityGrantService.java
  33. 527
      application/src/main/java/org/thingsboard/server/service/community_grant/DefaultCommunityGrantService.java
  34. 4
      application/src/main/java/org/thingsboard/server/service/edge/EdgeContextComponent.java
  35. 12
      application/src/main/java/org/thingsboard/server/service/edge/EdgeMsgConstructorUtils.java
  36. 257
      application/src/main/java/org/thingsboard/server/service/edge/rpc/EdgeGrpcService.java
  37. 49
      application/src/main/java/org/thingsboard/server/service/edge/rpc/processor/device/DeviceEdgeProcessor.java
  38. 2
      application/src/main/java/org/thingsboard/server/service/install/EntityDatabaseSchemaService.java
  39. 40
      application/src/main/java/org/thingsboard/server/service/install/SqlEntityDatabaseSchemaService.java
  40. 21
      application/src/main/java/org/thingsboard/server/service/install/lts/LtsMigrationService.java
  41. 43
      application/src/main/java/org/thingsboard/server/service/install/lts/V4_3_1_6Migration.java
  42. 60
      application/src/main/java/org/thingsboard/server/service/iot_hub/DefaultIotHubService.java
  43. 27
      application/src/main/java/org/thingsboard/server/service/lwm2m/LwM2MServiceImpl.java
  44. 111
      application/src/main/java/org/thingsboard/server/service/queue/DefaultTbClusterService.java
  45. 42
      application/src/main/java/org/thingsboard/server/service/rpc/TbRpcService.java
  46. 5
      application/src/main/java/org/thingsboard/server/service/security/AccessValidator.java
  47. 36
      application/src/main/java/org/thingsboard/server/service/security/auth/oauth2/CookieUtils.java
  48. 98
      application/src/main/java/org/thingsboard/server/service/security/auth/oauth2/HttpCookieOAuth2AuthorizationRequestRepository.java
  49. 212
      application/src/main/java/org/thingsboard/server/service/solutions/DefaultSolutionService.java
  50. 30
      application/src/main/java/org/thingsboard/server/service/solutions/data/SolutionValidationResult.java
  51. 29
      application/src/main/java/org/thingsboard/server/service/system/SystemPatchApplier.java
  52. 6
      application/src/main/java/org/thingsboard/server/service/telemetry/DefaultTbTelemetryService.java
  53. 76
      application/src/main/java/org/thingsboard/server/service/ws/DefaultWebSocketService.java
  54. 24
      application/src/main/resources/thingsboard.yml
  55. 6
      application/src/test/java/org/thingsboard/server/controller/AbstractControllerTest.java
  56. 7
      application/src/test/java/org/thingsboard/server/controller/AbstractNotifyEntityTest.java
  57. 678
      application/src/test/java/org/thingsboard/server/controller/CommunityGrantControllerTest.java
  58. 24
      application/src/test/java/org/thingsboard/server/controller/DeviceProfileControllerTest.java
  59. 107
      application/src/test/java/org/thingsboard/server/controller/LwM2MServiceImplConfigTest.java
  60. 3
      application/src/test/java/org/thingsboard/server/controller/TbTestWebSocketClient.java
  61. 36
      application/src/test/java/org/thingsboard/server/controller/TelemetryControllerTest.java
  62. 48
      application/src/test/java/org/thingsboard/server/controller/TwoFactorAuthTest.java
  63. 12
      application/src/test/java/org/thingsboard/server/controller/WebsocketApiTest.java
  64. 119
      application/src/test/java/org/thingsboard/server/edge/DeviceEdgeTest.java
  65. 30
      application/src/test/java/org/thingsboard/server/edge/DeviceProfileEdgeTest.java
  66. 90
      application/src/test/java/org/thingsboard/server/install/ThingsboardInstallServiceTest.java
  67. 9
      application/src/test/java/org/thingsboard/server/queue/discovery/HashPartitionServiceTest.java
  68. 99
      application/src/test/java/org/thingsboard/server/service/cf/DefaultCalculatedFieldProcessingServiceTest.java
  69. 126
      application/src/test/java/org/thingsboard/server/service/community_grant/CommunityGrantBundleFixtures.java
  70. 305
      application/src/test/java/org/thingsboard/server/service/community_grant/CommunityGrantFlowStateStoreTest.java
  71. 64
      application/src/test/java/org/thingsboard/server/service/community_grant/CommunityGrantLibpqDsnTest.java
  72. 421
      application/src/test/java/org/thingsboard/server/service/community_grant/CommunityGrantOfflineBundleTest.java
  73. 216
      application/src/test/java/org/thingsboard/server/service/community_grant/CommunityGrantOfflineReportStoreTest.java
  74. 59
      application/src/test/java/org/thingsboard/server/service/community_grant/CommunityGrantPlatformTest.java
  75. 1008
      application/src/test/java/org/thingsboard/server/service/community_grant/CommunityGrantPollerTest.java
  76. 600
      application/src/test/java/org/thingsboard/server/service/community_grant/CommunityGrantPortalClientTest.java
  77. 260
      application/src/test/java/org/thingsboard/server/service/community_grant/CommunityGrantReleaseSignatureVerifierTest.java
  78. 529
      application/src/test/java/org/thingsboard/server/service/community_grant/CommunityGrantReportRunnerTest.java
  79. 50
      application/src/test/java/org/thingsboard/server/service/community_grant/CommunityGrantSigningFixtures.java
  80. 70
      application/src/test/java/org/thingsboard/server/service/community_grant/CommunityGrantStateInfoTest.java
  81. 48
      application/src/test/java/org/thingsboard/server/service/community_grant/CommunityGrantStateTest.java
  82. 143
      application/src/test/java/org/thingsboard/server/service/community_grant/CommunityGrantUploadPayloadLimitTest.java
  83. 149
      application/src/test/java/org/thingsboard/server/service/community_grant/DefaultCommunityGrantServiceConcurrencyTest.java
  84. 1171
      application/src/test/java/org/thingsboard/server/service/community_grant/DefaultCommunityGrantServiceTest.java
  85. 325
      application/src/test/java/org/thingsboard/server/service/edge/rpc/EdgeGrpcServiceReconnectTest.java
  86. 182
      application/src/test/java/org/thingsboard/server/service/edge/rpc/EdgeGrpcServiceTest.java
  87. 34
      application/src/test/java/org/thingsboard/server/service/install/AbstractInstallPostgresTest.java
  88. 60
      application/src/test/java/org/thingsboard/server/service/install/InstallTestSupport.java
  89. 60
      application/src/test/java/org/thingsboard/server/service/install/SchemaUpdateSqlUpgradeOrderTest.java
  90. 106
      application/src/test/java/org/thingsboard/server/service/install/SqlEntityDatabaseSchemaServiceClusterIdTest.java
  91. 39
      application/src/test/java/org/thingsboard/server/service/install/TbClusterDdlDriftTest.java
  92. 83
      application/src/test/java/org/thingsboard/server/service/install/lts/LtsMigrationIntegrationTest.java
  93. 64
      application/src/test/java/org/thingsboard/server/service/install/lts/LtsMigrationServiceTest.java
  94. 70
      application/src/test/java/org/thingsboard/server/service/iot_hub/DefaultIotHubServiceTest.java
  95. 7
      application/src/test/java/org/thingsboard/server/service/job/JobManagerTest.java
  96. 205
      application/src/test/java/org/thingsboard/server/service/queue/DefaultTbClusterServiceTest.java
  97. 86
      application/src/test/java/org/thingsboard/server/service/script/NashornJsInvokeServiceTest.java
  98. 14
      application/src/test/java/org/thingsboard/server/service/script/TbelInvokeServiceTest.java
  99. 45
      application/src/test/java/org/thingsboard/server/service/security/auth/oauth2/CookieUtilsTest.java
  100. 151
      application/src/test/java/org/thingsboard/server/service/security/auth/oauth2/HttpCookieOAuth2AuthorizationRequestRepositoryTest.java

4
TEST_FAST.md

@ -42,10 +42,12 @@ 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 |
`-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

2
application/pom.xml

@ -9,7 +9,7 @@
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.thingsboard</groupId>
<version>4.3.1.6-SNAPSHOT</version>
<version>4.3.1.7-SNAPSHOT</version>
<artifactId>thingsboard</artifactId>
</parent>
<artifactId>application</artifactId>

2
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

29
application/src/main/data/upgrade/lts/4.3.1.6/schema_update.sql

@ -0,0 +1,29 @@
--
-- 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,
license_secret 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
-- 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

4
application/src/main/java/org/thingsboard/server/actors/tenant/TenantActor.java

@ -196,8 +196,8 @@ public class TenantActor extends RuleChainManagerActor {
private void forwardToCfActor(TenantAwareMsg msg, boolean priority) {
if (cfActor == null) {
if (msg instanceof CalculatedFieldStateRestoreMsg) {
log.warn("[{}] CF Actor is not initialized. ToCalculatedFieldSystemMsg: [{}]", tenantId, msg);
if (msg instanceof CalculatedFieldStateRestoreMsg restoreMsg) {
log.warn("[{}] CF Actor is not initialized. Skipping CF state restore: [{}]", tenantId, restoreMsg.getId());
} else {
log.debug("[{}] CF Actor is not initialized. ToCalculatedFieldSystemMsg: [{}]", tenantId, msg);
}

11
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

213
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<CommunityGrantStateInfo> 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<UUID> 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<Resource> 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));
}
}

9
application/src/main/java/org/thingsboard/server/controller/RpcV2Controller.java

@ -12,6 +12,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,6 +36,7 @@ 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.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;
@ -62,6 +64,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. " +
@ -220,13 +225,13 @@ 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(), rpc);
rpc.setStatus(RpcStatus.DELETED);
TbMsg msg = TbMsg.newMsg()

17
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<Authority> USER_AUTHORITIES = EnumSet.of(Authority.SYS_ADMIN, Authority.TENANT_ADMIN, Authority.CUSTOMER_USER);
private final ConcurrentMap<String, SessionMetaData> internalSessionMap = new ConcurrentHashMap<>();
private final ConcurrentMap<String, String> 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) {

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

10
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<CalculatedFieldId> cfIds, long ts, TimeseriesSaveRequest.Strategy strategy, TbCallback callback) {
Map<Long, List<KvEntry>> tsKvMap = JsonConverter.convertToTelemetry(jsonResult, ts);
if (tsKvMap.isEmpty()) {

4
application/src/main/java/org/thingsboard/server/service/cf/ctx/state/alarm/AlarmRuleState.java

@ -4,6 +4,8 @@ package org.thingsboard.server.service.cf.ctx.state.alarm;
import com.fasterxml.jackson.databind.node.ObjectNode;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.ToString;
import lombok.extern.slf4j.Slf4j;
import org.thingsboard.common.util.JacksonUtil;
import org.thingsboard.common.util.KvUtil;
@ -38,6 +40,8 @@ public class AlarmRuleState {
private final AlarmSeverity severity;
private AlarmRule alarmRule;
@ToString.Exclude
@EqualsAndHashCode.Exclude
private AlarmCalculatedFieldState state;
private AlarmCondition condition;

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

23
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<CommunityGrantCheckerInput> from(JsonNode input) {
if (input == null || !input.isObject() || input.isEmpty()) {
return Optional.empty();
}
return Optional.of(new CommunityGrantCheckerInput(JacksonUtil.toString(input)));
}
}

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

9
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) {
}

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

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

18
application/src/main/java/org/thingsboard/server/service/community_grant/CommunityGrantLicenseClaimRefusedException.java

@ -0,0 +1,18 @@
// 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;
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);
}
}

6
application/src/main/java/org/thingsboard/server/service/community_grant/CommunityGrantLicenseClaimRequest.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 CommunityGrantLicenseClaimRequest(String claimToken) {
}

10
application/src/main/java/org/thingsboard/server/service/community_grant/CommunityGrantLicenseClaimResponse.java

@ -0,0 +1,10 @@
// 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;
/** {@code secret} is set only once {@code activated} is true. */
@JsonIgnoreProperties(ignoreUnknown = true)
public record CommunityGrantLicenseClaimResponse(boolean activated, String secret) {
}

314
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.
* <pre>
* 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
* </pre>
* {@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<String> KNOWN_OS = List.of("linux", "darwin", "windows");
private static final List<String> 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<Set<String>> 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<String> 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"));
}
}

155
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<LocalReport> 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<String> get() {
LocalReport localReport = nodeLocalReport.get();
Optional<String> 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) {}
}

61
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<String> KNOWN_OS = List.of("darwin", "windows", "linux");
private static final List<String> 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<String> known, String mine) {
return known.stream().anyMatch(token -> !token.equals(mine) && fileName.contains(token));
}
}

547
application/src/main/java/org/thingsboard/server/service/community_grant/CommunityGrantPoller.java

@ -0,0 +1,547 @@
// 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<PartitionChangeEvent> {
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;
}
if (applyIfTerminal(token, statusValue, now)) {
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 whether the status was a terminal one, even when the flow could not be ended on this poll. */
private boolean applyIfTerminal(String token, String status, long now) {
CommunityGrantState terminalState = terminalStateFor(status);
if (terminalState == null) {
return false;
}
if (terminalState == CommunityGrantState.REGISTERED) {
onDone(token, now);
} else {
retire(token, terminalState, now, null);
}
return true;
}
/** The key is stored before the token is cleared, so a failure above it leaves the next poll to retry. */
private void onDone(String token, long now) {
String licenseSecret;
try {
licenseSecret = portalClient.claimLicense(token);
} catch (CommunityGrantLicenseClaimRefusedException e) {
log.warn("The license portal did not hand over the license key for this registration ({}). "
+ "The registration stands and the key can be entered by hand later", e.getMessage());
retire(token, CommunityGrantState.REGISTERED, now, null);
return;
}
if (StringUtils.isEmpty(licenseSecret)) {
return;
}
tbClusterStore.saveLicenseSecret(licenseSecret);
retire(token, CommunityGrantState.REGISTERED, now, null);
}
/** @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<CommunityGrantCheckerInput> 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;
}
if (applyIfTerminal(token, uploadedStatus, now)) {
return;
}
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<CommunityGrantFlowState> 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();
}
}

294
application/src/main/java/org/thingsboard/server/service/community_grant/CommunityGrantPortalClient.java

@ -0,0 +1,294 @@
// 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.HttpStatus;
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}";
private static final String LICENSE_CLAIM_PATH = "/api/noauth/freeLicense/claim";
/** 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();
}
/**
* This route reads the claim token from the body, not from the header the grant routes use.
*
* @return the granted license key, or {@code null} while the portal has none to hand over yet
* @throws CommunityGrantLicenseClaimRefusedException if the portal refuses the claim
*/
public String claimLicense(String token) {
String url = baseUrl + LICENSE_CLAIM_PATH;
CommunityGrantLicenseClaimResponse response;
try {
response = restTemplate.postForObject(url, new CommunityGrantLicenseClaimRequest(token),
CommunityGrantLicenseClaimResponse.class);
} catch (HttpStatusCodeException e) {
// A rate-limited claim is the one client error that is worth trying again.
if (e.getStatusCode().is4xxClientError()
&& e.getStatusCode().value() != HttpStatus.TOO_MANY_REQUESTS.value()) {
throw new CommunityGrantLicenseClaimRefusedException(e);
}
throw e;
}
return response != null && response.activated() ? response.secret() : null;
}
/**
* @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);
}
}

16
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) {
}

212
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<Integer, PublicKey> 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<Integer, PublicKey> parsePublicKeys(String configured) {
Map<Integer, PublicKey> 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");
}
}
}

6
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) {
}

9
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) {
}

383
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<String> buildCommand(Path checker) {
List<String> 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<ProcessHandle> 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<String, String> 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);
}
}
}

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

527
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<Exception> 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<Exception> 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);
}
}

4
application/src/main/java/org/thingsboard/server/service/edge/EdgeContextComponent.java

@ -47,6 +47,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.ai.AiModelProcessor;
import org.thingsboard.server.service.edge.rpc.processor.apikey.ApiKeyProcessor;
@ -130,6 +131,9 @@ public class EdgeContextComponent {
@Autowired
private DeviceService deviceService;
@Autowired
private TbRpcService tbRpcService;
@Autowired
private DomainService domainService;

12
application/src/main/java/org/thingsboard/server/service/edge/EdgeMsgConstructorUtils.java

@ -326,20 +326,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());
}
@ -366,6 +369,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;
}

257
application/src/main/java/org/thingsboard/server/service/edge/rpc/EdgeGrpcService.java

@ -74,9 +74,11 @@ 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.AtomicReference;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.function.Consumer;
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;
@ -306,13 +308,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);
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 {
@ -320,7 +319,8 @@ public class EdgeGrpcService extends EdgeRpcServiceGrpc.EdgeRpcServiceImplBase i
} finally {
newEventLock.unlock();
}
cancelScheduleEdgeEventsCheck(edgeId);
destroySession(toRemove);
toRemove.cleanUp();
}
cancelPendingDisconnectNotification(edgeId);
}
@ -362,16 +362,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 {
@ -392,9 +388,11 @@ public class EdgeGrpcService extends EdgeRpcServiceGrpc.EdgeRpcServiceImplBase i
// Connect notifies immediately; only the disconnect notification is debounced (see scheduleDisconnectNotification).
pushStateEventToRuleEngine(tenantId, edge, lastConnectTs, TbMsgType.CONNECT_EVENT);
notifyEdgeConnectivity(edge, true);
cancelScheduleEdgeEventsCheck(edgeId);
edgeEventsMigrationProcessed.putIfAbsent(edgeId, Boolean.FALSE);
scheduleEdgeEventsCheck(edgeGrpcSession);
if (replaced != null) {
destroySession(replaced);
}
}
private void startSyncProcess(TenantId tenantId, EdgeId edgeId, UUID requestId, String requestServiceId) {
@ -456,54 +454,73 @@ public class EdgeGrpcService extends EdgeRpcServiceGrpc.EdgeRpcServiceImplBase i
EdgeId edgeId = session.getEdge().getId();
TenantId tenantId = session.getEdge().getTenantId();
cancelScheduleEdgeEventsCheck(edgeId);
// 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(
() -> processEvents(session, edgeId, tenantId),
ctx.getEdgeEventStorageSettings().getNoRecordsSleepInterval(), TimeUnit.MILLISECONDS));
log.trace("[{}] Check edge event scheduled for edge [{}]", tenantId, edgeId.getId());
return current;
});
}
if (sessions.containsKey(edgeId)) {
ScheduledFuture<?> edgeEventCheckTask = edgeEventProcessingExecutorService.schedule(() -> {
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);
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 {
@Override
public void onFailure(Throwable t) {
log.warn("[{}] Failed to process edge events for edge [{}]!", tenantId, session.getEdge().getId().getId(), t);
scheduleEdgeEventsCheck(session);
}
} else {
scheduleEdgeEventsCheck(session);
}
} finally {
newEventLock.unlock();
}, ctx.getGrpcCallbackExecutorService());
} else {
scheduleEdgeEventsCheck(session);
}
} catch (Exception e) {
log.warn("[{}] Failed to process edge events for edge [{}]!", tenantId, session.getEdge().getId().getId(), e);
} else {
scheduleEdgeEventsCheck(session);
}
}, ctx.getEdgeEventStorageSettings().getNoRecordsSleepInterval(), TimeUnit.MILLISECONDS);
sessionEdgeEventChecks.put(edgeId, edgeEventCheckTask);
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());
} finally {
newEventLock.unlock();
}
} catch (Exception e) {
log.warn("[{}] Failed to process edge events for edge [{}]!", tenantId, session.getEdge().getId().getId(), e);
}
}
@ -531,58 +548,26 @@ 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);
// Claim-once removal: get() and remove() are not atomic, so a session that was replaced between the
// two would otherwise be dropped from the map, torn down and marked inactive by this stale callback
// even though it is the live one. Losing the race means this callback owns nothing - fall through to
// the stale-session branch below.
if (current != null && current.getSessionId().equals(sessionId) && sessions.remove(edgeId, current)) {
EdgeGrpcSession toRemove = current;
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);
TenantId tenantId = toRemove.getEdge().getTenantId();
// The edge may already have been claimed by a newer session - on this node (a replacement that
// landed while this stale callback was tearing its own session down) or on another live node.
// Either way the edge is connected, so none of the disconnect side effects apply:
// - clearing the flag makes saveEdgeEvent drop assignment events until a full sync;
// - a newer lastDisconnectTime would contradict the live session's lastConnectTime;
// - the DISCONNECT_EVENT payload is {"active": false, ...} with SERVER_SCOPE in the metadata,
// so a rule chain wiring Disconnect Event -> Save Attributes writes active=false straight
// back, re-creating the dropped-event behaviour through the rule engine;
// - the user-facing 'edge disconnected' notification would contradict a live session.
// Ownership being unknown (no cache entry) still counts as disconnected, so a genuinely offline
// edge is always marked inactive.
boolean replacedOnThisNode = sessions.containsKey(edgeId);
if (!replacedOnThisNode && !isOwnedByAnotherNode(edgeId)) {
// A newer session may already own the edge, on this node or on another live one. In that case the edge
// is connected, so skip all disconnect side effects: active=false, lastDisconnectTime, DISCONNECT_EVENT
// (its payload can write active=false back via Save Attributes) and the disconnect notification.
// Unknown ownership (no cache entry) still counts as disconnected. The local map is read last, after
// the cache round-trip, to see a same-node replacement as late as possible.
if (!isOwnedByAnotherNode(edgeId) && !sessions.containsKey(edgeId)) {
save(tenantId, edgeId, ACTIVITY_STATE, false);
long lastDisconnectTs = System.currentTimeMillis();
save(tenantId, edgeId, LAST_DISCONNECT_TIME, lastDisconnectTs);
pushStateEventToRuleEngine(toRemove.getEdge().getTenantId(), edge, lastDisconnectTs, TbMsgType.DISCONNECT_EVENT);
// Inside the guard, not after it. fireDelayedDisconnectNotification does re-verify liveness,
// but only on the debounced path: with EDGES_DISCONNECT_NOTIFICATION_DELAY_MS=0
// scheduleDisconnectNotification notifies straight away and skips that re-verify, so a live
// replacement would still raise a false 'edge disconnected'. The guard above has already
// answered the same question, so use it. On the debounced path this only saves a task that
// would have re-verified and dropped the notification anyway.
pushStateEventToRuleEngine(tenantId, edge, lastDisconnectTs, TbMsgType.DISCONNECT_EVENT);
scheduleDisconnectNotification(edge);
}
// sessionEdgeEventChecks is keyed by edgeId, not by session, so a replacement that landed on this
// node while this stale callback was running has already scheduled its check under the same key.
// Cancelling it here would leave the live session with no check loop - the loop only reschedules
// itself from inside the task, so a cancelled task never runs again - and downlinks, the migration
// check and high-priority events would stall silently until the edge reconnects. When the edge is
// owned by another node there is nothing live to protect: the check is node-local and belongs to
// the session we just tore down.
if (!replacedOnThisNode) {
cancelScheduleEdgeEventsCheck(edgeId);
}
destroySession(toRemove);
} else {
log.info("[{}] edge session [{}] is not current anymore. Attempting to destroy it by sessionId.", edgeId, sessionId);
EdgeGrpcSession stale = sessionsById.remove(sessionId);
@ -605,6 +590,53 @@ 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.
* <p>
* 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<EdgeGrpcSession> replaced = new AtomicReference<>();
sessions.compute(edgeId, (id, current) -> {
replaced.set(current);
cancelScheduleEdgeEventsCheck(edgeId);
return session;
});
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.
* <p>
* 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<EdgeGrpcSession> shouldDetach) {
AtomicReference<EdgeGrpcSession> 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();
}
// Only evict if the cache still points to this node. If the edge already reconnected to a different
// TB-Core node within the keep-alive window, that node has overwritten the entry - evicting it here
// would wipe the live owner and make fireDelayedDisconnectNotification raise a false 'disconnected'.
@ -627,11 +659,6 @@ public class EdgeGrpcService extends EdgeRpcServiceGrpc.EdgeRpcServiceImplBase i
// - entry naming a node that is no longer in the cluster: the edge sessions cache has no TTL by default
// (CACHE_SPECS_EDGE_SESSIONS_TTL=0) and is only ever evicted by the owning node, so a node that died
// without evicting would otherwise keep the edge marked active forever, with no reconciler to correct it.
// Note this covers a node that is gone, not one that restarted under the same service id - that claim
// still resolves as live, leaving the edge marked active until something reconnects. That errs towards
// queueing edge events rather than dropping them, which is the safe direction.
// This narrows the race rather than closing it: the attribute is plain last-writer-wins, and two nodes can
// still issue their async writes in an order this read cannot see.
private boolean isOwnedByAnotherNode(EdgeId edgeId) {
TbCacheValueWrapper<String> wrapper = edgeIdServiceIdCache.get(edgeId);
if (wrapper == null) {
@ -649,6 +676,12 @@ public class EdgeGrpcService extends EdgeRpcServiceGrpc.EdgeRpcServiceImplBase i
return edgeIdServiceIdCache.get(edgeId) != null;
}
/**
* 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()) {
@ -863,10 +896,10 @@ public class EdgeGrpcService extends EdgeRpcServiceGrpc.EdgeRpcServiceImplBase i
private void cleanupZombieSessions() {
try {
// Compare-and-remove: destroy() above is not instantaneous, so the edge may have reconnected and
// put a live session under this id in the meantime. Removing it unconditionally would leave a
// connected edge with no entry in 'sessions', silently no-opping every downlink lookup.
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 -> {

49
application/src/main/java/org/thingsboard/server/service/edge/rpc/processor/device/DeviceEdgeProcessor.java

@ -9,6 +9,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;
@ -24,7 +25,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;
@ -116,7 +120,10 @@ public class DeviceEdgeProcessor extends BaseDeviceProcessor implements DevicePr
@Override
public ListenableFuture<Void> 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, edge, deviceRpcCallMsg);
} else if (deviceRpcCallMsg.hasResponseMsg()) {
return processDeviceRpcResponseFromEdge(tenantId, deviceRpcCallMsg);
} else if (deviceRpcCallMsg.hasRequestMsg()) {
return processDeviceRpcRequestFromEdge(tenantId, edge, deviceRpcCallMsg);
@ -124,6 +131,46 @@ public class DeviceEdgeProcessor extends BaseDeviceProcessor implements DevicePr
return Futures.immediateFuture(null);
}
private ListenableFuture<Void> 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.
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());
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())) {
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);
}
private ListenableFuture<Void> processDeviceRpcResponseFromEdge(TenantId tenantId, DeviceRpcCallMsg deviceRpcCallMsg) {
SettableFuture<Void> futureToSet = SettableFuture.create();
UUID requestUuid = new UUID(deviceRpcCallMsg.getRequestUuidMSB(), deviceRpcCallMsg.getRequestUuidLSB());

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

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

21
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<VersionedMigration> 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. */

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

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

@ -7,9 +7,9 @@ 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.asset.AssetProfile;
import org.thingsboard.server.common.data.Dashboard;
import org.thingsboard.server.common.data.DeviceProfile;
import org.thingsboard.server.common.data.cf.CalculatedField;
import org.thingsboard.server.common.data.cf.CalculatedFieldType;
@ -25,7 +25,6 @@ import org.thingsboard.server.common.data.id.RuleChainId;
import org.thingsboard.server.common.data.id.TenantId;
import org.thingsboard.server.common.data.iot_hub.AlarmRuleInstalledItemDescriptor;
import org.thingsboard.server.common.data.iot_hub.CalculatedFieldInstalledItemDescriptor;
import org.thingsboard.server.common.data.iot_hub.DashboardInstalledItemDescriptor;
import org.thingsboard.server.common.data.iot_hub.DeviceInstalledItemDescriptor;
import org.thingsboard.server.common.data.iot_hub.IotHubInstalledItem;
import org.thingsboard.server.common.data.iot_hub.IotHubInstalledItemDescriptor;
@ -82,7 +81,6 @@ public class DefaultIotHubService implements IotHubService {
private static final String SECTION_RULE_CHAIN_METADATA = "rule chain metadata";
private static final String ITEM_TYPE_WIDGET = "widget";
private static final String ITEM_TYPE_DASHBOARD = "dashboard";
private static final String ITEM_TYPE_CALCULATED_FIELD = "calculated field";
private static final String ITEM_TYPE_ALARM_RULE = "alarm rule";
private static final String ITEM_TYPE_RULE_CHAIN = "rule chain";
@ -157,7 +155,6 @@ public class DefaultIotHubService implements IotHubService {
IotHubInstalledItemDescriptor descriptor = switch (itemType) {
case "WIDGET" -> installWidget(user, tenantId, fileData);
case "DASHBOARD" -> installDashboard(user, tenantId, fileData);
case "CALCULATED_FIELD" -> installCalculatedField(user, tenantId, fileData, data);
case "ALARM_RULE" -> installAlarmRule(user, tenantId, fileData, data);
case "RULE_CHAIN" -> installRuleChain(user, tenantId, fileData, data);
@ -218,22 +215,6 @@ public class DefaultIotHubService implements IotHubService {
return descriptor;
}
private DashboardInstalledItemDescriptor installDashboard(SecurityUser user, TenantId tenantId, byte[] fileData) throws Exception {
Dashboard dashboard;
try {
dashboard = JacksonUtil.fromString(new String(fileData), Dashboard.class, true);
} catch (Exception e) {
throw parseFailure(ACTION_INSTALL, ITEM_TYPE_DASHBOARD, e);
}
dashboard.setId(null);
dashboard.setTenantId(tenantId);
Dashboard saved = tbDashboardService.save(dashboard, user);
log.debug("[{}] Dashboard installed: {}", tenantId, saved.getTitle());
DashboardInstalledItemDescriptor descriptor = new DashboardInstalledItemDescriptor();
descriptor.setDashboardId(saved.getId());
return descriptor;
}
private CalculatedFieldInstalledItemDescriptor installCalculatedField(SecurityUser user, TenantId tenantId, byte[] fileData, JsonNode data) throws Exception {
CalculatedField calculatedField;
try {
@ -435,7 +416,6 @@ public class DefaultIotHubService implements IotHubService {
switch (itemType) {
case "WIDGET" -> updateWidget(user, tenantId, (WidgetInstalledItemDescriptor) descriptor, fileData);
case "DASHBOARD" -> updateDashboard(user, tenantId, (DashboardInstalledItemDescriptor) descriptor, fileData);
case "CALCULATED_FIELD" -> updateCalculatedField(user, tenantId, (CalculatedFieldInstalledItemDescriptor) descriptor, fileData);
case "ALARM_RULE" -> updateAlarmRule(user, tenantId, (AlarmRuleInstalledItemDescriptor) descriptor, fileData);
case "RULE_CHAIN" -> updateRuleChain(tenantId, (RuleChainInstalledItemDescriptor) descriptor, fileData);
@ -493,22 +473,6 @@ public class DefaultIotHubService implements IotHubService {
tbWidgetTypeService.save(existing, false, user);
}
private void updateDashboard(SecurityUser user, TenantId tenantId, DashboardInstalledItemDescriptor descriptor, byte[] fileData) throws Exception {
Dashboard newDashboard;
try {
newDashboard = JacksonUtil.fromString(new String(fileData), Dashboard.class, true);
} catch (Exception e) {
throw parseFailure(ACTION_UPDATE, ITEM_TYPE_DASHBOARD, e);
}
Dashboard existing = dashboardService.findDashboardById(tenantId, descriptor.getDashboardId());
if (existing == null) {
throw new Exception("Dashboard not found for update");
}
existing.setTitle(newDashboard.getTitle());
existing.setConfiguration(newDashboard.getConfiguration());
tbDashboardService.save(existing, user);
}
private void updateCalculatedField(SecurityUser user, TenantId tenantId, CalculatedFieldInstalledItemDescriptor descriptor, byte[] fileData) throws Exception {
CalculatedField newCf;
try {
@ -575,8 +539,6 @@ public class DefaultIotHubService implements IotHubService {
IotHubInstalledItemDescriptor descriptor = installedItem.getDescriptor();
if (descriptor instanceof WidgetInstalledItemDescriptor wd) {
return calculateWidgetChecksum(tenantId, wd);
} else if (descriptor instanceof DashboardInstalledItemDescriptor dd) {
return calculateDashboardChecksum(tenantId, dd);
} else if (descriptor instanceof CalculatedFieldInstalledItemDescriptor cd) {
return calculateCalculatedFieldChecksum(tenantId, cd.getCalculatedFieldId());
} else if (descriptor instanceof AlarmRuleInstalledItemDescriptor ad) {
@ -598,16 +560,6 @@ public class DefaultIotHubService implements IotHubService {
return sha256(content);
}
private String calculateDashboardChecksum(TenantId tenantId, DashboardInstalledItemDescriptor descriptor) {
Dashboard dashboard = dashboardService.findDashboardById(tenantId, descriptor.getDashboardId());
if (dashboard == null) {
return null;
}
String content = (dashboard.getTitle() != null ? dashboard.getTitle() : "") +
(dashboard.getConfiguration() != null ? dashboard.getConfiguration().toString() : "");
return sha256(content);
}
private String calculateWidgetChecksum(TenantId tenantId, WidgetInstalledItemDescriptor descriptor) {
WidgetTypeDetails widgetType = widgetTypeService.findWidgetTypeDetailsById(tenantId, descriptor.getWidgetTypeId());
if (widgetType == null) {
@ -780,11 +732,6 @@ public class DefaultIotHubService implements IotHubService {
if (widgetType != null) {
tbWidgetTypeService.delete(widgetType, user);
}
} else if (descriptor instanceof DashboardInstalledItemDescriptor dd) {
Dashboard dashboard = dashboardService.findDashboardById(tenantId, dd.getDashboardId());
if (dashboard != null) {
tbDashboardService.delete(dashboard, user);
}
} else if (descriptor instanceof CalculatedFieldInstalledItemDescriptor cd) {
CalculatedField calculatedField = calculatedFieldService.findById(tenantId, cd.getCalculatedFieldId());
if (calculatedField != null) {
@ -993,12 +940,13 @@ 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());
String failureMessage = ExceptionUtil.getMessage(e);
resultEntry.setErrorMessage(failureMessage);
resultEntries.add(resultEntry);
boolean rolledBack = rollbackInstalledItems(user, rollbackIds);
result.setSuccess(false);
result.setRolledBack(rolledBack);
result.setErrorMessage("Failed to install '" + entry.getName() + "': " + e.getMessage());
result.setErrorMessage(failureMessage);
result.setEntries(resultEntries);
result.setMissingItemIds(missingItemIds);
return result;

27
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;
@ -14,6 +15,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
@ -28,20 +31,34 @@ 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);
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 (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);
}
bsServ.setSecurityHost(bsServerConfig.getSecureHost());
bsServ.setSecurityPort(bsServerConfig.getSecurePort());
byte[] publicKeyBase64 = getPublicKey(bsServerConfig);

111
application/src/main/java/org/thingsboard/server/service/queue/DefaultTbClusterService.java

@ -7,9 +7,11 @@ import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Lazy;
import org.springframework.context.event.EventListener;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.thingsboard.common.util.JacksonUtil;
import org.thingsboard.common.util.SetCache;
import org.thingsboard.server.cache.TbTransactionalCache;
import org.thingsboard.server.cluster.TbClusterService;
import org.thingsboard.server.common.data.ApiUsageState;
@ -85,6 +87,7 @@ import org.thingsboard.server.queue.common.TbProtoQueueMsg;
import org.thingsboard.server.queue.common.TbRuleEngineProducerService;
import org.thingsboard.server.queue.discovery.PartitionService;
import org.thingsboard.server.queue.discovery.TopicService;
import org.thingsboard.server.queue.discovery.event.ServiceListChangedEvent;
import org.thingsboard.server.queue.provider.TbQueueProducerProvider;
import org.thingsboard.server.service.gateway_device.GatewayNotificationsService;
import org.thingsboard.server.service.ota.OtaPackageStateService;
@ -118,6 +121,12 @@ public class DefaultTbClusterService implements TbClusterService {
private final AtomicInteger toTransportNfs = new AtomicInteger(0);
private final AtomicInteger toEdgeMsgs = new AtomicInteger(0);
private final AtomicInteger toEdgeNfs = new AtomicInteger(0);
private final AtomicInteger skippedUnknownServiceNfs = new AtomicInteger(0);
private static final int RECENTLY_SEEN_SERVICES_MAX_SIZE = 1024;
// serviceType:serviceId -> seen. Bounded LRU of cluster members ever observed, used to grace a service id that is
// briefly missing from the live snapshot (see isUnknownService). Fed from ServiceListChangedEvent.
private final SetCache<String> recentlySeenServices = SetCache.boundedBySize(RECENTLY_SEEN_SERVICES_MAX_SIZE);
@Autowired
private PartitionService partitionService;
@ -197,6 +206,10 @@ public class DefaultTbClusterService implements TbClusterService {
@Override
public void pushNotificationToCore(String serviceId, FromDeviceRpcResponse response, TbQueueCallback callback) {
if (isUnknownService(ServiceType.TB_CORE, serviceId)) {
skipNotificationToUnknownService(ServiceType.TB_CORE, serviceId, callback);
return;
}
TopicPartitionInfo tpi = topicService.getNotificationsTopic(ServiceType.TB_CORE, serviceId);
log.trace("PUSHING msg: {} to:{}", response, tpi);
FromDeviceRPCResponseProto.Builder builder = FromDeviceRPCResponseProto.newBuilder()
@ -211,12 +224,93 @@ public class DefaultTbClusterService implements TbClusterService {
@Override
public void pushNotificationToCore(String targetServiceId, TransportProtos.RestApiCallResponseMsgProto responseMsgProto, TbQueueCallback callback) {
if (isUnknownService(ServiceType.TB_CORE, targetServiceId)) {
skipNotificationToUnknownService(ServiceType.TB_CORE, targetServiceId, callback);
return;
}
TopicPartitionInfo tpi = topicService.getNotificationsTopic(ServiceType.TB_CORE, targetServiceId);
ToCoreNotificationMsg msg = ToCoreNotificationMsg.newBuilder().setRestApiCallResponseMsg(responseMsgProto).build();
producerProvider.getTbCoreNotificationsMsgProducer().send(tpi, new TbProtoQueueMsg<>(UUID.randomUUID(), msg), callback);
toCoreNfs.incrementAndGet();
}
/**
* Per-service notification topics ({@code <notifications-topic>.<serviceId>}) are auto-created by the producer on
* first send. A {@code serviceId} that is not a member of the cluster - e.g. a stale node id or a value injected
* via message metadata - would therefore create an orphan topic that nobody ever consumes and that is never
* cleaned up. To prevent that, notifications whose target service id is not a current member of the cluster are
* skipped.
* <p>
* This is a safety net for never-real ids, not a precise gatekeeper, so it is deliberately lenient. A service id is
* treated as known if it is either a current member ({@link PartitionService#isKnownServiceId}) or a recently seen
* one ({@link #recentlySeenServices}). The recently-seen grace covers nodes that are briefly absent from the live
* snapshot - a discovery-propagation lag, a rolling restart or a transient scale-down - so legitimate replies to
* them are not dropped; genuine non-delivery to a node that is actually gone is already handled by the caller-side
* RPC/REST timeout. The check also fails open while the cluster topology is not yet known (empty/absent membership,
* e.g. right after startup).
*/
private boolean isUnknownService(ServiceType serviceType, String serviceId) {
if (serviceId == null || serviceId.isEmpty()) {
return true;
}
if (partitionService.isKnownServiceId(serviceType, serviceId)) {
return false; // currently a live member
}
Set<String> serviceIds = partitionService.getAllServiceIds(serviceType);
if (serviceIds == null || serviceIds.isEmpty()) {
return false; // topology not known yet - fail open
}
return !recentlySeenServices.contains(recentlySeenServiceKey(serviceType, serviceId));
}
private void skipNotificationToUnknownService(ServiceType serviceType, String serviceId, TbQueueCallback callback) {
log.debug("Skipping notification push to unknown {} service id [{}]", serviceType, serviceId);
skippedUnknownServiceNfs.incrementAndGet();
if (callback != null) {
// Deliberate skip - the target is not a cluster member. Complete the callback as a no-op success,
// matching pushNotificationToTransport, so callers don't treat an intentional skip as a delivery error.
callback.onSuccess(null);
}
}
/**
* Records every observed cluster member so that {@link #isUnknownService} can grace a service id that has dropped
* out of the live snapshot (propagation lag, rolling restart, transient scale-down) instead of dropping
* notifications to it. Bounded by {@link #RECENTLY_SEEN_SERVICES_MAX_SIZE} with LRU eviction, so an id that is gone
* for good eventually ages out and the guard tightens again. Discovery events are change-only, so this never
* removes entries - it only adds; the live-snapshot check in {@link #isUnknownService} stays authoritative for
* current members.
*/
@EventListener
public void onServiceListChanged(ServiceListChangedEvent event) {
rememberSeenService(event.getCurrentService());
List<TransportProtos.ServiceInfo> otherServices = event.getOtherServices();
if (otherServices != null) {
otherServices.forEach(this::rememberSeenService);
}
}
private void rememberSeenService(TransportProtos.ServiceInfo serviceInfo) {
if (serviceInfo == null) {
return;
}
String serviceId = serviceInfo.getServiceId();
if (serviceId == null || serviceId.isEmpty()) {
return;
}
for (String serviceType : serviceInfo.getServiceTypesList()) {
recentlySeenServices.add(recentlySeenServiceKey(serviceType, serviceId));
}
}
private static String recentlySeenServiceKey(ServiceType serviceType, String serviceId) {
return recentlySeenServiceKey(serviceType.name(), serviceId);
}
private static String recentlySeenServiceKey(String serviceType, String serviceId) {
return serviceType + ":" + serviceId;
}
@Override
public void pushMsgToRuleEngine(TopicPartitionInfo tpi, UUID msgId, ToRuleEngineMsg msg, TbQueueCallback callback) {
log.trace("PUSHING msg: {} to:{}", msg, tpi);
@ -311,6 +405,10 @@ public class DefaultTbClusterService implements TbClusterService {
@Override
public void pushNotificationToRuleEngine(String serviceId, FromDeviceRpcResponse response, TbQueueCallback callback) {
if (isUnknownService(ServiceType.TB_RULE_ENGINE, serviceId)) {
skipNotificationToUnknownService(ServiceType.TB_RULE_ENGINE, serviceId, callback);
return;
}
TopicPartitionInfo tpi = topicService.getNotificationsTopic(ServiceType.TB_RULE_ENGINE, serviceId);
log.trace("PUSHING msg: {} to:{}", response, tpi);
FromDeviceRPCResponseProto.Builder builder = FromDeviceRPCResponseProto.newBuilder()
@ -325,11 +423,8 @@ public class DefaultTbClusterService implements TbClusterService {
@Override
public void pushNotificationToTransport(String serviceId, ToTransportMsg response, TbQueueCallback callback) {
if (serviceId == null || serviceId.isEmpty()) {
log.trace("pushNotificationToTransport: skipping message without serviceId [{}], (ToTransportMsg) response [{}]", serviceId, response);
if (callback != null) {
callback.onSuccess(null); //callback that message already sent, no useful payload expected
}
if (isUnknownService(ServiceType.TB_TRANSPORT, serviceId)) {
skipNotificationToUnknownService(ServiceType.TB_TRANSPORT, serviceId, callback);
return;
}
TopicPartitionInfo tpi = topicService.getNotificationsTopic(ServiceType.TB_TRANSPORT, serviceId);
@ -632,9 +727,11 @@ public class DefaultTbClusterService implements TbClusterService {
int toTransportNfsCnt = toTransportNfs.getAndSet(0);
int toEdgeMsgCnt = toEdgeMsgs.getAndSet(0);
int toEdgeNfsCnt = toEdgeNfs.getAndSet(0);
if (toCoreMsgCnt > 0 || toCoreNfsCnt > 0 || toRuleEngineMsgsCnt > 0 || toRuleEngineNfsCnt > 0 || toTransportNfsCnt > 0 || toEdgeMsgCnt > 0 || toEdgeNfsCnt > 0) {
int skippedUnknownServiceNfsCnt = skippedUnknownServiceNfs.getAndSet(0);
if (toCoreMsgCnt > 0 || toCoreNfsCnt > 0 || toRuleEngineMsgsCnt > 0 || toRuleEngineNfsCnt > 0 || toTransportNfsCnt > 0 || toEdgeMsgCnt > 0 || toEdgeNfsCnt > 0 || skippedUnknownServiceNfsCnt > 0) {
log.info("To TbCore: [{}] messages [{}] notifications; To TbRuleEngine: [{}] messages [{}] notifications; To Transport: [{}] notifications;" +
"To Edge: [{}] messages [{}] notifications", toCoreMsgCnt, toCoreNfsCnt, toRuleEngineMsgsCnt, toRuleEngineNfsCnt, toTransportNfsCnt, toEdgeMsgCnt, toEdgeNfsCnt);
"To Edge: [{}] messages [{}] notifications; Skipped notifications to unknown service id: [{}]",
toCoreMsgCnt, toCoreNfsCnt, toRuleEngineMsgsCnt, toRuleEngineNfsCnt, toTransportNfsCnt, toEdgeMsgCnt, toEdgeNfsCnt, skippedUnknownServiceNfsCnt);
}
}
}

42
application/src/main/java/org/thingsboard/server/service/rpc/TbRpcService.java

@ -3,12 +3,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;
@ -18,9 +24,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.dao.edge.EdgeEventService;
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
@ -28,6 +39,9 @@ import org.thingsboard.server.queue.util.TbCoreComponent;
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) {
Rpc saved = rpcService.save(rpc);
@ -67,4 +81,32 @@ public class TbRpcService {
return rpcService.findAllByDeviceIdAndStatus(tenantId, deviceId, rpcStatus, pageLink);
}
/**
* 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);
}
}
private void pushRpcDeleteToEdges(TenantId tenantId, Rpc rpc) {
List<EdgeId> 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) {
// 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);
edgeEventService.saveAsync(edgeEvent);
}
}
}

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

@ -263,6 +263,7 @@ public class AccessValidator {
accessControlService.checkPermission(currentUser, Resource.DEVICE_PROFILE, operation, entityId, deviceProfile);
} catch (ThingsboardException e) {
callback.onSuccess(ValidationResult.accessDenied(e.getMessage()));
return;
}
callback.onSuccess(ValidationResult.ok(deviceProfile));
}
@ -281,6 +282,7 @@ public class AccessValidator {
accessControlService.checkPermission(currentUser, Resource.ASSET_PROFILE, operation, entityId, assetProfile);
} catch (ThingsboardException e) {
callback.onSuccess(ValidationResult.accessDenied(e.getMessage()));
return;
}
callback.onSuccess(ValidationResult.ok(assetProfile));
}
@ -293,6 +295,7 @@ public class AccessValidator {
} else {
if (!operation.equals(Operation.READ_TELEMETRY)) {
callback.onSuccess(ValidationResult.accessDenied("Allowed only READ_TELEMETRY operation!"));
return;
}
ApiUsageState apiUsageState = apiUsageStateService.findApiUsageStateById(currentUser.getTenantId(), new ApiUsageStateId(entityId.getId()));
if (apiUsageState == null) {
@ -302,6 +305,7 @@ public class AccessValidator {
accessControlService.checkPermission(currentUser, Resource.API_USAGE_STATE, operation, entityId, apiUsageState);
} catch (ThingsboardException e) {
callback.onSuccess(ValidationResult.accessDenied(e.getMessage()));
return;
}
callback.onSuccess(ValidationResult.ok(apiUsageState));
}
@ -320,6 +324,7 @@ public class AccessValidator {
accessControlService.checkPermission(currentUser, Resource.OTA_PACKAGE, operation, entityId, otaPackage);
} catch (ThingsboardException e) {
callback.onSuccess(ValidationResult.accessDenied(e.getMessage()));
return;
}
callback.onSuccess(ValidationResult.ok(otaPackage));
}

36
application/src/main/java/org/thingsboard/server/service/security/auth/oauth2/CookieUtils.java

@ -2,30 +2,14 @@
// SPDX-License-Identifier: Apache-2.0
package org.thingsboard.server.service.security.auth.oauth2;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.jackson2.SecurityJackson2Modules;
import java.io.IOException;
import java.util.Arrays;
import java.util.Base64;
import java.util.Optional;
@Slf4j
public class CookieUtils {
private static final ObjectMapper OBJECT_MAPPER;
static {
ClassLoader loader = CookieUtils.class.getClassLoader();
OBJECT_MAPPER = new ObjectMapper();
OBJECT_MAPPER.registerModules(SecurityJackson2Modules.getModules(loader));
}
public static Optional<Cookie> getCookie(HttpServletRequest request, String name) {
Cookie[] cookies = request.getCookies();
@ -61,24 +45,4 @@ public class CookieUtils {
}
}
}
public static String serialize(Object object) {
try {
return Base64.getUrlEncoder()
.encodeToString(OBJECT_MAPPER.writeValueAsBytes(object));
} catch (JsonProcessingException e) {
throw new IllegalArgumentException("The given Json object value: "
+ object + " cannot be transformed to a String", e);
}
}
public static <T> T deserialize(Cookie cookie, Class<T> cls) {
byte[] decodedBytes = Base64.getUrlDecoder().decode(cookie.getValue());
try {
return OBJECT_MAPPER.readValue(decodedBytes, cls);
} catch (IOException e) {
throw new IllegalArgumentException("The given string value: "
+ Arrays.toString(decodedBytes) + " cannot be transformed to Json object", e);
}
}
}

98
application/src/main/java/org/thingsboard/server/service/security/auth/oauth2/HttpCookieOAuth2AuthorizationRequestRepository.java

@ -2,13 +2,34 @@
// SPDX-License-Identifier: Apache-2.0
package org.thingsboard.server.service.security.auth.oauth2;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.bouncycastle.crypto.digests.SHA256Digest;
import org.bouncycastle.crypto.generators.HKDFBytesGenerator;
import org.bouncycastle.crypto.params.HKDFParameters;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.jackson2.SecurityJackson2Modules;
import org.springframework.security.oauth2.client.web.AuthorizationRequestRepository;
import org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationRequest;
import org.springframework.stereotype.Component;
import org.thingsboard.server.queue.util.TbCoreComponent;
import org.thingsboard.server.service.security.auth.jwt.settings.JwtSettingsService;
import javax.crypto.Cipher;
import javax.crypto.spec.GCMParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import java.security.GeneralSecurityException;
import java.security.SecureRandom;
import java.time.Clock;
import java.util.Arrays;
import java.util.Base64;
@Slf4j
@Component
@TbCoreComponent
public class HttpCookieOAuth2AuthorizationRequestRepository implements AuthorizationRequestRepository<OAuth2AuthorizationRequest> {
@ -17,10 +38,31 @@ public class HttpCookieOAuth2AuthorizationRequestRepository implements Authoriza
public static final String PREV_URI_COOKIE_NAME = "prev_uri";
private static final int cookieExpireSeconds = 180;
private static final byte[] KEY_DERIVATION_INFO = "thingsboard-oauth2-authorization-request-cookie".getBytes(StandardCharsets.UTF_8);
private static final int KEY_LENGTH = 32;
private static final int NONCE_LENGTH = 12;
private static final int TAG_LENGTH_BITS = 128;
private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper()
.registerModules(SecurityJackson2Modules.getModules(HttpCookieOAuth2AuthorizationRequestRepository.class.getClassLoader()));
private final JwtSettingsService jwtSettingsService;
private final Clock clock;
private final SecureRandom secureRandom = new SecureRandom();
@Autowired
public HttpCookieOAuth2AuthorizationRequestRepository(JwtSettingsService jwtSettingsService) {
this(jwtSettingsService, Clock.systemUTC());
}
HttpCookieOAuth2AuthorizationRequestRepository(JwtSettingsService jwtSettingsService, Clock clock) {
this.jwtSettingsService = jwtSettingsService;
this.clock = clock;
}
@Override
public OAuth2AuthorizationRequest loadAuthorizationRequest(HttpServletRequest request) {
return CookieUtils.getCookie(request, OAUTH2_AUTHORIZATION_REQUEST_COOKIE_NAME)
.map(cookie -> CookieUtils.deserialize(cookie, OAuth2AuthorizationRequest.class))
.map(this::decrypt)
.orElse(null);
}
@ -34,7 +76,7 @@ public class HttpCookieOAuth2AuthorizationRequestRepository implements Authoriza
if (PrevUriValidator.isValid(prevUri)) {
CookieUtils.addCookie(response, PREV_URI_COOKIE_NAME, prevUri, cookieExpireSeconds);
}
CookieUtils.addCookie(response, OAUTH2_AUTHORIZATION_REQUEST_COOKIE_NAME, CookieUtils.serialize(authorizationRequest), cookieExpireSeconds);
CookieUtils.addCookie(response, OAUTH2_AUTHORIZATION_REQUEST_COOKIE_NAME, encrypt(authorizationRequest), cookieExpireSeconds);
}
@Override
@ -45,4 +87,56 @@ public class HttpCookieOAuth2AuthorizationRequestRepository implements Authoriza
public void removeAuthorizationRequestCookies(HttpServletRequest request, HttpServletResponse response) {
CookieUtils.deleteCookie(request, response, OAUTH2_AUTHORIZATION_REQUEST_COOKIE_NAME);
}
private String encrypt(OAuth2AuthorizationRequest authorizationRequest) {
try {
byte[] json = OBJECT_MAPPER.writeValueAsBytes(authorizationRequest);
byte[] plaintext = ByteBuffer.allocate(Long.BYTES + json.length).putLong(clock.millis()).put(json).array();
byte[] nonce = new byte[NONCE_LENGTH];
secureRandom.nextBytes(nonce);
byte[] ciphertext = initCipher(Cipher.ENCRYPT_MODE, nonce).doFinal(plaintext);
byte[] envelope = ByteBuffer.allocate(NONCE_LENGTH + ciphertext.length).put(nonce).put(ciphertext).array();
return Base64.getUrlEncoder().withoutPadding().encodeToString(envelope);
} catch (Exception e) {
throw new IllegalStateException("Failed to encrypt OAuth2 authorization request", e);
}
}
private OAuth2AuthorizationRequest decrypt(Cookie cookie) {
try {
byte[] envelope = Base64.getUrlDecoder().decode(cookie.getValue());
if (envelope.length < NONCE_LENGTH + TAG_LENGTH_BITS / Byte.SIZE + Long.BYTES) {
log.debug("Ignoring OAuth2 authorization request cookie: too short");
return null;
}
byte[] nonce = Arrays.copyOf(envelope, NONCE_LENGTH);
byte[] plaintext = initCipher(Cipher.DECRYPT_MODE, nonce).doFinal(envelope, NONCE_LENGTH, envelope.length - NONCE_LENGTH);
ByteBuffer buffer = ByteBuffer.wrap(plaintext);
long issuedAt = buffer.getLong();
if (clock.millis() - issuedAt > cookieExpireSeconds * 1000L) {
log.debug("Ignoring OAuth2 authorization request cookie: expired");
return null;
}
return OBJECT_MAPPER.readValue(plaintext, Long.BYTES, plaintext.length - Long.BYTES, OAuth2AuthorizationRequest.class);
} catch (Exception e) {
log.debug("Ignoring invalid OAuth2 authorization request cookie: {}", e.getClass().getSimpleName());
return null;
}
}
private Cipher initCipher(int mode, byte[] nonce) throws GeneralSecurityException {
Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");
cipher.init(mode, new SecretKeySpec(deriveKey(), "AES"), new GCMParameterSpec(TAG_LENGTH_BITS, nonce));
return cipher;
}
private byte[] deriveKey() {
byte[] signingKey = Base64.getDecoder().decode(jwtSettingsService.getJwtSettings().getTokenSigningKey());
HKDFBytesGenerator hkdf = new HKDFBytesGenerator(new SHA256Digest());
hkdf.init(new HKDFParameters(signingKey, null, KEY_DERIVATION_INFO));
byte[] key = new byte[KEY_LENGTH];
hkdf.generateBytes(key, 0, KEY_LENGTH);
return key;
}
}

212
application/src/main/java/org/thingsboard/server/service/solutions/DefaultSolutionService.java

@ -19,7 +19,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;
@ -30,7 +29,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;
@ -102,6 +100,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;
@ -115,6 +114,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;
@ -144,8 +144,10 @@ 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;
@ -166,6 +168,14 @@ 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_PLACEHOLDER = "$random";
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;
@ -237,9 +247,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 {
@ -280,73 +290,159 @@ public class DefaultSolutionService implements SolutionService {
}
}
private SolutionInstallResponse validateSolution(TenantId tenantId, Path tempDir) {
Map<EntityType, List<HasName>> alreadyExistingEntities = new HashMap<>();
//TODO: check other entities.
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.
List<ReferenceableEntityDefinition> ruleChains = loadListOfEntitiesIfFileExists(tempDir, "rule_chains.json", new TypeReference<>() {
});
if (!ruleChains.isEmpty()) {
for (ReferenceableEntityDefinition ruleChain : ruleChains) {
List<RuleChain> 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<DeviceProfileDefinition> 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<AssetProfileDefinition> 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<CustomerDefinition> customers = loadListOfEntitiesIfFileExists(tempDir, "customers.json", new TypeReference<>() {
});
List<DashboardDefinition> dashboards = loadListOfEntitiesIfFileExists(tempDir, "dashboards.json", new TypeReference<>() {
});
List<AssetDefinition> assets = loadListOfEntitiesIfFileExists(tempDir, "assets.json", new TypeReference<>() {
});
List<DeviceDefinition> devices = loadListOfEntitiesIfFileExists(tempDir, "devices.json", new TypeReference<>() {
});
List<EdgeDefinition> edges = loadListOfEntitiesIfFileExists(tempDir, "edges.json", new TypeReference<>() {
});
// Insertion ordered, so that the reported sections keep the order the entities are provisioned in.
Map<EntityType, List<String>> conflicts = new LinkedHashMap<>();
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, 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 SolutionValidationResult.passed();
}
StringBuilder details = new StringBuilder(CONFLICTS_INTRO).append(BLANK_LINE);
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);
}
return SolutionValidationResult.conflictsFound(details.toString());
}
private static SolutionInstallResponse conflictResponse(String conflictReport) {
SolutionInstallResponse response = new SolutionInstallResponse();
response.setSuccess(false);
response.setDetails(conflictReport);
return response;
}
/**
* 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<EntityType, List<String>> conflicts, List<? extends EntityDefinition> definitions,
Function<String, ? extends HasName> lookup) {
Set<String> checked = new HashSet<>();
for (EntityDefinition definition : definitions) {
if (checked.add(definition.getName())) {
collectConflict(conflicts, definition.getEntityType(), definition.getName(), lookup);
}
}
}
List<DashboardDefinition> dashboards = loadListOfEntitiesIfFileExists(tempDir, "dashboards.json", new TypeReference<>() {
});
if (!dashboards.isEmpty()) {
for (DashboardDefinition dashboard : dashboards) {
List<DashboardInfo> 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));
}
private <T> void collectConflicts(Map<EntityType, List<String>> conflicts, EntityType entityType, List<T> definitions,
Function<T, String> nameExtractor, Function<String, ? extends HasName> lookup) {
Set<String> checked = new HashSet<>();
for (T definition : definitions) {
String name = nameExtractor.apply(definition);
if (checked.add(name)) {
collectConflict(conflicts, entityType, name, lookup);
}
}
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;
}
private void collectConflict(Map<EntityType, List<String>> conflicts, EntityType entityType, String name,
Function<String, ? extends HasName> lookup) {
if (StringUtils.isEmpty(name)) {
return;
}
HasName existing = lookup.apply(name);
if (existing != null) {
conflicts.computeIfAbsent(entityType, key -> new ArrayList<>()).add(quoted(existing.getName()));
}
}
/**
* 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<EntityType, List<String>> conflicts, TenantId tenantId, Path tempDir,
List<ReferenceableEntityDefinition> definitions) {
Set<String> 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;
}
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, and must be looked up as is.
*/
private static boolean isRandomizedCustomerTitle(String title) {
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}
* 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 static void appendConflicts(StringBuilder details, EntityType entityType, List<String> conflictDescriptions) {
details.append("- **").append(entityType.getNormalName()).append("**: ")
.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());
}
private SolutionInstallResponse doInstallSolution(User user, TenantId tenantId, String solutionId, Path tempDir, HttpServletRequest request) {
SolutionInstallContext ctx = new SolutionInstallContext(tenantId, solutionId, tempDir, user, new TenantSolutionTemplateInstructions());
@ -1442,10 +1538,6 @@ public class DefaultSolutionService implements SolutionService {
return String.valueOf(now.toInstant().toEpochMilli());
}
private String getTypeLabel(EntityType type) {
return type.name().toLowerCase().replace('_', ' ');
}
private <T> T loadEntityIfFileExists(Path tempDir, String fileName, Class<T> clazz) {
Path filePath = tempDir.resolve("entities").resolve(fileName);
if (Files.exists(filePath)) {
@ -1459,7 +1551,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);
}

30
application/src/main/java/org/thingsboard/server/service/solutions/data/SolutionValidationResult.java

@ -0,0 +1,30 @@
// SPDX-FileCopyrightText: Copyright The Thingsboard Authors
// SPDX-License-Identifier: Apache-2.0
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);
}
}

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

6
application/src/main/java/org/thingsboard/server/service/telemetry/DefaultTbTelemetryService.java

@ -19,7 +19,9 @@ import org.thingsboard.server.common.data.kv.ReadTsKvQuery;
import org.thingsboard.server.common.data.kv.TsKvEntry;
import org.thingsboard.server.dao.timeseries.TimeseriesService;
import org.thingsboard.server.service.security.AccessValidator;
import org.thingsboard.server.service.security.ValidationCallback;
import org.thingsboard.server.service.security.ValidationResult;
import org.thingsboard.server.service.security.ValidationResultCode;
import org.thingsboard.server.service.security.model.SecurityUser;
import org.thingsboard.server.service.security.permission.Operation;
@ -42,6 +44,10 @@ public class DefaultTbTelemetryService implements TbTelemetryService {
accessValidator.validate(currentUser, Operation.READ_TELEMETRY, entityId, new FutureCallback<>() {
@Override
public void onSuccess(ValidationResult validationResult) {
if (validationResult.getResultCode() != ValidationResultCode.OK) {
onFailure(ValidationCallback.getException(validationResult));
return;
}
try {
AggregationParams params;
if (Aggregation.NONE.equals(agg)) {

76
application/src/main/java/org/thingsboard/server/service/ws/DefaultWebSocketService.java

@ -882,72 +882,36 @@ public class DefaultWebSocketService implements WebSocketService {
}, executor);
}
private <T> FutureCallback<ValidationResult> getAttributesFetchCallback(final TenantId tenantId, final EntityId entityId, final List<String> keys, final FutureCallback<List<AttributeKvEntry>> callback) {
return new FutureCallback<ValidationResult>() {
@Override
public void onSuccess(@Nullable ValidationResult result) {
List<ListenableFuture<List<AttributeKvEntry>>> futures = new ArrayList<>();
for (AttributeScope scope : AttributeScope.values()) {
futures.add(attributesService.find(tenantId, entityId, scope, keys));
}
ListenableFuture<List<AttributeKvEntry>> future = mergeAllAttributesFutures(futures);
Futures.addCallback(future, callback, MoreExecutors.directExecutor());
private FutureCallback<ValidationResult> getAttributesFetchCallback(final TenantId tenantId, final EntityId entityId, final List<String> keys, final FutureCallback<List<AttributeKvEntry>> callback) {
return on(r -> {
List<ListenableFuture<List<AttributeKvEntry>>> futures = new ArrayList<>();
for (AttributeScope scope : AttributeScope.values()) {
futures.add(attributesService.find(tenantId, entityId, scope, keys));
}
@Override
public void onFailure(Throwable t) {
callback.onFailure(t);
}
};
ListenableFuture<List<AttributeKvEntry>> future = mergeAllAttributesFutures(futures);
Futures.addCallback(future, callback, MoreExecutors.directExecutor());
}, callback::onFailure);
}
private <T> FutureCallback<ValidationResult> getAttributesFetchCallback(final TenantId tenantId, final EntityId entityId, final String scope, final List<String> keys, final FutureCallback<List<AttributeKvEntry>> callback) {
return new FutureCallback<ValidationResult>() {
@Override
public void onSuccess(@Nullable ValidationResult result) {
Futures.addCallback(attributesService.find(tenantId, entityId, AttributeScope.valueOf(scope), keys), callback, MoreExecutors.directExecutor());
}
@Override
public void onFailure(Throwable t) {
callback.onFailure(t);
}
};
private FutureCallback<ValidationResult> getAttributesFetchCallback(final TenantId tenantId, final EntityId entityId, final String scope, final List<String> keys, final FutureCallback<List<AttributeKvEntry>> callback) {
return on(r -> Futures.addCallback(attributesService.find(tenantId, entityId, AttributeScope.valueOf(scope), keys), callback, MoreExecutors.directExecutor()), callback::onFailure);
}
private <T> FutureCallback<ValidationResult> getAttributesFetchCallback(final TenantId tenantId, final EntityId entityId, final FutureCallback<List<AttributeKvEntry>> callback) {
return new FutureCallback<ValidationResult>() {
@Override
public void onSuccess(@Nullable ValidationResult result) {
List<ListenableFuture<List<AttributeKvEntry>>> futures = new ArrayList<>();
for (AttributeScope scope : AttributeScope.values()) {
futures.add(attributesService.findAll(tenantId, entityId, scope));
}
ListenableFuture<List<AttributeKvEntry>> future = mergeAllAttributesFutures(futures);
Futures.addCallback(future, callback, MoreExecutors.directExecutor());
private FutureCallback<ValidationResult> getAttributesFetchCallback(final TenantId tenantId, final EntityId entityId, final FutureCallback<List<AttributeKvEntry>> callback) {
return on(r -> {
List<ListenableFuture<List<AttributeKvEntry>>> futures = new ArrayList<>();
for (AttributeScope scope : AttributeScope.values()) {
futures.add(attributesService.findAll(tenantId, entityId, scope));
}
@Override
public void onFailure(Throwable t) {
callback.onFailure(t);
}
};
ListenableFuture<List<AttributeKvEntry>> future = mergeAllAttributesFutures(futures);
Futures.addCallback(future, callback, MoreExecutors.directExecutor());
}, callback::onFailure);
}
private <T> FutureCallback<ValidationResult> getAttributesFetchCallback(final TenantId tenantId, final EntityId entityId, final String scope, final FutureCallback<List<AttributeKvEntry>> callback) {
return new FutureCallback<ValidationResult>() {
@Override
public void onSuccess(@Nullable ValidationResult result) {
Futures.addCallback(attributesService.findAll(tenantId, entityId, AttributeScope.valueOf(scope)), callback, MoreExecutors.directExecutor());
}
@Override
public void onFailure(Throwable t) {
callback.onFailure(t);
}
};
private FutureCallback<ValidationResult> getAttributesFetchCallback(final TenantId tenantId, final EntityId entityId, final String scope, final FutureCallback<List<AttributeKvEntry>> callback) {
return on(r -> Futures.addCallback(attributesService.findAll(tenantId, entityId, AttributeScope.valueOf(scope)), callback, MoreExecutors.directExecutor()), callback::onFailure);
}
private FutureCallback<ValidationResult> on(Consumer<Void> success, Consumer<Throwable> failure) {

24
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
@ -1291,7 +1292,7 @@ transport:
# <li> A value that are > 4: MultiNodeConnectionIdGenerator is used </li> </ul>
connection_id_length: "${LWM2M_DTLS_CONNECTION_ID_LENGTH:8}"
server:
# LwM2M Server ID
# 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}"
@ -1333,8 +1334,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}"
# 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}"
# LwM2M bootstrap server bind port
@ -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.

6
application/src/test/java/org/thingsboard/server/controller/AbstractControllerTest.java

@ -92,7 +92,7 @@ public abstract class AbstractControllerTest extends AbstractNotifyEntityTest {
}
protected TbTestWebSocketClient buildAndConnectWebSocketClient(String path) throws URISyntaxException, InterruptedException {
TbTestWebSocketClient wsClient = new TbTestWebSocketClient(new URI(WS_URL + wsPort + path));
TbTestWebSocketClient wsClient = buildWebSocketClient(path);
assertThat(wsClient.connectBlocking(TIMEOUT, TimeUnit.SECONDS)).isTrue();
if (!path.contains("token=")) {
wsClient.authenticate(token);
@ -100,4 +100,8 @@ public abstract class AbstractControllerTest extends AbstractNotifyEntityTest {
return wsClient;
}
protected TbTestWebSocketClient buildWebSocketClient(String path) throws URISyntaxException {
return new TbTestWebSocketClient(new URI(WS_URL + wsPort + path));
}
}

7
application/src/test/java/org/thingsboard/server/controller/AbstractNotifyEntityTest.java

@ -364,8 +364,13 @@ public abstract class AbstractNotifyEntityTest extends AbstractWebTest {
}
private void testSendNotificationMsgToEdgeServiceTimeEntityEqAny(TenantId tenantId, ActionType actionType, int cntTime) {
// Count only entities that can be synced to edge. Background services may save non-edge entities for the
// tenant at any moment (e.g. QUEUE_STATS created by the periodic rule engine stats report), and their
// ADDED notifications have no edge event type, so they are dropped by TbClusterService anyway.
ArgumentMatcher<EntityId> matcherEdgeEntityId = argument -> argument != null
&& EdgeUtils.getEdgeEventTypeByEntityType(argument.getEntityType()) != null;
Mockito.verify(tbClusterService, times(cntTime)).sendNotificationMsgToEdge(Mockito.eq(tenantId),
Mockito.any(), Mockito.any(EntityId.class), Mockito.any(), Mockito.isNull(),
Mockito.any(), Mockito.argThat(matcherEdgeEntityId), Mockito.any(), Mockito.isNull(),
Mockito.eq(EdgeUtils.getEdgeEventActionTypeByActionType(actionType)), Mockito.any());
}

678
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<String> 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<JsonNode>() {});
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<JsonNode>() {});
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<JsonNode>() {});
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<String> verifiedName = ArgumentCaptor.forClass(String.class);
Mockito.verify(reportRunner).verifyUploadedChecker(any(), any(), verifiedName.capture());
assertThat(verifiedName.getValue()).isEqualTo(CHECKER_FILE_NAME_FOR_THIS_HOST);
ArgumentCaptor<String> fileName = ArgumentCaptor.forClass(String.class);
ArgumentCaptor<CommunityGrantCheckerInput> 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<JsonNode>() {});
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<JsonNode>() {});
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<JsonNode>() {});
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<AuditLog> auditLogs = findAuditLogs(user, actionType);
assertThat(auditLogs).hasSize(1);
assertThat(auditLogs.get(0).getActionStatus()).isEqualTo(expectedStatus);
return auditLogs.get(0);
}
private List<AuditLog> 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();
}
}

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

107
application/src/test/java/org/thingsboard/server/controller/LwM2MServiceImplConfigTest.java

@ -0,0 +1,107 @@
// 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.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;
@ExtendWith(MockitoExtension.class)
public class LwM2MServiceImplConfigTest {
@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);
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);
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);
}
@Test
void testGetServerSecurityInfo_Server_Less_PRIMARY_LWM2M_SERVER_DefaultsToOneAndLogsWarn() {
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());
}
@Test
void testGetServerSecurityInfo_Server_NOT_USED_IDENTIFYING_LWM2M_SERVER_MAX_DefaultsToOneAndLogsWarn() {
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());
}
@Test
void testGetServerSecurityInfo_ServerWithNullId_DefaultsToOneAndLogsWarn() {
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());
}
}

3
application/src/test/java/org/thingsboard/server/controller/TbTestWebSocketClient.java

@ -42,6 +42,8 @@ public class TbTestWebSocketClient extends WebSocketClient {
@Getter
private volatile String lastMsg;
@Getter
private volatile Integer closeCode;
private volatile CountDownLatch reply;
private volatile CountDownLatch update;
@ -74,6 +76,7 @@ public class TbTestWebSocketClient extends WebSocketClient {
@Override
public void onClose(int i, String s, boolean b) {
closeCode = i;
log.info("CLOSED.");
}

36
application/src/test/java/org/thingsboard/server/controller/TelemetryControllerTest.java

@ -10,8 +10,10 @@ import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException;
import org.thingsboard.common.util.JacksonUtil;
import org.thingsboard.server.common.data.AttributeScope;
import org.thingsboard.server.common.data.Device;
import org.thingsboard.server.common.data.SaveDeviceWithCredentialsRequest;
import org.thingsboard.server.common.data.id.DeviceProfileId;
import org.thingsboard.server.common.data.kv.BasicTsKvEntry;
import org.thingsboard.server.common.data.kv.LongDataEntry;
import org.thingsboard.server.common.data.query.AliasEntityId;
@ -22,9 +24,11 @@ import org.thingsboard.server.common.data.security.DeviceCredentialsType;
import org.thingsboard.server.dao.service.DaoSqlTest;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import static org.assertj.core.api.Assertions.assertThat;
import static org.awaitility.Awaitility.await;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import static org.thingsboard.server.common.data.query.EntityKeyType.TIME_SERIES;
@ -291,6 +295,38 @@ public class TelemetryControllerTest extends AbstractControllerTest {
Assert.assertTrue(tsDataAfterDeletion.get("key3").get(0).get("value").isNull());
}
@Test
public void testCustomerUserCannotReadTimeseriesOfNotAssignedDevice() throws Exception {
loginTenantAdmin();
Device device = createDevice();
tsService.save(tenantId, device.getId(), new BasicTsKvEntry(1000L, new LongDataEntry("t", 1L))).get();
loginCustomerUser();
String url = "/api/plugins/telemetry/DEVICE/{entityId}/values/timeseries?keys=t&startTs=0&endTs={endTs}";
doGetAsync(url, device.getUuidId(), System.currentTimeMillis()).andExpect(status().isForbidden());
doGetAsync(url + "&agg=SUM&interval=86400000", device.getUuidId(), System.currentTimeMillis()).andExpect(status().isForbidden());
doGetAsync(url, UUID.randomUUID(), System.currentTimeMillis()).andExpect(status().isNotFound());
loginTenantAdmin();
assignDeviceToCustomer(device.getId(), customerId);
loginCustomerUser();
ObjectNode result = doGetAsync(url, ObjectNode.class, device.getUuidId(), System.currentTimeMillis());
Assert.assertEquals(1L, result.get("t").get(0).get("value").asLong());
}
@Test
public void testCustomerUserCannotSaveDeviceProfileAttributes() throws Exception {
loginTenantAdmin();
DeviceProfileId deviceProfileId = createDevice().getDeviceProfileId();
loginCustomerUser();
doPostAsync("/api/plugins/telemetry/DEVICE_PROFILE/" + deviceProfileId + "/SERVER_SCOPE", "{\"attr\": \"value\"}", String.class, status().isForbidden());
await().during(1, TimeUnit.SECONDS).atMost(2, TimeUnit.SECONDS)
.until(() -> attributesService.find(tenantId, deviceProfileId, AttributeScope.SERVER_SCOPE, "attr").get().isEmpty());
}
private Device createDevice() throws Exception {
String testToken = "TEST_TOKEN";

48
application/src/test/java/org/thingsboard/server/controller/TwoFactorAuthTest.java

@ -4,6 +4,7 @@ package org.thingsboard.server.controller;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonNode;
import org.java_websocket.framing.CloseFrame;
import org.jboss.aerogear.security.otp.Totp;
import org.junit.After;
import org.junit.Before;
@ -14,6 +15,8 @@ import org.springframework.test.context.bean.override.mockito.MockitoBean;
import org.springframework.test.context.bean.override.mockito.MockitoSpyBean;
import org.springframework.web.util.UriComponentsBuilder;
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;
@ -26,6 +29,8 @@ import org.thingsboard.server.common.data.notification.targets.platform.TenantAd
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;
@ -43,6 +48,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;
@ -145,6 +151,48 @@ public class TwoFactorAuthTest extends AbstractControllerTest {
assertThat(currentUser.getId()).isEqualTo(user.getId());
}
@Test
public void testWsAuthCmd_preVerificationTokenRejected() throws Exception {
configureTotpTwoFa();
logInWithMfaToken(username, password, Authority.PRE_VERIFICATION_TOKEN);
wsClient = buildAndConnectWebSocketClient();
await().atMost(TIMEOUT, TimeUnit.SECONDS).until(wsClient::isClosed);
}
@Test
public void testWsQueryToken_preVerificationTokenRejected() throws Exception {
configureTotpTwoFa();
logInWithMfaToken(username, password, Authority.PRE_VERIFICATION_TOKEN);
// The server accepts the handshake and closes the session right away from afterConnectionEstablished().
// connectBlocking() returns false when that close frame is processed before it checks the open state,
// so its result is not asserted here; the server-side close code proves the token was rejected.
wsClient = buildWebSocketClient("/api/ws?token=" + token);
wsClient.connectBlocking(TIMEOUT, TimeUnit.SECONDS);
await().atMost(TIMEOUT, TimeUnit.SECONDS).until(wsClient::isClosed);
assertThat(wsClient.getCloseCode()).isEqualTo(CloseFrame.UNEXPECTED_CONDITION);
}
@Test
public void testWs_accessTokenAcceptedAfterTwoFa() throws Exception {
TotpTwoFaAccountConfig totpTwoFaAccountConfig = configureTotpTwoFa();
logInWithMfaToken(username, password, Authority.PRE_VERIFICATION_TOKEN);
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 -> {

12
application/src/test/java/org/thingsboard/server/controller/WebsocketApiTest.java

@ -966,6 +966,18 @@ public class WebsocketApiTest extends AbstractControllerTest {
assertThat(update.get("data").get("attr").get(0).get(1).asText()).isEqualTo(expectedAttrValue);
}
@Test
public void testAttributesSubscription_customerUserNotAssignedDevice() throws Exception {
sendAttributes(device, TbAttributeSubscriptionScope.SERVER_SCOPE, List.of(
new BaseAttributeKvEntry(System.currentTimeMillis(), new StringDataEntry("attr", "secret"))
));
loginCustomerUser();
JsonNode update = getWsClient().subscribeForAttributes(device.getId(), TbAttributeSubscriptionScope.SERVER_SCOPE.name(), List.of("attr"));
assertThat(update.get("errorCode").asInt()).isNotEqualTo(SubscriptionErrorCode.NO_ERROR.getCode());
assertThat(update.path("data").isEmpty()).isTrue();
}
@Test
public void testEntityCountCmd_filterTypeSingularCompatibilityTest() throws Exception {
ObjectNode oldFormatDeviceTypeFilterSingular = JacksonUtil.newObjectNode();

119
application/src/test/java/org/thingsboard/server/edge/DeviceEdgeTest.java

@ -38,12 +38,16 @@ 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.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;
@ -93,6 +97,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
@ -654,6 +661,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);

30
application/src/test/java/org/thingsboard/server/edge/DeviceProfileEdgeTest.java

@ -232,13 +232,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"));
@ -400,15 +400,15 @@ public class DeviceProfileEdgeTest extends AbstractEdgeTest {
JacksonUtil.fromString(AbstractLwM2MIntegrationTest.TELEMETRY_WITHOUT_OBSERVE, TelemetryMappingConfiguration.class);
transportConfiguration.setObserveAttr(observeAttrConfiguration);
List<LwM2MBootstrapServerCredential> 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<LwM2MBootstrapServerCredential> 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;
}

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

9
application/src/test/java/org/thingsboard/server/queue/discovery/HashPartitionServiceTest.java

@ -83,6 +83,7 @@ public class HashPartitionServiceTest {
.setServiceId("tb-core-0")
.addAllServiceTypes(Collections.singletonList(ServiceType.TB_CORE.name()))
.build();
when(serviceInfoProvider.getServiceInfo()).thenReturn(currentServer);
List<ServiceInfo> otherServers = new ArrayList<>();
for (int i = 1; i < SERVER_COUNT; i++) {
otherServers.add(ServiceInfo.newBuilder()
@ -94,6 +95,14 @@ public class HashPartitionServiceTest {
partitionService.recalculatePartitions(currentServer, otherServers);
}
@Test
public void testIsKnownServiceId() {
assertThat(partitionService.isKnownServiceId(ServiceType.TB_CORE, "tb-core-0")).isTrue(); // current server
assertThat(partitionService.isKnownServiceId(ServiceType.TB_CORE, "tb-rule-1")).isTrue(); // other server
assertThat(partitionService.isKnownServiceId(ServiceType.TB_CORE, "unknown-id")).isFalse();
assertThat(partitionService.isKnownServiceId(ServiceType.TB_RULE_ENGINE, "tb-core-0")).isFalse(); // wrong type
}
@Test
public void testDispersionOnMillionDevices() {
List<DeviceId> devices = new ArrayList<>();

99
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<TimeseriesSaveRequest> captor = ArgumentCaptor.forClass(TimeseriesSaveRequest.class);
verify(tsSubService).saveTimeseries(captor.capture());
return captor.getValue();
}
}

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

305
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<AdminSettings> 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<AdminSettings> 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<AdminSettings> 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);
}
}

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

421
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<String> 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<Arguments> goldenVectors() {
List<Arguments> 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<Arguments> manifestsBrokenOneRuleAtATime() {
List<Arguments> cases = new ArrayList<>();
List<String> 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);
}
}
}

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

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

1008
application/src/test/java/org/thingsboard/server/service/community_grant/CommunityGrantPollerTest.java

File diff suppressed because it is too large

600
application/src/test/java/org/thingsboard/server/service/community_grant/CommunityGrantPortalClientTest.java

@ -0,0 +1,600 @@
// 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.headerDoesNotExist;
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 testClaimLicenseSendsTheTokenInTheBodyAndReturnsTheKey() {
mockServer.expect(requestTo(BASE_URL + "/api/noauth/freeLicense/claim"))
.andExpect(method(HttpMethod.POST))
.andExpect(content().json("{\"claimToken\":\"" + TOKEN + "\"}"))
.andExpect(headerDoesNotExist(CLAIM_TOKEN_HEADER))
.andRespond(withSuccess("{\"activated\":true,\"secret\":\"granted-key\"}", MediaType.APPLICATION_JSON));
assertThat(client.claimLicense(TOKEN)).isEqualTo("granted-key");
mockServer.verify();
}
@Test
void testClaimLicenseReturnsNothingWhileThePortalHasNoKeyYet() {
mockServer.expect(requestTo(BASE_URL + "/api/noauth/freeLicense/claim"))
.andRespond(withSuccess("{\"activated\":false}", MediaType.APPLICATION_JSON));
assertThat(client.claimLicense(TOKEN)).isNull();
mockServer.verify();
}
@Test
void testClaimLicenseTurnsAClientErrorIntoARefusal() {
mockServer.expect(requestTo(BASE_URL + "/api/noauth/freeLicense/claim"))
.andRespond(withStatus(HttpStatus.BAD_REQUEST));
assertThatThrownBy(() -> 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"))
.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<Object, ConnectionConfig> resolver =
(Resolver<Object, ConnectionConfig>) 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();
}
};
}
}

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

529
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<ILoggingEvent> 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<String, String> 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();
}
}

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

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

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

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

149
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<Future<?>> 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<String, AdminSettings> 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<AdminSettings> 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<HasId<?>> findEntity(TenantId tenantId, EntityId entityId) {
throw new UnsupportedOperationException("Not used by CommunityGrantFlowStateStore");
}
@Override
public FluentFuture<Optional<HasId<?>>> findEntityAsync(TenantId tenantId, EntityId entityId) {
throw new UnsupportedOperationException("Not used by CommunityGrantFlowStateStore");
}
@Override
public EntityType getEntityType() {
throw new UnsupportedOperationException("Not used by CommunityGrantFlowStateStore");
}
}
}

1171
application/src/test/java/org/thingsboard/server/service/community_grant/DefaultCommunityGrantServiceTest.java

File diff suppressed because it is too large

325
application/src/test/java/org/thingsboard/server/service/edge/rpc/EdgeGrpcServiceReconnectTest.java

@ -0,0 +1,325 @@
// SPDX-FileCopyrightText: Copyright The Thingsboard Authors
// SPDX-License-Identifier: Apache-2.0
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<EdgeId, String> 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<TbProtoQueueMsg<ToEdgeEventNotificationMsg>> consumerManager = mock(QueueConsumerManager.class);
@SuppressWarnings("unchecked")
TbQueueConsumer<TbProtoQueueMsg<ToEdgeEventNotificationMsg>> 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<EdgeId, EdgeGrpcSession> sessions() {
return field("sessions");
}
private ConcurrentMap<UUID, EdgeGrpcSession> sessionsById() {
return field("sessionsById");
}
private ConcurrentMap<EdgeId, ScheduledFuture<?>> edgeEventChecks() {
return field("sessionEdgeEventChecks");
}
private Map<EdgeId, Boolean> newEvents() {
return field("sessionNewEvents");
}
private ConcurrentMap<EdgeId, Boolean> migrationProcessed() {
return field("edgeEventsMigrationProcessed");
}
@SuppressWarnings("unchecked")
private <T> T field(String name) {
return (T) ReflectionTestUtils.getField(service, name);
}
}

182
application/src/test/java/org/thingsboard/server/service/edge/rpc/EdgeGrpcServiceTest.java

@ -24,10 +24,6 @@ import org.thingsboard.server.common.data.notification.rule.trigger.Notification
import org.thingsboard.server.common.msg.TbMsg;
import org.thingsboard.server.common.msg.notification.NotificationRuleProcessor;
import org.thingsboard.server.common.msg.queue.ServiceType;
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.PartitionService;
import org.thingsboard.server.queue.discovery.TbServiceInfoProvider;
import org.thingsboard.server.service.edge.EdgeContextComponent;
@ -43,7 +39,6 @@ import java.util.concurrent.ConcurrentMap;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyBoolean;
import static org.mockito.ArgumentMatchers.anyLong;
import static org.mockito.ArgumentMatchers.isNull;
import static org.mockito.ArgumentMatchers.argThat;
@ -227,17 +222,14 @@ public class EdgeGrpcServiceTest {
@Test
public void givenSessionReplacedDuringDisconnect_whenStaleCallbackRuns_thenLiveSessionKept() {
// Reproduces the get()/remove() interleaving on a single node: onEdgeConnect swaps in a new session
// right after the stale callback's id check passes. The stale callback must not evict or tear down
// the live session, nor clear the activity state.
// onEdgeConnect has already swapped in a new session on this node when the stale callback runs.
// The check-and-remove is a single atomic step against the same map that onEdgeConnect writes
// through, so the swap can only land before or after it. The stale callback must not evict or
// tear down the live session, nor clear the activity state.
UUID staleSessionId = UUID.randomUUID();
EdgeGrpcSession live = mock(EdgeGrpcSession.class);
EdgeGrpcSession stale = mock(EdgeGrpcSession.class);
when(stale.getSessionId()).thenAnswer(invocation -> {
sessions().put(edgeId, live);
return staleSessionId;
});
sessions().put(edgeId, stale);
when(live.getSessionId()).thenReturn(UUID.randomUUID());
sessions().put(edgeId, live);
onEdgeDisconnect(staleSessionId);
@ -246,20 +238,11 @@ public class EdgeGrpcServiceTest {
}
@Test
public void givenSessionReplacedOnThisNodeAfterRemoval_whenStaleCallbackRuns_thenNoDisconnectSideEffects() {
// The stale callback wins the compare-and-remove, then tearing its own session down takes a while
// (for the Kafka session this stops a consumer). The edge reconnects to THIS node in that gap, so the
// ownership cache legitimately names us and isOwnedByAnotherNode cannot help. None of the disconnect
// side effects may run: not the flag, not the timestamp, not the DISCONNECT_EVENT push.
public void givenSessionReplacedOnThisNodeDuringDisconnect_whenStaleCallbackRuns_thenNoDisconnectSideEffects() {
// the edge reconnects to this node after the stale session was detached, so the cache names this node
UUID sessionId = UUID.randomUUID();
EdgeGrpcSession stale = mock(EdgeGrpcSession.class);
when(stale.getSessionId()).thenReturn(sessionId);
when(stale.getEdge()).thenReturn(edge);
when(stale.destroy()).thenAnswer(invocation -> {
sessions().put(edgeId, mock(EdgeGrpcSession.class));
return true;
});
sessions().put(edgeId, stale);
sessions().put(edgeId, sessionFor(sessionId));
reconnectToThisNodeOnOwnershipCheck();
onEdgeDisconnect(sessionId);
@ -271,124 +254,33 @@ public class EdgeGrpcServiceTest {
@Test
public void givenEdgeReconnectedToAnotherNode_whenDisconnect_thenDisconnectEventNotPushed() {
// The DISCONNECT_EVENT payload is {"active": false, ...} with SERVER_SCOPE, so a rule chain wiring
// Disconnect Event -> Save Attributes would persist active=false back and re-create the bug.
EdgeSessionStub stub = registerSession();
// DISCONNECT_EVENT carries active=false, a Save Attributes node would write it back
UUID sessionId = UUID.randomUUID();
sessions().put(edgeId, sessionFor(sessionId));
when(serviceInfoProvider.getServiceId()).thenReturn(THIS_NODE);
when(edgeIdServiceIdCache.get(edgeId)).thenReturn(SimpleTbCacheValueWrapper.wrap(OTHER_NODE));
when(partitionService.getAllServiceIds(ServiceType.TB_CORE)).thenReturn(Set.of(THIS_NODE, OTHER_NODE));
onEdgeDisconnect(stub.sessionId());
onEdgeDisconnect(sessionId);
verify(clusterService, never()).pushMsgToRuleEngine(any(TenantId.class), any(EntityId.class), any(TbMsg.class), isNull());
}
@Test
public void givenEdgeGenuinelyDisconnected_whenDisconnect_thenDisconnectEventPushed() {
// Also proves the never() assertions above are not vacuous: the push does happen on this path.
EdgeSessionStub stub = registerSession();
when(serviceInfoProvider.getServiceId()).thenReturn(THIS_NODE);
when(edgeIdServiceIdCache.get(edgeId)).thenReturn(SimpleTbCacheValueWrapper.wrap(THIS_NODE));
onEdgeDisconnect(stub.sessionId());
verify(clusterService, times(1)).pushMsgToRuleEngine(any(TenantId.class), any(EntityId.class), any(TbMsg.class), isNull());
}
@Test
public void givenSessionReplacedOnThisNode_whenStaleCallbackRuns_thenReplacementEdgeEventsCheckNotCancelled() {
// sessionEdgeEventChecks is keyed by edgeId, not by session, so the replacement's check sits under the
// same key as the one this callback is tearing down. The check loop only reschedules itself from inside
// the task, so cancelling it here would leave a connected edge with nothing to restart downlink
// delivery - the same silent stall this guard exists to prevent.
UUID sessionId = UUID.randomUUID();
EdgeGrpcSession stale = mock(EdgeGrpcSession.class);
when(stale.getSessionId()).thenReturn(sessionId);
when(stale.getEdge()).thenReturn(edge);
ScheduledFuture<?> replacementCheck = mock(ScheduledFuture.class);
when(stale.destroy()).thenAnswer(invocation -> {
sessions().put(edgeId, mock(EdgeGrpcSession.class));
sessionEdgeEventChecks().put(edgeId, replacementCheck);
return true;
});
sessions().put(edgeId, stale);
onEdgeDisconnect(sessionId);
verify(replacementCheck, never()).cancel(anyBoolean());
assertThat(sessionEdgeEventChecks()).containsEntry(edgeId, replacementCheck);
}
@Test
public void givenEdgeGenuinelyDisconnected_whenDisconnect_thenEdgeEventsCheckCancelled() {
// Counterpart to the test above: proves the cancel still runs on a real disconnect, so the guard is
// not simply disabling it.
UUID sessionId = UUID.randomUUID();
sessions().put(edgeId, sessionFor(sessionId));
ScheduledFuture<?> check = mock(ScheduledFuture.class);
sessionEdgeEventChecks().put(edgeId, check);
when(serviceInfoProvider.getServiceId()).thenReturn(THIS_NODE);
when(edgeIdServiceIdCache.get(edgeId)).thenReturn(SimpleTbCacheValueWrapper.wrap(THIS_NODE));
onEdgeDisconnect(sessionId);
verify(check, times(1)).cancel(anyBoolean());
assertThat(sessionEdgeEventChecks()).doesNotContainKey(edgeId);
}
// --- zombie session cleanup ---
@Test
@SuppressWarnings("unchecked")
public void givenZombieSessionReplacedDuringDestroy_whenCleanupRuns_thenReplacementKept() {
// destroy() stops a Kafka consumer and is not instantaneous. If the edge reconnects in that gap, an
// unconditional sessions.remove(edgeId) would drop the live session, leaving a connected edge with no
// map entry - every downlink lookup then silently no-ops.
KafkaEdgeGrpcSession zombie = mock(KafkaEdgeGrpcSession.class);
when(zombie.getEdge()).thenReturn(edge);
when(zombie.isConnected()).thenReturn(false);
QueueConsumerManager<TbProtoQueueMsg<ToEdgeEventNotificationMsg>> consumerManager = mock(QueueConsumerManager.class);
TbQueueConsumer<TbProtoQueueMsg<ToEdgeEventNotificationMsg>> consumer = mock(TbQueueConsumer.class);
when(consumer.isStopped()).thenReturn(false);
when(consumerManager.getConsumer()).thenReturn(consumer);
when(zombie.getConsumer()).thenReturn(consumerManager);
EdgeGrpcSession replacement = mock(EdgeGrpcSession.class);
when(zombie.destroy()).thenAnswer(invocation -> {
sessions().put(edgeId, replacement);
return true;
});
sessions().put(edgeId, zombie);
ReflectionTestUtils.invokeMethod(edgeGrpcService, "cleanupZombieSessions");
assertThat(sessions()).containsEntry(edgeId, replacement);
}
@Test
@SuppressWarnings("unchecked")
public void givenZombieSessionStillCurrent_whenCleanupRuns_thenItIsRemoved() {
// Counterpart: with no replacement, the compare-and-remove must still drop the zombie.
KafkaEdgeGrpcSession zombie = mock(KafkaEdgeGrpcSession.class);
when(zombie.getEdge()).thenReturn(edge);
when(zombie.isConnected()).thenReturn(false);
QueueConsumerManager<TbProtoQueueMsg<ToEdgeEventNotificationMsg>> consumerManager = mock(QueueConsumerManager.class);
TbQueueConsumer<TbProtoQueueMsg<ToEdgeEventNotificationMsg>> consumer = mock(TbQueueConsumer.class);
when(consumer.isStopped()).thenReturn(false);
when(consumerManager.getConsumer()).thenReturn(consumer);
when(zombie.getConsumer()).thenReturn(consumerManager);
when(zombie.destroy()).thenReturn(true);
sessions().put(edgeId, zombie);
ReflectionTestUtils.invokeMethod(edgeGrpcService, "cleanupZombieSessions");
assertThat(sessions()).doesNotContainKey(edgeId);
verify(clusterService, times(1)).pushMsgToRuleEngine(any(TenantId.class), any(EntityId.class), any(TbMsg.class), isNull());
}
// --- onEdgeConnect ownership publish order ---
@Test
public void givenConnect_whenClaimingOwnership_thenCachePutHappensBeforeActiveStateWrite() {
// Load-bearing ordering: the previous node's onEdgeDisconnect reads this cache entry to decide whether
// to clear the flag, so the claim must be visible before active=true is written. Nothing else pins the
// order, and a tidy-up that groups the save(...) calls together would silently restore the race.
// the previous node reads this cache entry on disconnect, so the claim must be visible before active=true
EdgeGrpcSession session = mock(EdgeGrpcSession.class);
when(session.getSessionId()).thenReturn(UUID.randomUUID());
when(session.getEdge()).thenReturn(edge);
@ -405,8 +297,6 @@ public class EdgeGrpcServiceTest {
inOrder.verify(tsSubService).saveAttributes(argThat(activeStateWrite()));
}
// --- service-id cache eviction guard ---
@Test
public void givenEdgeOwnedByThisNode_whenDisconnect_thenInactiveStateIsPersisted() {
UUID sessionId = UUID.randomUUID();
@ -434,23 +324,13 @@ public class EdgeGrpcServiceTest {
verify(tsSubService, times(1)).saveAttributes(argThat(lastDisconnectTimeWrite()));
}
// --- disconnect notification guard ---
@Test
public void givenZeroDelayAndSessionReplacedOnThisNode_whenStaleCallbackRuns_thenNoDisconnectNotification() {
// EDGES_DISCONNECT_NOTIFICATION_DELAY_MS=0 makes scheduleDisconnectNotification notify immediately and
// skip fireDelayedDisconnectNotification's liveness re-verify, so the disconnect guard is the only
// thing standing between a live replacement and a false 'edge disconnected' notification.
// with zero delay the notification skips the liveness re-check, so only the disconnect guard prevents it
UUID sessionId = UUID.randomUUID();
EdgeGrpcSession stale = mock(EdgeGrpcSession.class);
when(stale.getSessionId()).thenReturn(sessionId);
when(stale.getEdge()).thenReturn(edge);
when(stale.destroy()).thenAnswer(invocation -> {
sessions().put(edgeId, mock(EdgeGrpcSession.class));
return true;
});
sessions().put(edgeId, sessionFor(sessionId));
reconnectToThisNodeOnOwnershipCheck();
lenient().when(ctx.getRuleProcessor()).thenReturn(ruleProcessor);
sessions().put(edgeId, stale);
onEdgeDisconnect(sessionId);
@ -459,7 +339,6 @@ public class EdgeGrpcServiceTest {
@Test
public void givenZeroDelayAndEdgeGenuinelyDisconnected_whenDisconnect_thenNotificationSent() {
// Counterpart: the immediate path must still fire for a real disconnect.
UUID sessionId = UUID.randomUUID();
sessions().put(edgeId, sessionFor(sessionId));
when(edgeIdServiceIdCache.get(edgeId)).thenReturn(null);
@ -474,13 +353,13 @@ public class EdgeGrpcServiceTest {
ReflectionTestUtils.invokeMethod(edgeGrpcService, "onEdgeDisconnect", edge, sessionId);
}
private EdgeSessionStub registerSession() {
UUID sessionId = UUID.randomUUID();
sessions().put(edgeId, sessionFor(sessionId));
return new EdgeSessionStub(sessionId);
}
private record EdgeSessionStub(UUID sessionId) {
// simulates a reconnect to this node landing after the stale session was detached, before the guard runs
private void reconnectToThisNodeOnOwnershipCheck() {
when(serviceInfoProvider.getServiceId()).thenReturn(THIS_NODE);
when(edgeIdServiceIdCache.get(edgeId)).thenAnswer(invocation -> {
sessions().put(edgeId, mock(EdgeGrpcSession.class));
return SimpleTbCacheValueWrapper.wrap(THIS_NODE);
});
}
private ArgumentMatcher<AttributesSaveRequest> activeStateWrite() {
@ -498,11 +377,6 @@ public class EdgeGrpcServiceTest {
return session;
}
@SuppressWarnings("unchecked")
private ConcurrentMap<EdgeId, ScheduledFuture<?>> sessionEdgeEventChecks() {
return (ConcurrentMap<EdgeId, ScheduledFuture<?>>) ReflectionTestUtils.getField(edgeGrpcService, "sessionEdgeEventChecks");
}
private ArgumentMatcher<AttributesSaveRequest> inactiveStateWrite() {
return request -> request != null
&& edgeId.equals(request.getEntityId())

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

60
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<String> tbClusterStatements(String sql) {
List<String> statements = new ArrayList<>();
Matcher matcher = TB_CLUSTER_DDL.matcher(sql);
while (matcher.find()) {
statements.add(matcher.group(1));
}
return statements;
}
}

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

106
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<UUID> 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<UUID> 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<String> productionClusterDdl() {
String resourceName = "sql/" + SqlEntityDatabaseSchemaService.SCHEMA_ENTITIES_SQL;
List<String> statements = tbClusterStatements(readResource(resourceName));
assertThat(statements).as("tb_cluster DDL found in %s", resourceName).hasSize(2);
return statements;
}
private static List<UUID> readClusterIds() throws SQLException {
List<UUID> 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;
}
}

39
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<String> fromSchemaEntities = normalized(tbClusterStatements(readResource(schemaEntities)));
List<String> 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<String> normalized(List<String> statements) {
return statements.stream().map(statement -> statement.replaceAll("\\s+", " ").trim()).toList();
}
}

83
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<LtsMigration> 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");

64
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<String> events) {
doAnswer(invocation -> events.add("record:" + invocation.getArgument(0)))
.when(schemaSettingsService).updateSchemaVersion(anyString());
}
private LtsMigrationService service(List<LtsMigration> 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<String> applied = new ArrayList<>();
List<String> 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<String> 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<String> 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<String> 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<String> 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());

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

@ -15,8 +15,8 @@ import org.mockito.junit.jupiter.MockitoExtension;
import org.thingsboard.common.util.JacksonUtil;
import org.thingsboard.server.common.data.id.IotHubInstalledItemId;
import org.thingsboard.server.common.data.id.TenantId;
import org.thingsboard.server.common.data.iot_hub.DashboardInstalledItemDescriptor;
import org.thingsboard.server.common.data.iot_hub.IotHubInstalledItem;
import org.thingsboard.server.common.data.iot_hub.RuleChainInstalledItemDescriptor;
import org.thingsboard.server.dao.iot_hub.IotHubInstalledItemService;
import org.thingsboard.server.service.security.model.SecurityUser;
@ -89,7 +89,7 @@ class DefaultIotHubServiceTest {
mockTenant();
String versionId = UUID.randomUUID().toString();
String itemId = UUID.randomUUID().toString();
when(iotHubRestClient.getVersionInfo(versionId)).thenReturn(version(versionId, itemId, "DASHBOARD", "Root", "1.0"));
when(iotHubRestClient.getVersionInfo(versionId)).thenReturn(version(versionId, itemId, "RULE_CHAIN", "Root", "1.0"));
when(iotHubInstalledItemService.findInstalledItemIdsByTenantIdAndItemIdIn(eq(tenantId), any())).thenReturn(List.of());
InstallPlan plan = service.resolveInstallPlan(user, versionId);
@ -107,7 +107,7 @@ class DefaultIotHubServiceTest {
String versionId = UUID.randomUUID().toString();
String rootItemId = UUID.randomUUID().toString();
String relatedItemId = UUID.randomUUID().toString();
ObjectNode root = version(versionId, rootItemId, "DASHBOARD", "Root", "1.0");
ObjectNode root = version(versionId, rootItemId, "RULE_CHAIN", "Root", "1.0");
root.putArray("relatedItems").add(relatedItemId);
when(iotHubRestClient.getVersionInfo(versionId)).thenReturn(root);
when(iotHubRestClient.getPublishedVersionByItemId(relatedItemId))
@ -129,7 +129,7 @@ class DefaultIotHubServiceTest {
String versionId = UUID.randomUUID().toString();
String rootItemId = UUID.randomUUID().toString();
String relatedItemId = UUID.randomUUID().toString();
ObjectNode root = version(versionId, rootItemId, "DASHBOARD", "Root", "1.0");
ObjectNode root = version(versionId, rootItemId, "RULE_CHAIN", "Root", "1.0");
root.putArray("relatedItems").add(relatedItemId);
when(iotHubRestClient.getVersionInfo(versionId)).thenReturn(root);
when(iotHubRestClient.getPublishedVersionByItemId(relatedItemId)).thenReturn(null);
@ -149,7 +149,7 @@ class DefaultIotHubServiceTest {
String versionId = UUID.randomUUID().toString();
String rootItemId = UUID.randomUUID().toString();
String relatedItemId = UUID.randomUUID().toString();
ObjectNode root = version(versionId, rootItemId, "DASHBOARD", "Root", "1.0");
ObjectNode root = version(versionId, rootItemId, "RULE_CHAIN", "Root", "1.0");
root.putArray("relatedItems").add(relatedItemId);
when(iotHubRestClient.getVersionInfo(versionId)).thenReturn(root);
when(iotHubRestClient.getPublishedVersionByItemId(relatedItemId)).thenThrow(new RuntimeException("boom"));
@ -280,7 +280,7 @@ class DefaultIotHubServiceTest {
when(iotHubInstalledItemService.findInstalledItemIdsByTenantIdAndItemIdIn(eq(tenantId), any())).thenReturn(List.of());
IotHubInstalledItem depItem = installedItem(UUID.randomUUID());
IotHubInstalledItem rootItem = installedItem(UUID.randomUUID());
DashboardInstalledItemDescriptor rootDescriptor = new DashboardInstalledItemDescriptor();
RuleChainInstalledItemDescriptor rootDescriptor = new RuleChainInstalledItemDescriptor();
rootItem.setDescriptor(rootDescriptor);
doReturn(depItem).when(service).doInstallVersion(eq(user), eq(depVersionId), any(), any());
doReturn(rootItem).when(service).doInstallVersion(eq(user), eq(rootVersionId), any(), any());
@ -331,6 +331,64 @@ class DefaultIotHubServiceTest {
inOrder.verify(service).deleteInstalledItem(user, dep1Item.getId());
}
@Test
void installPlan_errorMessageIsTheFailureItselfWithoutAnyPrefix() 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 sentence around the failure belongs to the dialog, which localizes it
assertThat(result.getErrorMessage()).isEqualTo("install failed");
}
@Test
void installPlan_dependencyFails_failureIsReportedOnTheEntryAndAsTheResultMessage() 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);
// 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());
}
@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();

7
application/src/test/java/org/thingsboard/server/service/job/JobManagerTest.java

@ -152,10 +152,13 @@ public class JobManagerTest extends AbstractControllerTest {
int tasksCount = 200;
JobId jobId = submitJob(DummyJobConfiguration.builder()
.successfulTasksCount(tasksCount)
.taskProcessingTimeMs(50)
.taskProcessingTimeMs(TimeUnit.SECONDS.toMillis(30)) // keeps tasks in flight when the job is cancelled, whatever the partitioning strategy
.taskProcessingTimeoutMs(TimeUnit.SECONDS.toMillis(60))
.build()).getId();
Thread.sleep(500);
await().atMost(TIMEOUT, TimeUnit.SECONDS).untilAsserted(() -> {
assertThat(findJobById(jobId).getStatus()).isEqualTo(JobStatus.RUNNING);
});
cancelJob(jobId);
await().atMost(TIMEOUT, TimeUnit.SECONDS).untilAsserted(() -> {
Job job = findJobById(jobId);

205
application/src/test/java/org/thingsboard/server/service/queue/DefaultTbClusterServiceTest.java

@ -32,6 +32,7 @@ import org.thingsboard.server.common.msg.TbMsg;
import org.thingsboard.server.common.msg.TbMsgMetaData;
import org.thingsboard.server.common.msg.queue.ServiceType;
import org.thingsboard.server.common.msg.queue.TopicPartitionInfo;
import org.thingsboard.server.common.msg.rpc.FromDeviceRpcResponse;
import org.thingsboard.server.dao.cf.CalculatedFieldService;
import org.thingsboard.server.dao.edge.EdgeService;
import org.thingsboard.server.gen.transport.TransportProtos;
@ -42,6 +43,7 @@ import org.thingsboard.server.queue.common.TbProtoQueueMsg;
import org.thingsboard.server.queue.common.TbRuleEngineProducerService;
import org.thingsboard.server.queue.discovery.PartitionService;
import org.thingsboard.server.queue.discovery.TopicService;
import org.thingsboard.server.queue.discovery.event.ServiceListChangedEvent;
import org.thingsboard.server.queue.provider.TbQueueProducerProvider;
import org.thingsboard.server.service.gateway_device.GatewayNotificationsService;
import org.thingsboard.server.service.ota.OtaPackageStateService;
@ -77,6 +79,8 @@ public class DefaultTbClusterServiceTest {
public static final String TRANSPORT = "transport";
public static final String UNKNOWN_SERVICE_ID = "not-a-cluster-member";
@MockitoBean
protected TbDeviceProfileCache deviceProfileCache;
@MockitoBean
@ -277,6 +281,7 @@ public class DefaultTbClusterServiceTest {
TbQueueProducer<TbProtoQueueMsg<TransportProtos.ToCoreNotificationMsg>> tbCoreQueueProducer = mock(TbQueueProducer.class);
doReturn(tpi).when(topicService).getNotificationsTopic(any(ServiceType.class), any(String.class));
when(partitionService.isKnownServiceId(ServiceType.TB_CORE, CORE)).thenReturn(true);
when(producerProvider.getTbCoreNotificationsMsgProducer()).thenReturn(tbCoreQueueProducer);
TransportProtos.RestApiCallResponseMsgProto responseMsgProto = TransportProtos.RestApiCallResponseMsgProto.getDefaultInstance();
TransportProtos.ToCoreNotificationMsg toCoreNotificationMsg = TransportProtos.ToCoreNotificationMsg.newBuilder().setRestApiCallResponseMsg(responseMsgProto).build();
@ -291,6 +296,206 @@ public class DefaultTbClusterServiceTest {
assertThat(protoQueueMsgArgumentCaptorValue.getKey()).isNotNull();
assertThat(protoQueueMsgArgumentCaptorValue.getValue()).isEqualTo(toCoreNotificationMsg);
assertThat(protoQueueMsgArgumentCaptorValue.getHeaders().getData()).isEqualTo(new DefaultTbQueueMsgHeaders().getData());
// a live member is accepted without falling back to the fail-open / recently-seen checks
verify(partitionService, never()).getAllServiceIds(ServiceType.TB_CORE);
}
@Test
public void testPushNotificationToCoreToUnknownServiceIdIsSkipped() {
when(partitionService.getAllServiceIds(ServiceType.TB_CORE)).thenReturn(Sets.newHashSet(CORE));
TbQueueCallback callback = mock(TbQueueCallback.class);
clusterService.pushNotificationToCore(UNKNOWN_SERVICE_ID, new FromDeviceRpcResponse(UUID.randomUUID(), null, null), callback);
verify(topicService, never()).getNotificationsTopic(eq(ServiceType.TB_CORE), eq(UNKNOWN_SERVICE_ID));
verify(producerProvider, never()).getTbCoreNotificationsMsgProducer();
verify(callback, times(1)).onSuccess(isNull());
verify(callback, never()).onFailure(any(Throwable.class));
}
@Test
public void testPushNotificationToCoreToRecentlySeenButOfflineServiceIdIsSent() {
String offlineCore = "core-offline";
TopicPartitionInfo tpi = mock(TopicPartitionInfo.class);
TbQueueCallback callback = mock(TbQueueCallback.class);
TbQueueProducer<TbProtoQueueMsg<TransportProtos.ToCoreNotificationMsg>> tbCoreQueueProducer = mock(TbQueueProducer.class);
// offlineCore was a cluster member moments ago but has dropped out of the current live snapshot
((DefaultTbClusterService) clusterService).onServiceListChanged(new ServiceListChangedEvent(
List.of(TransportProtos.ServiceInfo.newBuilder().setServiceId(offlineCore).addServiceTypes(ServiceType.TB_CORE.name()).build()),
TransportProtos.ServiceInfo.newBuilder().setServiceId(CORE).addServiceTypes(ServiceType.TB_CORE.name()).build()));
when(partitionService.getAllServiceIds(ServiceType.TB_CORE)).thenReturn(Sets.newHashSet(CORE));
doReturn(tpi).when(topicService).getNotificationsTopic(ServiceType.TB_CORE, offlineCore);
when(producerProvider.getTbCoreNotificationsMsgProducer()).thenReturn(tbCoreQueueProducer);
clusterService.pushNotificationToCore(offlineCore, new FromDeviceRpcResponse(UUID.randomUUID(), null, null), callback);
verify(tbCoreQueueProducer, times(1)).send(eq(tpi), any(TbProtoQueueMsg.class), eq(callback));
}
@Test
public void testPushNotificationToCoreToKnownServiceIdIsSent() {
TopicPartitionInfo tpi = mock(TopicPartitionInfo.class);
TbQueueCallback callback = mock(TbQueueCallback.class);
TbQueueProducer<TbProtoQueueMsg<TransportProtos.ToCoreNotificationMsg>> tbCoreQueueProducer = mock(TbQueueProducer.class);
when(partitionService.isKnownServiceId(ServiceType.TB_CORE, CORE)).thenReturn(true);
doReturn(tpi).when(topicService).getNotificationsTopic(ServiceType.TB_CORE, CORE);
when(producerProvider.getTbCoreNotificationsMsgProducer()).thenReturn(tbCoreQueueProducer);
clusterService.pushNotificationToCore(CORE, new FromDeviceRpcResponse(UUID.randomUUID(), null, null), callback);
verify(tbCoreQueueProducer, times(1)).send(eq(tpi), any(TbProtoQueueMsg.class), eq(callback));
// a live member is accepted without falling back to the fail-open / recently-seen checks
verify(partitionService, never()).getAllServiceIds(ServiceType.TB_CORE);
}
@Test
public void testPushNotificationToCoreFailsOpenWhenClusterTopologyIsUnknown() {
TopicPartitionInfo tpi = mock(TopicPartitionInfo.class);
TbQueueCallback callback = mock(TbQueueCallback.class);
TbQueueProducer<TbProtoQueueMsg<TransportProtos.ToCoreNotificationMsg>> tbCoreQueueProducer = mock(TbQueueProducer.class);
when(partitionService.getAllServiceIds(ServiceType.TB_CORE)).thenReturn(Sets.newHashSet());
doReturn(tpi).when(topicService).getNotificationsTopic(any(ServiceType.class), any(String.class));
when(producerProvider.getTbCoreNotificationsMsgProducer()).thenReturn(tbCoreQueueProducer);
clusterService.pushNotificationToCore(UNKNOWN_SERVICE_ID, new FromDeviceRpcResponse(UUID.randomUUID(), null, null), callback);
verify(tbCoreQueueProducer, times(1)).send(eq(tpi), any(TbProtoQueueMsg.class), eq(callback));
}
@Test
public void testPushNotificationToRuleEngineToUnknownServiceIdIsSkipped() {
when(partitionService.getAllServiceIds(ServiceType.TB_RULE_ENGINE)).thenReturn(Sets.newHashSet(RULE_ENGINE));
TbQueueCallback callback = mock(TbQueueCallback.class);
clusterService.pushNotificationToRuleEngine(UNKNOWN_SERVICE_ID, new FromDeviceRpcResponse(UUID.randomUUID(), null, null), callback);
verify(topicService, never()).getNotificationsTopic(eq(ServiceType.TB_RULE_ENGINE), eq(UNKNOWN_SERVICE_ID));
verify(producerProvider, never()).getRuleEngineNotificationsMsgProducer();
verify(callback, times(1)).onSuccess(isNull());
verify(callback, never()).onFailure(any(Throwable.class));
}
@Test
public void testPushNotificationToRuleEngineToRecentlySeenButOfflineServiceIdIsSent() {
String offlineRuleEngine = "rule-engine-offline";
TopicPartitionInfo tpi = mock(TopicPartitionInfo.class);
TbQueueCallback callback = mock(TbQueueCallback.class);
TbQueueProducer<TbProtoQueueMsg<TransportProtos.ToRuleEngineNotificationMsg>> tbRuleEngineQueueProducer = mock(TbQueueProducer.class);
// offlineRuleEngine was a cluster member moments ago but has dropped out of the current live snapshot
((DefaultTbClusterService) clusterService).onServiceListChanged(new ServiceListChangedEvent(
List.of(TransportProtos.ServiceInfo.newBuilder().setServiceId(offlineRuleEngine).addServiceTypes(ServiceType.TB_RULE_ENGINE.name()).build()),
TransportProtos.ServiceInfo.newBuilder().setServiceId(RULE_ENGINE).addServiceTypes(ServiceType.TB_RULE_ENGINE.name()).build()));
when(partitionService.getAllServiceIds(ServiceType.TB_RULE_ENGINE)).thenReturn(Sets.newHashSet(RULE_ENGINE));
doReturn(tpi).when(topicService).getNotificationsTopic(ServiceType.TB_RULE_ENGINE, offlineRuleEngine);
when(producerProvider.getRuleEngineNotificationsMsgProducer()).thenReturn(tbRuleEngineQueueProducer);
clusterService.pushNotificationToRuleEngine(offlineRuleEngine, new FromDeviceRpcResponse(UUID.randomUUID(), null, null), callback);
verify(tbRuleEngineQueueProducer, times(1)).send(eq(tpi), any(TbProtoQueueMsg.class), eq(callback));
}
@Test
public void testPushNotificationToRuleEngineToKnownServiceIdIsSent() {
TopicPartitionInfo tpi = mock(TopicPartitionInfo.class);
TbQueueCallback callback = mock(TbQueueCallback.class);
TbQueueProducer<TbProtoQueueMsg<TransportProtos.ToRuleEngineNotificationMsg>> tbRuleEngineQueueProducer = mock(TbQueueProducer.class);
when(partitionService.isKnownServiceId(ServiceType.TB_RULE_ENGINE, RULE_ENGINE)).thenReturn(true);
doReturn(tpi).when(topicService).getNotificationsTopic(ServiceType.TB_RULE_ENGINE, RULE_ENGINE);
when(producerProvider.getRuleEngineNotificationsMsgProducer()).thenReturn(tbRuleEngineQueueProducer);
clusterService.pushNotificationToRuleEngine(RULE_ENGINE, new FromDeviceRpcResponse(UUID.randomUUID(), null, null), callback);
verify(tbRuleEngineQueueProducer, times(1)).send(eq(tpi), any(TbProtoQueueMsg.class), eq(callback));
// a live member is accepted without falling back to the fail-open / recently-seen checks
verify(partitionService, never()).getAllServiceIds(ServiceType.TB_RULE_ENGINE);
}
@Test
public void testPushNotificationToRuleEngineFailsOpenWhenClusterTopologyIsUnknown() {
TopicPartitionInfo tpi = mock(TopicPartitionInfo.class);
TbQueueCallback callback = mock(TbQueueCallback.class);
TbQueueProducer<TbProtoQueueMsg<TransportProtos.ToRuleEngineNotificationMsg>> tbRuleEngineQueueProducer = mock(TbQueueProducer.class);
when(partitionService.getAllServiceIds(ServiceType.TB_RULE_ENGINE)).thenReturn(Sets.newHashSet());
doReturn(tpi).when(topicService).getNotificationsTopic(any(ServiceType.class), any(String.class));
when(producerProvider.getRuleEngineNotificationsMsgProducer()).thenReturn(tbRuleEngineQueueProducer);
clusterService.pushNotificationToRuleEngine(UNKNOWN_SERVICE_ID, new FromDeviceRpcResponse(UUID.randomUUID(), null, null), callback);
verify(tbRuleEngineQueueProducer, times(1)).send(eq(tpi), any(TbProtoQueueMsg.class), eq(callback));
}
@Test
public void testPushNotificationToTransportToUnknownServiceIdIsSkipped() {
when(partitionService.getAllServiceIds(ServiceType.TB_TRANSPORT)).thenReturn(Sets.newHashSet(TRANSPORT));
TbQueueCallback callback = mock(TbQueueCallback.class);
clusterService.pushNotificationToTransport(UNKNOWN_SERVICE_ID, TransportProtos.ToTransportMsg.getDefaultInstance(), callback);
verify(topicService, never()).getNotificationsTopic(eq(ServiceType.TB_TRANSPORT), eq(UNKNOWN_SERVICE_ID));
verify(producerProvider, never()).getTransportNotificationsMsgProducer();
verify(callback, times(1)).onSuccess(isNull());
verify(callback, never()).onFailure(any(Throwable.class));
}
@Test
public void testPushNotificationToTransportToKnownServiceIdIsSent() {
TopicPartitionInfo tpi = mock(TopicPartitionInfo.class);
TbQueueCallback callback = mock(TbQueueCallback.class);
TbQueueProducer<TbProtoQueueMsg<TransportProtos.ToTransportMsg>> tbTransportQueueProducer = mock(TbQueueProducer.class);
when(partitionService.isKnownServiceId(ServiceType.TB_TRANSPORT, TRANSPORT)).thenReturn(true);
doReturn(tpi).when(topicService).getNotificationsTopic(ServiceType.TB_TRANSPORT, TRANSPORT);
when(producerProvider.getTransportNotificationsMsgProducer()).thenReturn(tbTransportQueueProducer);
clusterService.pushNotificationToTransport(TRANSPORT, TransportProtos.ToTransportMsg.getDefaultInstance(), callback);
verify(tbTransportQueueProducer, times(1)).send(eq(tpi), any(TbProtoQueueMsg.class), eq(callback));
// a live member is accepted without falling back to the fail-open / recently-seen checks
verify(partitionService, never()).getAllServiceIds(ServiceType.TB_TRANSPORT);
}
@Test
public void testPushNotificationToTransportToRecentlySeenButOfflineServiceIdIsSent() {
String offlineTransport = "transport-offline";
TopicPartitionInfo tpi = mock(TopicPartitionInfo.class);
TbQueueCallback callback = mock(TbQueueCallback.class);
TbQueueProducer<TbProtoQueueMsg<TransportProtos.ToTransportMsg>> tbTransportQueueProducer = mock(TbQueueProducer.class);
// offlineTransport was a cluster member moments ago but has dropped out of the current live snapshot
((DefaultTbClusterService) clusterService).onServiceListChanged(new ServiceListChangedEvent(
List.of(TransportProtos.ServiceInfo.newBuilder().setServiceId(offlineTransport).addServiceTypes(ServiceType.TB_TRANSPORT.name()).build()),
TransportProtos.ServiceInfo.newBuilder().setServiceId(TRANSPORT).addServiceTypes(ServiceType.TB_TRANSPORT.name()).build()));
when(partitionService.getAllServiceIds(ServiceType.TB_TRANSPORT)).thenReturn(Sets.newHashSet(TRANSPORT));
doReturn(tpi).when(topicService).getNotificationsTopic(ServiceType.TB_TRANSPORT, offlineTransport);
when(producerProvider.getTransportNotificationsMsgProducer()).thenReturn(tbTransportQueueProducer);
clusterService.pushNotificationToTransport(offlineTransport, TransportProtos.ToTransportMsg.getDefaultInstance(), callback);
verify(tbTransportQueueProducer, times(1)).send(eq(tpi), any(TbProtoQueueMsg.class), eq(callback));
}
@Test
public void testPushNotificationToTransportFailsOpenWhenClusterTopologyIsUnknown() {
TopicPartitionInfo tpi = mock(TopicPartitionInfo.class);
TbQueueCallback callback = mock(TbQueueCallback.class);
TbQueueProducer<TbProtoQueueMsg<TransportProtos.ToTransportMsg>> tbTransportQueueProducer = mock(TbQueueProducer.class);
when(partitionService.getAllServiceIds(ServiceType.TB_TRANSPORT)).thenReturn(Sets.newHashSet());
doReturn(tpi).when(topicService).getNotificationsTopic(any(ServiceType.class), any(String.class));
when(producerProvider.getTransportNotificationsMsgProducer()).thenReturn(tbTransportQueueProducer);
clusterService.pushNotificationToTransport(UNKNOWN_SERVICE_ID, TransportProtos.ToTransportMsg.getDefaultInstance(), callback);
verify(tbTransportQueueProducer, times(1)).send(eq(tpi), any(TbProtoQueueMsg.class), eq(callback));
}
@Test

86
application/src/test/java/org/thingsboard/server/service/script/NashornJsInvokeServiceTest.java

@ -4,13 +4,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;
@ -18,6 +22,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;
@ -209,6 +214,87 @@ 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 + "')")).isEqualTo(true);
invokeService.release(scriptId).get();
// the property must be deleted, not just set to undefined: an abandoned binding keeps
// its slot in the Global's PropertyMap forever
assertThat(evalInEngine("this.hasOwnProperty('" + functionName + "')")).isEqualTo(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, "{}");

14
application/src/test/java/org/thingsboard/server/service/script/TbelInvokeServiceTest.java

@ -288,6 +288,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, "{}");

45
application/src/test/java/org/thingsboard/server/service/security/auth/oauth2/CookieUtilsTest.java

@ -1,45 +0,0 @@
// SPDX-FileCopyrightText: Copyright The Thingsboard Authors
// SPDX-License-Identifier: Apache-2.0
package org.thingsboard.server.service.security.auth.oauth2;
import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletRequest;
import org.junit.Test;
import org.mockito.Mockito;
import org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationRequest;
import java.util.LinkedHashMap;
import java.util.Map;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.thingsboard.server.service.security.auth.oauth2.HttpCookieOAuth2AuthorizationRequestRepository.OAUTH2_AUTHORIZATION_REQUEST_COOKIE_NAME;
public class CookieUtilsTest {
@Test
public void serializeDeserializeOAuth2AuthorizationRequestTest() {
HttpCookieOAuth2AuthorizationRequestRepository cookieRequestRepo = new HttpCookieOAuth2AuthorizationRequestRepository();
HttpServletRequest servletRequest = Mockito.mock(HttpServletRequest.class);
Map<String, Object> additionalParameters = new LinkedHashMap<>();
additionalParameters.put("param1", "value1");
additionalParameters.put("param2", "value2");
var request = OAuth2AuthorizationRequest.authorizationCode()
.authorizationUri("testUri").clientId("testId")
.scope("read", "write")
.additionalParameters(additionalParameters).build();
Cookie cookie = new Cookie(OAUTH2_AUTHORIZATION_REQUEST_COOKIE_NAME, CookieUtils.serialize(request));
Mockito.when(servletRequest.getCookies()).thenReturn(new Cookie[]{cookie});
OAuth2AuthorizationRequest deserializedRequest = cookieRequestRepo.loadAuthorizationRequest(servletRequest);
assertNotNull(deserializedRequest);
assertEquals(request.getGrantType(), deserializedRequest.getGrantType());
assertEquals(request.getAuthorizationUri(), deserializedRequest.getAuthorizationUri());
assertEquals(request.getClientId(), deserializedRequest.getClientId());
}
}

151
application/src/test/java/org/thingsboard/server/service/security/auth/oauth2/HttpCookieOAuth2AuthorizationRequestRepositoryTest.java

@ -2,27 +2,50 @@
// SPDX-License-Identifier: Apache-2.0
package org.thingsboard.server.service.security.auth.oauth2;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.NullAndEmptySource;
import org.junit.jupiter.params.provider.ValueSource;
import org.mockito.ArgumentCaptor;
import org.springframework.security.jackson2.SecurityJackson2Modules;
import org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationRequest;
import org.thingsboard.server.common.data.security.model.JwtSettings;
import org.thingsboard.server.service.security.auth.jwt.settings.JwtSettingsService;
import java.security.SecureRandom;
import java.time.Clock;
import java.util.Base64;
import java.util.LinkedHashMap;
import java.util.Map;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.atLeastOnce;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static org.thingsboard.server.service.security.auth.oauth2.HttpCookieOAuth2AuthorizationRequestRepository.OAUTH2_AUTHORIZATION_REQUEST_COOKIE_NAME;
import static org.thingsboard.server.service.security.auth.oauth2.HttpCookieOAuth2AuthorizationRequestRepository.PREV_URI_COOKIE_NAME;
import static org.thingsboard.server.service.security.auth.oauth2.HttpCookieOAuth2AuthorizationRequestRepository.PREV_URI_PARAMETER;
public class HttpCookieOAuth2AuthorizationRequestRepositoryTest {
private final HttpCookieOAuth2AuthorizationRequestRepository repository = new HttpCookieOAuth2AuthorizationRequestRepository();
private static final long NOW = 1_700_000_000_000L;
private final JwtSettingsService jwtSettingsService = mock(JwtSettingsService.class);
private final Clock clock = mock(Clock.class);
private final HttpCookieOAuth2AuthorizationRequestRepository repository =
new HttpCookieOAuth2AuthorizationRequestRepository(jwtSettingsService, clock);
@BeforeEach
public void before() {
givenSigningKey(randomSigningKey());
when(clock.millis()).thenReturn(NOW);
}
@Test
public void testPrevUriSavedForInAppPath() {
@ -37,20 +60,140 @@ public class HttpCookieOAuth2AuthorizationRequestRepositoryTest {
assertThat(savePrevUri(prevUri)).isNull();
}
@Test
public void testAuthorizationRequestRoundTrip() {
Map<String, Object> additionalParameters = new LinkedHashMap<>();
additionalParameters.put("param1", "value1");
additionalParameters.put("param2", "value2");
OAuth2AuthorizationRequest authorizationRequest = OAuth2AuthorizationRequest.authorizationCode()
.authorizationUri("testUri").clientId("testId")
.scope("read", "write")
.state("testState")
.additionalParameters(additionalParameters)
.attributes(attributes -> attributes.put(TbOAuth2ParameterNames.CALLBACK_URL_SCHEME, "tbmobile"))
.build();
OAuth2AuthorizationRequest loaded = load(save(authorizationRequest));
assertThat(loaded).isNotNull();
assertThat(loaded.getGrantType()).isEqualTo(authorizationRequest.getGrantType());
assertThat(loaded.getAuthorizationUri()).isEqualTo(authorizationRequest.getAuthorizationUri());
assertThat(loaded.getClientId()).isEqualTo(authorizationRequest.getClientId());
assertThat(loaded.getScopes()).isEqualTo(authorizationRequest.getScopes());
assertThat(loaded.getState()).isEqualTo(authorizationRequest.getState());
assertThat(loaded.getAdditionalParameters()).isEqualTo(additionalParameters);
assertThat(CallbackUrlSchemeValidator.getCallbackUrlScheme(loaded)).isEqualTo("tbmobile");
}
@Test
public void testCookieIsNotPlainJson() {
String cookieValue = save(authorizationRequest());
assertThat(new String(Base64.getUrlDecoder().decode(cookieValue))).doesNotContain("testId");
}
@Test
public void testEachCookieUsesFreshNonce() {
assertThat(save(authorizationRequest())).isNotEqualTo(save(authorizationRequest()));
}
@Test
public void testTamperedCookieIsRejected() {
byte[] envelope = Base64.getUrlDecoder().decode(save(authorizationRequest()));
for (int i = 0; i < envelope.length; i++) {
byte[] tampered = envelope.clone();
tampered[i] ^= 0x01;
assertThat(load(Base64.getUrlEncoder().withoutPadding().encodeToString(tampered))).as("bit flipped at byte %s", i).isNull();
}
}
@Test
public void testTruncatedCookieIsRejected() {
String cookieValue = save(authorizationRequest());
assertThat(load(cookieValue.substring(0, cookieValue.length() - 4))).isNull();
}
@Test
public void testCookieEncryptedWithDifferentKeyIsRejected() {
String cookieValue = save(authorizationRequest());
givenSigningKey(randomSigningKey());
assertThat(load(cookieValue)).isNull();
}
@Test
public void testNewCookieIsAcceptedAfterKeyRotation() {
givenSigningKey(randomSigningKey());
String cookieValue = save(authorizationRequest());
assertThat(load(cookieValue)).isNotNull();
}
@Test
public void testUnencryptedCookieIsRejected() throws Exception {
ObjectMapper mapper = new ObjectMapper().registerModules(SecurityJackson2Modules.getModules(getClass().getClassLoader()));
String plainCookieValue = Base64.getUrlEncoder().encodeToString(mapper.writeValueAsBytes(authorizationRequest()));
assertThat(load(plainCookieValue)).isNull();
}
@ParameterizedTest
@ValueSource(strings = {"", "a", "AAAA", "not base64 !", "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"})
public void testMalformedCookieIsRejected(String cookieValue) {
assertThat(load(cookieValue)).isNull();
}
@Test
public void testExpiredCookieIsRejected() {
String cookieValue = save(authorizationRequest());
when(clock.millis()).thenReturn(NOW + 180_000);
assertThat(load(cookieValue)).isNotNull();
when(clock.millis()).thenReturn(NOW + 180_001);
assertThat(load(cookieValue)).isNull();
}
private OAuth2AuthorizationRequest authorizationRequest() {
return OAuth2AuthorizationRequest.authorizationCode().authorizationUri("testUri").clientId("testId").build();
}
private String save(OAuth2AuthorizationRequest authorizationRequest) {
HttpServletRequest request = mock(HttpServletRequest.class);
HttpServletResponse response = mock(HttpServletResponse.class);
repository.saveAuthorizationRequest(authorizationRequest, request, response);
return findCookie(response, OAUTH2_AUTHORIZATION_REQUEST_COOKIE_NAME);
}
private OAuth2AuthorizationRequest load(String cookieValue) {
HttpServletRequest request = mock(HttpServletRequest.class);
when(request.getCookies()).thenReturn(new Cookie[]{new Cookie(OAUTH2_AUTHORIZATION_REQUEST_COOKIE_NAME, cookieValue)});
return repository.loadAuthorizationRequest(request);
}
private String savePrevUri(String prevUri) {
HttpServletRequest request = mock(HttpServletRequest.class);
HttpServletResponse response = mock(HttpServletResponse.class);
when(request.getParameter(PREV_URI_PARAMETER)).thenReturn(prevUri);
repository.saveAuthorizationRequest(OAuth2AuthorizationRequest.authorizationCode()
.authorizationUri("testUri").clientId("testId").build(), request, response);
repository.saveAuthorizationRequest(authorizationRequest(), request, response);
return findCookie(response, PREV_URI_COOKIE_NAME);
}
private String findCookie(HttpServletResponse response, String name) {
ArgumentCaptor<Cookie> cookieCaptor = ArgumentCaptor.forClass(Cookie.class);
verify(response, atLeastOnce()).addCookie(cookieCaptor.capture());
return cookieCaptor.getAllValues().stream()
.filter(cookie -> PREV_URI_COOKIE_NAME.equals(cookie.getName()))
.filter(cookie -> name.equals(cookie.getName()))
.map(Cookie::getValue)
.findAny().orElse(null);
}
private void givenSigningKey(String signingKey) {
JwtSettings jwtSettings = new JwtSettings();
jwtSettings.setTokenSigningKey(signingKey);
when(jwtSettingsService.getJwtSettings()).thenReturn(jwtSettings);
}
private static String randomSigningKey() {
byte[] key = new byte[64];
new SecureRandom().nextBytes(key);
return Base64.getEncoder().encodeToString(key);
}
}

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

Loading…
Cancel
Save