Browse Source
# Conflicts: # application/src/main/java/org/thingsboard/server/service/edge/rpc/EdgeGrpcService.javapull/16163/head
327 changed files with 21200 additions and 6821 deletions
@ -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 |
|||
@ -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)); |
|||
} |
|||
|
|||
} |
|||
@ -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; |
|||
} |
|||
|
|||
} |
|||
@ -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))); |
|||
} |
|||
|
|||
} |
|||
@ -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); |
|||
} |
|||
|
|||
} |
|||
@ -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) { |
|||
} |
|||
@ -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; |
|||
} |
|||
|
|||
} |
|||
@ -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(); |
|||
} |
|||
|
|||
} |
|||
@ -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); |
|||
} |
|||
|
|||
} |
|||
@ -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) { |
|||
} |
|||
@ -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) { |
|||
} |
|||
@ -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")); |
|||
} |
|||
|
|||
} |
|||
@ -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) {} |
|||
|
|||
} |
|||
@ -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)); |
|||
} |
|||
|
|||
} |
|||
@ -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(); |
|||
} |
|||
|
|||
} |
|||
@ -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); |
|||
} |
|||
|
|||
} |
|||
@ -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) { |
|||
} |
|||
@ -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"); |
|||
} |
|||
} |
|||
|
|||
} |
|||
@ -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) { |
|||
} |
|||
@ -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) { |
|||
} |
|||
@ -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); |
|||
} |
|||
} |
|||
|
|||
} |
|||
@ -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; |
|||
|
|||
} |
|||
@ -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); |
|||
} |
|||
|
|||
} |
|||
@ -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"); |
|||
} |
|||
} |
|||
} |
|||
@ -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); |
|||
} |
|||
|
|||
} |
|||
@ -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(); |
|||
} |
|||
|
|||
} |
|||
@ -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()); |
|||
} |
|||
} |
|||
@ -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(); |
|||
} |
|||
|
|||
} |
|||
@ -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(); |
|||
} |
|||
|
|||
} |
|||
@ -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); |
|||
} |
|||
} |
|||
|
|||
} |
|||
@ -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); |
|||
} |
|||
|
|||
} |
|||
@ -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); |
|||
} |
|||
|
|||
} |
|||
@ -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); |
|||
} |
|||
} |
|||
|
|||
} |
|||
@ -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); |
|||
} |
|||
|
|||
} |
|||
@ -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(); |
|||
} |
|||
|
|||
} |
|||
File diff suppressed because it is too large
@ -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(); |
|||
} |
|||
}; |
|||
} |
|||
|
|||
} |
|||
@ -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; |
|||
} |
|||
|
|||
} |
|||
@ -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(); |
|||
} |
|||
|
|||
} |
|||
@ -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); |
|||
} |
|||
|
|||
} |
|||
@ -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(); |
|||
} |
|||
|
|||
} |
|||
@ -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(); |
|||
} |
|||
|
|||
} |
|||
@ -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); |
|||
} |
|||
|
|||
} |
|||
@ -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"); |
|||
} |
|||
} |
|||
|
|||
} |
|||
File diff suppressed because it is too large
@ -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); |
|||
} |
|||
|
|||
} |
|||
@ -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); |
|||
} |
|||
} |
|||
|
|||
} |
|||
@ -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; |
|||
} |
|||
|
|||
} |
|||
@ -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")); |
|||
} |
|||
|
|||
} |
|||
@ -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; |
|||
} |
|||
} |
|||
@ -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(); |
|||
} |
|||
|
|||
} |
|||
@ -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()); |
|||
} |
|||
|
|||
} |
|||
Some files were not shown because too many files changed in this diff
Loading…
Reference in new issue