Browse Source
# Conflicts: # application/src/test/java/org/thingsboard/server/edge/UserEdgeTest.java # common/cache/src/main/java/org/thingsboard/server/cache/RedisTbTransactionalCache.java # pom.xml # tools/src/main/python/license-headers/README.md # tools/src/main/python/license-headers/check_license_headers.py # tools/src/main/python/license-headers/test_check_license_headers.pypull/16341/head
777 changed files with 121892 additions and 41413 deletions
@ -0,0 +1,2 @@ |
|||
# Shipped as committed: its SBOM records the SHA-256 of these exact bytes |
|||
application/src/main/data/resources/js_extensions/gateway-management-extension.js -text |
|||
@ -0,0 +1,14 @@ |
|||
# Maintainers |
|||
|
|||
This file lists the maintainers of the ThingsBoard project. |
|||
Maintainers review and merge pull requests, triage issues, and drive project releases. |
|||
|
|||
| Name | GitHub | Email | |
|||
|---------------------|--------------------------------------------------------|---------------------------| |
|||
| Andrii Shvaika | [@ashvayka](https://github.com/ashvayka) | ashvayka@thingsboard.io | |
|||
| Igor Kulikov | [@ikulikov](https://github.com/ikulikov) | ikulikov@thingsboard.io | |
|||
| Viacheslav Klimov | [@ViacheslavKlimov](https://github.com/ViacheslavKlimov) | vklimov@thingsboard.io | |
|||
| Vladyslav Prykhodko | [@vvlladd28](https://github.com/vvlladd28) | vprykhodko@thingsboard.io | |
|||
| Sergey Matvienko | [@smatvienko-tb](https://github.com/smatvienko-tb) | smatvienko@thingsboard.io | |
|||
|
|||
For security issues, please follow the process described in [security.md](security.md) instead of contacting maintainers directly. |
|||
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
@ -0,0 +1,80 @@ |
|||
// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc.
|
|||
// SPDX-License-Identifier: BUSL-1.1
|
|||
package org.thingsboard.server.controller; |
|||
|
|||
import com.fasterxml.jackson.databind.JsonNode; |
|||
import lombok.RequiredArgsConstructor; |
|||
import org.springframework.http.CacheControl; |
|||
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.DeleteMapping; |
|||
import org.springframework.web.bind.annotation.GetMapping; |
|||
import org.springframework.web.bind.annotation.PathVariable; |
|||
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.ResponseStatus; |
|||
import org.springframework.web.bind.annotation.RestController; |
|||
import org.springframework.web.multipart.MultipartFile; |
|||
import org.thingsboard.server.common.data.exception.ThingsboardException; |
|||
import org.thingsboard.server.common.data.permission.Operation; |
|||
import org.thingsboard.server.common.data.permission.Resource; |
|||
import org.thingsboard.server.queue.util.TbCoreComponent; |
|||
import org.thingsboard.server.service.ai.resource.AiResourceService; |
|||
import org.thingsboard.server.service.security.model.SecurityUser; |
|||
|
|||
import java.time.Duration; |
|||
import java.util.UUID; |
|||
|
|||
@RequiredArgsConstructor |
|||
@RestController |
|||
@TbCoreComponent |
|||
@RequestMapping("/api/ai/resources") |
|||
class AiResourceController extends BaseController { |
|||
|
|||
private final AiResourceService aiResourceService; |
|||
|
|||
@PreAuthorize("hasAuthority('TENANT_ADMIN')") |
|||
@GetMapping("/config") |
|||
public JsonNode getAiResourcesConfig() throws ThingsboardException { |
|||
SecurityUser user = getCurrentUser(); |
|||
accessControlService.checkPermission(user, Resource.AI, Operation.READ); |
|||
return aiResourceService.getConfig(user); |
|||
} |
|||
|
|||
@PreAuthorize("hasAuthority('TENANT_ADMIN')") |
|||
@PostMapping(consumes = MediaType.MULTIPART_FORM_DATA_VALUE) |
|||
@ResponseStatus(HttpStatus.CREATED) |
|||
public JsonNode uploadAiResource(@RequestPart("file") MultipartFile file) throws ThingsboardException { |
|||
SecurityUser user = getCurrentUser(); |
|||
accessControlService.checkPermission(user, Resource.AI, Operation.WRITE); |
|||
return aiResourceService.upload(file, user); |
|||
} |
|||
|
|||
@PreAuthorize("hasAuthority('TENANT_ADMIN')") |
|||
@GetMapping("/{resourceId}") |
|||
public ResponseEntity<byte[]> downloadAiResource(@PathVariable UUID resourceId) throws ThingsboardException { |
|||
SecurityUser user = getCurrentUser(); |
|||
accessControlService.checkPermission(user, Resource.AI, Operation.READ); |
|||
AiResourceService.AiResourceContent content = aiResourceService.download(resourceId, user); |
|||
return ResponseEntity.ok() |
|||
.contentType(MediaType.parseMediaType(content.mediaType())) |
|||
.header(HttpHeaders.CONTENT_DISPOSITION, toContentDisposition(content.name())) |
|||
.header("X-Content-Type-Options", "nosniff") |
|||
.cacheControl(CacheControl.maxAge(Duration.ofHours(1)).cachePrivate()) |
|||
.body(content.data()); |
|||
} |
|||
|
|||
@PreAuthorize("hasAuthority('TENANT_ADMIN')") |
|||
@DeleteMapping("/{resourceId}") |
|||
@ResponseStatus(HttpStatus.NO_CONTENT) |
|||
public void deleteAiResource(@PathVariable UUID resourceId) throws ThingsboardException { |
|||
SecurityUser user = getCurrentUser(); |
|||
accessControlService.checkPermission(user, Resource.AI, Operation.WRITE); |
|||
aiResourceService.delete(resourceId, user); |
|||
} |
|||
|
|||
} |
|||
@ -0,0 +1,24 @@ |
|||
// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc.
|
|||
// SPDX-License-Identifier: BUSL-1.1
|
|||
package org.thingsboard.server.service.ai.resource; |
|||
|
|||
import com.fasterxml.jackson.databind.JsonNode; |
|||
import org.springframework.web.multipart.MultipartFile; |
|||
import org.thingsboard.server.common.data.exception.ThingsboardException; |
|||
import org.thingsboard.server.service.security.model.SecurityUser; |
|||
|
|||
import java.util.UUID; |
|||
|
|||
public interface AiResourceService { |
|||
|
|||
JsonNode getConfig(SecurityUser user); |
|||
|
|||
JsonNode upload(MultipartFile file, SecurityUser user) throws ThingsboardException; |
|||
|
|||
AiResourceContent download(UUID resourceId, SecurityUser user); |
|||
|
|||
void delete(UUID resourceId, SecurityUser user); |
|||
|
|||
record AiResourceContent(String name, String mediaType, byte[] data) {} |
|||
|
|||
} |
|||
@ -0,0 +1,84 @@ |
|||
// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc.
|
|||
// SPDX-License-Identifier: BUSL-1.1
|
|||
package org.thingsboard.server.service.ai.resource; |
|||
|
|||
import com.fasterxml.jackson.databind.JsonNode; |
|||
import lombok.RequiredArgsConstructor; |
|||
import org.springframework.stereotype.Service; |
|||
import org.springframework.web.multipart.MultipartFile; |
|||
import org.thingsboard.ai.common.channel.ChannelProtocol; |
|||
import org.thingsboard.ai.common.channel.ResourceOperationRequest; |
|||
import org.thingsboard.ai.common.channel.ResourceUploadRequest; |
|||
import org.thingsboard.server.common.data.exception.ThingsboardErrorCode; |
|||
import org.thingsboard.server.common.data.exception.ThingsboardException; |
|||
import org.thingsboard.server.queue.util.TbCoreComponent; |
|||
import org.thingsboard.server.service.ai.TbAiService; |
|||
import org.thingsboard.server.service.ai.transport.TbAiOperation; |
|||
import org.thingsboard.server.service.ai.transport.TbAiOperations; |
|||
import org.thingsboard.server.service.security.model.SecurityUser; |
|||
|
|||
import java.io.ByteArrayOutputStream; |
|||
import java.io.IOException; |
|||
import java.io.InputStream; |
|||
import java.io.OutputStream; |
|||
import java.nio.charset.StandardCharsets; |
|||
import java.util.Base64; |
|||
import java.util.UUID; |
|||
|
|||
@Service |
|||
@TbCoreComponent |
|||
@RequiredArgsConstructor |
|||
class DefaultAiResourceService implements AiResourceService { |
|||
|
|||
private final TbAiService tbAiService; |
|||
private final TbAiOperations operations; |
|||
|
|||
@Override |
|||
public JsonNode getConfig(SecurityUser user) { |
|||
return tbAiService.process(tokenProvider -> operations.execute( |
|||
new TbAiOperation(ChannelProtocol.RESOURCE_CONFIG, null), user, tokenProvider), user, false); |
|||
} |
|||
|
|||
@Override |
|||
public JsonNode upload(MultipartFile file, SecurityUser user) throws ThingsboardException { |
|||
if (file == null || file.isEmpty()) { |
|||
throw new ThingsboardException("The file is empty", ThingsboardErrorCode.BAD_REQUEST_PARAMS); |
|||
} |
|||
long maxSize = getConfig(user).path("maxSize").asLong(0); |
|||
if (maxSize > 0 && file.getSize() > maxSize) { |
|||
throw new ThingsboardException("The file is too large: " + file.getOriginalFilename(), ThingsboardErrorCode.BAD_REQUEST_PARAMS); |
|||
} |
|||
String data; |
|||
try { |
|||
data = base64(file); |
|||
} catch (IOException e) { |
|||
throw new ThingsboardException("Failed to read the file", e, ThingsboardErrorCode.GENERAL); |
|||
} |
|||
var request = new ResourceUploadRequest(file.getOriginalFilename(), file.getContentType(), data); |
|||
return tbAiService.process(tokenProvider -> operations.execute( |
|||
new TbAiOperation(ChannelProtocol.RESOURCE_UPLOAD, request), user, tokenProvider), user, false); |
|||
} |
|||
|
|||
private static String base64(MultipartFile file) throws IOException { |
|||
var encoded = new ByteArrayOutputStream((int) Math.min(Integer.MAX_VALUE - 8, (file.getSize() + 2) / 3 * 4)); |
|||
try (InputStream in = file.getInputStream(); OutputStream encoder = Base64.getEncoder().wrap(encoded)) { |
|||
in.transferTo(encoder); |
|||
} |
|||
return encoded.toString(StandardCharsets.ISO_8859_1); |
|||
} |
|||
|
|||
@Override |
|||
public AiResourceContent download(UUID resourceId, SecurityUser user) { |
|||
JsonNode content = tbAiService.process(tokenProvider -> operations.execute( |
|||
new TbAiOperation(ChannelProtocol.RESOURCE_GET, new ResourceOperationRequest(resourceId)), user, tokenProvider), user, false); |
|||
return new AiResourceContent(content.path("name").asText(), content.path("mediaType").asText(), |
|||
Base64.getDecoder().decode(content.path("data").asText())); |
|||
} |
|||
|
|||
@Override |
|||
public void delete(UUID resourceId, SecurityUser user) { |
|||
tbAiService.process(tokenProvider -> operations.execute( |
|||
new TbAiOperation(ChannelProtocol.RESOURCE_DELETE, new ResourceOperationRequest(resourceId)), user, tokenProvider), user, false); |
|||
} |
|||
|
|||
} |
|||
@ -0,0 +1,20 @@ |
|||
// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc.
|
|||
// SPDX-License-Identifier: BUSL-1.1
|
|||
package org.thingsboard.server.service.converter; |
|||
|
|||
import org.thingsboard.server.common.data.converter.ConverterType; |
|||
import org.thingsboard.server.common.data.integration.IntegrationType; |
|||
|
|||
import java.util.Optional; |
|||
|
|||
public interface ConverterDefaultsService { |
|||
|
|||
Optional<String> getPayload(IntegrationType integrationType, ConverterType converterType); |
|||
|
|||
Optional<String> getMetadata(IntegrationType integrationType, ConverterType converterType); |
|||
|
|||
Optional<String> getIntegrationName(IntegrationType integrationType); |
|||
|
|||
Optional<String> getDownlinkMsgType(IntegrationType integrationType); |
|||
|
|||
} |
|||
@ -0,0 +1,66 @@ |
|||
// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc.
|
|||
// SPDX-License-Identifier: BUSL-1.1
|
|||
package org.thingsboard.server.service.converter; |
|||
|
|||
import lombok.extern.slf4j.Slf4j; |
|||
import org.springframework.stereotype.Service; |
|||
import org.thingsboard.common.util.JacksonUtil; |
|||
import org.thingsboard.server.common.data.converter.ConverterType; |
|||
import org.thingsboard.server.common.data.integration.IntegrationType; |
|||
import org.thingsboard.server.queue.util.TbCoreComponent; |
|||
|
|||
import java.io.IOException; |
|||
import java.io.InputStream; |
|||
import java.nio.charset.StandardCharsets; |
|||
import java.util.Optional; |
|||
|
|||
@TbCoreComponent |
|||
@Service |
|||
@Slf4j |
|||
public class DefaultConverterDefaultsService implements ConverterDefaultsService { |
|||
|
|||
private static final String CONVERTERS_DIR = "converters"; |
|||
private static final String PAYLOAD_FILE = "payload.json"; |
|||
private static final String METADATA_FILE = "metadata.json"; |
|||
private static final String INTEGRATION_FILE = "integration.json"; |
|||
private static final String MSG_TYPE_FILE = "msgType.txt"; |
|||
|
|||
@Override |
|||
public Optional<String> getPayload(IntegrationType integrationType, ConverterType converterType) { |
|||
return getFileContent(integrationType, converterType.getDirectory() + "/" + PAYLOAD_FILE); |
|||
} |
|||
|
|||
@Override |
|||
public Optional<String> getMetadata(IntegrationType integrationType, ConverterType converterType) { |
|||
return getFileContent(integrationType, converterType.getDirectory() + "/" + METADATA_FILE); |
|||
} |
|||
|
|||
@Override |
|||
public Optional<String> getIntegrationName(IntegrationType integrationType) { |
|||
return getFileContent(integrationType, INTEGRATION_FILE) |
|||
.map(content -> JacksonUtil.toJsonNode(content).get("name").asText()); |
|||
} |
|||
|
|||
@Override |
|||
public Optional<String> getDownlinkMsgType(IntegrationType integrationType) { |
|||
return getFileContent(integrationType, ConverterType.DOWNLINK.getDirectory() + "/" + MSG_TYPE_FILE) |
|||
.map(String::trim); |
|||
} |
|||
|
|||
private Optional<String> getFileContent(IntegrationType integrationType, String relativePath) { |
|||
if (integrationType.getDirectory() == null) { |
|||
return Optional.empty(); |
|||
} |
|||
String path = String.join("/", CONVERTERS_DIR, integrationType.getDirectory(), relativePath); |
|||
try (InputStream in = getClass().getClassLoader().getResourceAsStream(path)) { |
|||
if (in == null) { |
|||
return Optional.empty(); |
|||
} |
|||
return Optional.of(new String(in.readAllBytes(), StandardCharsets.UTF_8)); |
|||
} catch (IOException e) { |
|||
log.warn("Failed to read converter defaults file {}", path, e); |
|||
return Optional.empty(); |
|||
} |
|||
} |
|||
|
|||
} |
|||
@ -0,0 +1,86 @@ |
|||
// SPDX-FileCopyrightText: Copyright The ThingsBoard Authors
|
|||
// SPDX-FileCopyrightText: Modifications Copyright ThingsBoard, Inc.
|
|||
// SPDX-License-Identifier: Apache-2.0 AND BUSL-1.1
|
|||
package org.thingsboard.server.service.edge; |
|||
|
|||
import lombok.RequiredArgsConstructor; |
|||
import lombok.extern.slf4j.Slf4j; |
|||
import org.springframework.stereotype.Component; |
|||
import org.thingsboard.server.common.data.HasOwnerId; |
|||
import org.thingsboard.server.common.data.HasTenantId; |
|||
import org.thingsboard.server.common.data.id.EntityId; |
|||
import org.thingsboard.server.common.data.id.TenantId; |
|||
import org.thingsboard.server.dao.entity.EntityDaoRegistry; |
|||
import org.thingsboard.server.dao.entity.EntityService; |
|||
import org.thingsboard.server.exception.DataValidationException; |
|||
import org.thingsboard.server.queue.util.TbCoreComponent; |
|||
|
|||
/** |
|||
* Checks that entities referenced by edge messages belong to the edge's tenant. |
|||
*/ |
|||
@Slf4j |
|||
@Component |
|||
@TbCoreComponent |
|||
@RequiredArgsConstructor |
|||
public class EdgeEntityTenantChecker { |
|||
|
|||
private final EntityService entityService; |
|||
private final EntityDaoRegistry entityDaoRegistry; |
|||
|
|||
/** |
|||
* Returns true if the entity exists and belongs to the tenant. |
|||
* Uses the entity services, so cached and tenant-scoped lookups are used where available. |
|||
*/ |
|||
public boolean isTenantEntity(TenantId tenantId, EntityId entityId) { |
|||
if (entityId == null) { |
|||
return false; |
|||
} |
|||
try { |
|||
return entityService.fetchEntity(tenantId, entityId) |
|||
.map(entity -> { |
|||
if (entity instanceof HasTenantId hasTenantId) { |
|||
return tenantId.equals(hasTenantId.getTenantId()); |
|||
} |
|||
// entities without own tenant id (entity groups) belong to the tenant of their owner
|
|||
return entity instanceof HasOwnerId hasOwnerId && isTenantEntity(tenantId, hasOwnerId.getOwnerId()); |
|||
}) |
|||
.orElse(false); |
|||
} catch (IllegalArgumentException e) { |
|||
log.warn("[{}] Unsupported entity type of {}", tenantId, entityId); |
|||
return false; |
|||
} |
|||
} |
|||
|
|||
/** |
|||
* Loads the entity regardless of its tenant, so that an id of another tenant's entity is detected. |
|||
* Returns null if the entity doesn't exist, throws if it belongs to a different tenant. |
|||
*/ |
|||
@SuppressWarnings("unchecked") |
|||
public <T> T findTenantEntity(TenantId tenantId, EntityId entityId) { |
|||
Object entity = findEntity(tenantId, entityId); |
|||
if (entity instanceof HasTenantId hasTenantId && !tenantId.equals(hasTenantId.getTenantId())) { |
|||
throw new DataValidationException(entityId.getEntityType() + " " + entityId.getId() + " belongs to a different tenant!"); |
|||
} |
|||
return (T) entity; |
|||
} |
|||
|
|||
/** |
|||
* Returns the tenant of the entity regardless of the given tenant, or null if the entity doesn't exist. |
|||
*/ |
|||
public TenantId findEntityTenantId(TenantId tenantId, EntityId entityId) { |
|||
return findEntity(tenantId, entityId) instanceof HasTenantId hasTenantId ? hasTenantId.getTenantId() : null; |
|||
} |
|||
|
|||
private Object findEntity(TenantId tenantId, EntityId entityId) { |
|||
if (entityId == null) { |
|||
return null; |
|||
} |
|||
try { |
|||
return entityDaoRegistry.getDao(entityId.getEntityType()).findById(tenantId, entityId.getId()); |
|||
} catch (IllegalArgumentException e) { |
|||
log.warn("[{}] Unsupported entity type of {}", tenantId, entityId); |
|||
return null; |
|||
} |
|||
} |
|||
|
|||
} |
|||
@ -0,0 +1,77 @@ |
|||
// SPDX-FileCopyrightText: Copyright The ThingsBoard Authors
|
|||
// SPDX-License-Identifier: Apache-2.0
|
|||
package org.thingsboard.server.service.edge; |
|||
|
|||
import com.google.protobuf.Descriptors.FieldDescriptor; |
|||
import com.google.protobuf.Message; |
|||
|
|||
import java.util.Collection; |
|||
import java.util.List; |
|||
import java.util.Map; |
|||
import java.util.StringJoiner; |
|||
import java.util.UUID; |
|||
import java.util.stream.Collectors; |
|||
|
|||
/** |
|||
* Describes edge protobuf messages without their payloads, so they can be logged or put into notifications |
|||
* without exposing entity JSON, credentials, tokens or secrets. |
|||
*/ |
|||
public final class EdgeMsgSummaryUtils { |
|||
|
|||
private static final String MSB = "MSB"; |
|||
private static final String LSB = "LSB"; |
|||
|
|||
private EdgeMsgSummaryUtils() { |
|||
} |
|||
|
|||
// e.g. DownlinkMsg[downlinkMsgId=12, deviceUpdateMsg x2, deviceCredentialsUpdateMsg x1]
|
|||
// e.g. DeviceUpdateMsg[msgType=ENTITY_UPDATED_RPC_MESSAGE, id=1d6f1e2c-...]
|
|||
public static String toSummary(Message msg) { |
|||
if (msg == null) { |
|||
return "null"; |
|||
} |
|||
Map<FieldDescriptor, Object> fields = msg.getAllFields(); |
|||
StringJoiner summary = new StringJoiner(", ", msg.getDescriptorForType().getName() + "[", "]"); |
|||
fields.forEach((field, value) -> { |
|||
String name = field.getName(); |
|||
if (field.isRepeated()) { |
|||
summary.add(name + " x" + ((List<?>) value).size()); |
|||
return; |
|||
} |
|||
switch (field.getJavaType()) { |
|||
case INT, LONG -> { |
|||
FieldDescriptor lsbField = name.endsWith(MSB) ? findPairField(msg, name, MSB, LSB) : null; |
|||
if (lsbField != null && value instanceof Long msb && msg.getField(lsbField) instanceof Long lsb) { |
|||
summary.add(name.substring(0, name.length() - MSB.length()) + "=" + new UUID(msb, lsb)); |
|||
} else if (!isPrintedWithPair(msg, fields, name)) { |
|||
summary.add(name + "=" + value); |
|||
} |
|||
} |
|||
case BOOLEAN, ENUM -> summary.add(name + "=" + value); |
|||
case MESSAGE -> summary.add(name); |
|||
// strings and bytes may hold entity JSON, credentials or secrets
|
|||
default -> { |
|||
} |
|||
} |
|||
}); |
|||
return summary.toString(); |
|||
} |
|||
|
|||
// LSB part of an id is printed together with its MSB part
|
|||
private static boolean isPrintedWithPair(Message msg, Map<FieldDescriptor, Object> fields, String name) { |
|||
if (!name.endsWith(LSB)) { |
|||
return false; |
|||
} |
|||
FieldDescriptor msbField = findPairField(msg, name, LSB, MSB); |
|||
return msbField != null && fields.containsKey(msbField); |
|||
} |
|||
|
|||
private static FieldDescriptor findPairField(Message msg, String name, String suffix, String pairSuffix) { |
|||
return msg.getDescriptorForType().findFieldByName(name.substring(0, name.length() - suffix.length()) + pairSuffix); |
|||
} |
|||
|
|||
public static String toSummary(Collection<? extends Message> msgs) { |
|||
return msgs.stream().map(EdgeMsgSummaryUtils::toSummary).collect(Collectors.joining(", ", "[", "]")); |
|||
} |
|||
|
|||
} |
|||
File diff suppressed because it is too large
@ -0,0 +1,119 @@ |
|||
// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc.
|
|||
// SPDX-License-Identifier: BUSL-1.1
|
|||
package org.thingsboard.server.service.iot_hub; |
|||
|
|||
import com.fasterxml.jackson.databind.JsonNode; |
|||
import com.fasterxml.jackson.databind.node.ObjectNode; |
|||
import lombok.RequiredArgsConstructor; |
|||
import org.springframework.stereotype.Component; |
|||
import org.thingsboard.server.common.data.EntityType; |
|||
import org.thingsboard.server.common.data.HasTenantId; |
|||
import org.thingsboard.server.common.data.HasVersion; |
|||
import org.thingsboard.server.common.data.id.ConverterId; |
|||
import org.thingsboard.server.common.data.id.DashboardId; |
|||
import org.thingsboard.server.common.data.id.DeviceProfileId; |
|||
import org.thingsboard.server.common.data.id.EntityId; |
|||
import org.thingsboard.server.common.data.id.IntegrationId; |
|||
import org.thingsboard.server.common.data.id.RuleChainId; |
|||
import org.thingsboard.server.common.data.id.TenantId; |
|||
import org.thingsboard.server.common.data.iot_hub.DeviceInstalledItemDescriptor; |
|||
import org.thingsboard.server.common.data.rule.RuleChain; |
|||
import org.thingsboard.server.dao.converter.ConverterService; |
|||
import org.thingsboard.server.dao.dashboard.DashboardService; |
|||
import org.thingsboard.server.dao.device.DeviceProfileService; |
|||
import org.thingsboard.server.dao.integration.IntegrationService; |
|||
import org.thingsboard.server.dao.rule.RuleChainService; |
|||
import org.thingsboard.server.queue.util.TbCoreComponent; |
|||
|
|||
import java.util.HashMap; |
|||
import java.util.Map; |
|||
import java.util.Set; |
|||
import java.util.UUID; |
|||
|
|||
/** |
|||
* The entities of a device package whose content an update overwrites, and their checksums. A device, a gateway |
|||
* and a gateway connector don't have one: an update never changes them. |
|||
*/ |
|||
@Component |
|||
@TbCoreComponent |
|||
@RequiredArgsConstructor |
|||
public class DevicePackageEntities { |
|||
|
|||
static final Set<EntityType> CHECKSUM_TYPES = Set.of(EntityType.DEVICE_PROFILE, EntityType.DASHBOARD, |
|||
EntityType.RULE_CHAIN, EntityType.CONVERTER, EntityType.INTEGRATION); |
|||
|
|||
private final DeviceProfileService deviceProfileService; |
|||
private final DashboardService dashboardService; |
|||
private final RuleChainService ruleChainService; |
|||
private final ConverterService converterService; |
|||
private final IntegrationService integrationService; |
|||
|
|||
/** The entity of the tenant, null when there is none, e.g. it was deleted. A rule chain comes with its metadata. */ |
|||
public Snapshot load(TenantId tenantId, EntityId entityId) { |
|||
Object entity = switch (entityId.getEntityType()) { |
|||
case DEVICE_PROFILE -> deviceProfileService.findDeviceProfileById(tenantId, (DeviceProfileId) entityId); |
|||
case DASHBOARD -> dashboardService.findDashboardById(tenantId, (DashboardId) entityId); |
|||
case RULE_CHAIN -> ruleChainService.findRuleChainById(tenantId, (RuleChainId) entityId); |
|||
case CONVERTER -> converterService.findConverterById(tenantId, (ConverterId) entityId); |
|||
case INTEGRATION -> integrationService.findIntegrationById(tenantId, (IntegrationId) entityId); |
|||
default -> throw new IllegalArgumentException("Unsupported entity type: " + entityId.getEntityType()); |
|||
}; |
|||
if (entity == null || !tenantId.equals(((HasTenantId) entity).getTenantId())) { |
|||
return null; |
|||
} |
|||
Object metadata = entity instanceof RuleChain ruleChain ? ruleChainService.loadRuleChainMetaData(tenantId, ruleChain.getId()) : null; |
|||
return new Snapshot(entity, metadata); |
|||
} |
|||
|
|||
public String checksum(TenantId tenantId, EntityId entityId) { |
|||
Snapshot snapshot = load(tenantId, entityId); |
|||
return snapshot != null ? snapshot.checksum() : null; |
|||
} |
|||
|
|||
/** |
|||
* Adds the checksum of each entity the install state names, so that an update can tell whether someone changed |
|||
* it since. Entities the user kept at install are left out: an update never overwrites them. |
|||
*/ |
|||
public void addChecksums(TenantId tenantId, DeviceInstalledItemDescriptor descriptor) { |
|||
if (descriptor.getInstallState() == null || descriptor.getCreatedEntityIds() == null) { |
|||
return; |
|||
} |
|||
Map<UUID, EntityId> createdIds = new HashMap<>(); |
|||
descriptor.getCreatedEntityIds().forEach(id -> createdIds.put(id.getId(), id)); |
|||
descriptor.getInstallState().forEach((stepName, state) -> { |
|||
EntityId entityId = entityIdOf(state, createdIds); |
|||
if (entityId != null && CHECKSUM_TYPES.contains(entityId.getEntityType()) && state.isObject()) { |
|||
String checksum = checksum(tenantId, entityId); |
|||
if (checksum != null) { |
|||
((ObjectNode) state).put("checksum", checksum); |
|||
} |
|||
} |
|||
}); |
|||
} |
|||
|
|||
/** The package entity an install-state step recorded, with its type from the ids the package created. */ |
|||
static EntityId entityIdOf(JsonNode state, Map<UUID, EntityId> createdIds) { |
|||
JsonNode id = state != null ? state.path("entityOutput").path("id") : null; |
|||
if (id == null || !id.isTextual() || "use-existing".equals(state.path("resolution").asText())) { |
|||
return null; |
|||
} |
|||
try { |
|||
return createdIds.get(UUID.fromString(id.asText())); |
|||
} catch (IllegalArgumentException e) { |
|||
return null; |
|||
} |
|||
} |
|||
|
|||
public record Snapshot(Object entity, Object metadata) { |
|||
|
|||
public Long version() { |
|||
return ((HasVersion) entity).getVersion(); |
|||
} |
|||
|
|||
public String checksum() { |
|||
return metadata != null ? EntityChecksum.of(entity, metadata) : EntityChecksum.of(entity); |
|||
} |
|||
|
|||
} |
|||
|
|||
} |
|||
@ -0,0 +1,27 @@ |
|||
// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc.
|
|||
// SPDX-License-Identifier: BUSL-1.1
|
|||
package org.thingsboard.server.service.iot_hub; |
|||
|
|||
import lombok.AllArgsConstructor; |
|||
import lombok.Data; |
|||
import lombok.NoArgsConstructor; |
|||
import org.thingsboard.server.common.data.id.EntityId; |
|||
|
|||
/** An entity of an installed device package as an update finds it, before it changes anything. */ |
|||
@Data |
|||
@NoArgsConstructor |
|||
@AllArgsConstructor |
|||
public class DevicePackageEntityState { |
|||
|
|||
private String stepName; |
|||
private EntityId entityId; |
|||
private boolean exists; |
|||
// Sent back with the update, which fails if someone changed the entity in between
|
|||
private Long version; |
|||
// Changed since the package installed or last updated it; null when the install state has no checksum of it
|
|||
// (installed before checksums were kept)
|
|||
private Boolean modified; |
|||
// Other installed device packages use it, so overwriting it affects them
|
|||
private boolean shared; |
|||
|
|||
} |
|||
@ -0,0 +1,19 @@ |
|||
// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc.
|
|||
// SPDX-License-Identifier: BUSL-1.1
|
|||
package org.thingsboard.server.service.iot_hub; |
|||
|
|||
import org.thingsboard.server.common.data.id.IotHubInstalledItemId; |
|||
import org.thingsboard.server.service.security.model.SecurityUser; |
|||
|
|||
import java.util.List; |
|||
|
|||
/** Updates an installed device package to another version of its item. */ |
|||
public interface DevicePackageUpdateService { |
|||
|
|||
/** The package's entities as they are now: whether they still exist, changed since, or are shared. */ |
|||
List<DevicePackageEntityState> check(SecurityUser user, IotHubInstalledItemId installedItemId); |
|||
|
|||
/** Applies the update in one transaction, together with the new version of the installed item, or nothing. */ |
|||
DeviceUpdateResult apply(SecurityUser user, IotHubInstalledItemId installedItemId, DeviceUpdateRequest request); |
|||
|
|||
} |
|||
@ -0,0 +1,80 @@ |
|||
// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc.
|
|||
// SPDX-License-Identifier: BUSL-1.1
|
|||
package org.thingsboard.server.service.iot_hub; |
|||
|
|||
import com.fasterxml.jackson.databind.JsonNode; |
|||
import lombok.Data; |
|||
|
|||
import java.util.List; |
|||
import java.util.Map; |
|||
import java.util.UUID; |
|||
|
|||
/** |
|||
* The update of an installed device package as the install wizard planned it: the entity of each install step |
|||
* of the new version, already resolved from its template, and what to do with it. The server applies all of it |
|||
* in one transaction, together with the new version of the installed item, or nothing. |
|||
*/ |
|||
@Data |
|||
public class DeviceUpdateRequest { |
|||
|
|||
private String versionId; |
|||
// The version installed when the wizard planned the update; the update fails if the package changed since
|
|||
private UUID fromVersionId; |
|||
// The install method of the new version's steps; the installed one when not set
|
|||
private String selectedInstallMethod; |
|||
// The form values of the install state, by step: the server adds the entities to it
|
|||
private Map<String, JsonNode> installState; |
|||
private List<Step> steps; |
|||
|
|||
public enum Action { |
|||
// Taken as it is: the new version doesn't change it, or the user kept an entity they had
|
|||
KEEP, |
|||
// Takes the entity from the step
|
|||
OVERWRITE, |
|||
// A new entity: new in this version, deleted since install, or a copy next to one with the same name
|
|||
CREATE |
|||
} |
|||
|
|||
@Data |
|||
public static class Step { |
|||
private String name; |
|||
// The package step's stable id, so that a next version can rename the step. It is also the step's install state
|
|||
// key when set, which the default converter update relies on to write the state back under the stored key
|
|||
private String id; |
|||
// InstallStepType of the package: DEVICE_PROFILE, DEVICE, GATEWAY, GATEWAY_CONNECTOR, DASHBOARD, RULE_CHAIN,
|
|||
// UPLINK_CONVERTER, DOWNLINK_CONVERTER, INTEGRATION
|
|||
private String type; |
|||
private Action action; |
|||
// KEEP and OVERWRITE: the entity
|
|||
private UUID entityId; |
|||
// OVERWRITE: the version the user reviewed; a different one means someone changed the entity since
|
|||
private Long expectedVersion; |
|||
// The user confirmed overwriting an entity of another package or one they didn't install with this package
|
|||
private boolean confirmed; |
|||
// OVERWRITE and CREATE: the entity resolved from the template. ${<alias>.<property>} of an entity this
|
|||
// update creates is left for the server, which knows its id only once it is created.
|
|||
private JsonNode entity; |
|||
// DEVICE and GATEWAY: the credentials template, if any
|
|||
private JsonNode credentials; |
|||
// OVERWRITE and CREATE: the attributes of the saved entity, written after the transaction. Like the entity,
|
|||
// they may keep ${<alias>.<property>} of an entity this update creates.
|
|||
private JsonNode serverAttributes; |
|||
private JsonNode sharedAttributes; |
|||
// The resolution the install state records for it
|
|||
private String resolution; |
|||
// INTEGRATION: the step's metadata entries, which the package's converter reads. A KEEP merges them into the
|
|||
// integration, e.g. one the package took as it was; null removes an entry
|
|||
private JsonNode metadata; |
|||
// UPLINK_CONVERTER: the step takes ThingsBoard's default converter, which the install state records for the update check
|
|||
private boolean defaultConverter; |
|||
|
|||
/** |
|||
* The key of the step's install state: its id, or else its type and name, so that two steps of an install |
|||
* method never share it. The install wizard keys the steps of an install the same way. |
|||
*/ |
|||
public String stateKey() { |
|||
return id != null ? id : type + ":" + name; |
|||
} |
|||
} |
|||
|
|||
} |
|||
@ -0,0 +1,37 @@ |
|||
// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc.
|
|||
// SPDX-License-Identifier: BUSL-1.1
|
|||
package org.thingsboard.server.service.iot_hub; |
|||
|
|||
import com.fasterxml.jackson.databind.node.ObjectNode; |
|||
import lombok.AllArgsConstructor; |
|||
import lombok.Data; |
|||
import lombok.NoArgsConstructor; |
|||
import org.thingsboard.server.common.data.iot_hub.DeviceInstalledItemDescriptor; |
|||
|
|||
import java.util.Map; |
|||
|
|||
/** |
|||
* Either everything was applied, or nothing was: on a failure the transaction was rolled back and failedStep |
|||
* is the install state key of the step that failed, if one did. |
|||
*/ |
|||
@Data |
|||
@NoArgsConstructor |
|||
@AllArgsConstructor |
|||
public class DeviceUpdateResult { |
|||
|
|||
private boolean success; |
|||
private String errorMessage; |
|||
private String failedStep; |
|||
private DeviceInstalledItemDescriptor descriptor; |
|||
// By install state key of the step: what the install instructions resolve, e.g. ${integration.httpEndpoint}, ${device.token}
|
|||
private Map<String, ObjectNode> outputs; |
|||
|
|||
public static DeviceUpdateResult success(DeviceInstalledItemDescriptor descriptor, Map<String, ObjectNode> outputs) { |
|||
return new DeviceUpdateResult(true, null, null, descriptor, outputs); |
|||
} |
|||
|
|||
public static DeviceUpdateResult error(String errorMessage, String failedStep) { |
|||
return new DeviceUpdateResult(false, errorMessage, failedStep, null, null); |
|||
} |
|||
|
|||
} |
|||
@ -0,0 +1,116 @@ |
|||
// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc.
|
|||
// SPDX-License-Identifier: BUSL-1.1
|
|||
package org.thingsboard.server.service.iot_hub; |
|||
|
|||
import com.fasterxml.jackson.databind.JsonNode; |
|||
import com.fasterxml.jackson.databind.node.ArrayNode; |
|||
import com.fasterxml.jackson.databind.node.ObjectNode; |
|||
import org.thingsboard.common.util.JacksonUtil; |
|||
import org.thingsboard.server.common.data.integration.Integration; |
|||
import org.thingsboard.server.common.data.rule.RuleChainMetaData; |
|||
import org.thingsboard.server.common.data.rule.RuleNode; |
|||
|
|||
import java.nio.charset.StandardCharsets; |
|||
import java.security.MessageDigest; |
|||
import java.security.NoSuchAlgorithmException; |
|||
import java.util.ArrayList; |
|||
import java.util.HexFormat; |
|||
import java.util.Iterator; |
|||
import java.util.List; |
|||
import java.util.Set; |
|||
|
|||
/** |
|||
* The checksum of an entity as the server stores it, kept in the install state of a device package. A different |
|||
* checksum later means someone changed the entity, even a widget resized. The fields the server sets, and the name, |
|||
* which an update keeps, don't count, nor do the debug settings, which the user turns on without changing what the |
|||
* entity does, and whether a profile is the default one, which changes when another profile becomes the default. |
|||
*/ |
|||
final class EntityChecksum { |
|||
|
|||
private static final Set<String> SKIPPED_KEYS = Set.of("id", "name", "title", "version", "createdTime", "tenantId", |
|||
"customerId", "ownerId", "assignedCustomers", "externalId", "ruleChainId", "resources", "debugMode", "debugSettings", "default"); |
|||
|
|||
private EntityChecksum() { |
|||
} |
|||
|
|||
/** A rule chain is checked with its metadata: pass both. */ |
|||
static String of(Object... parts) { |
|||
StringBuilder canonical = new StringBuilder(); |
|||
for (Object part : parts) { |
|||
JsonNode node = part instanceof RuleChainMetaData metadata ? ruleChainContent(metadata) : JacksonUtil.valueToTree(part); |
|||
if (part instanceof Integration && node.get("configuration") instanceof ObjectNode configuration) { |
|||
// Device packages on one integration add their entries to its metadata: that is no change to the integration
|
|||
configuration.remove("metadata"); |
|||
} |
|||
appendCanonical(canonical, node, true); |
|||
canonical.append('|'); |
|||
} |
|||
try { |
|||
byte[] hash = MessageDigest.getInstance("SHA-256").digest(canonical.toString().getBytes(StandardCharsets.UTF_8)); |
|||
return HexFormat.of().formatHex(hash); |
|||
} catch (NoSuchAlgorithmException e) { |
|||
throw new IllegalStateException(e); |
|||
} |
|||
} |
|||
|
|||
/** |
|||
* What a rule chain does, as the IoT Hub checksum of a rule chain item takes it: the nodes' type, name and |
|||
* configuration, and the connections. Node ids, layout and debug settings change without the user changing |
|||
* what the rule chain does, e.g. when it is saved again. |
|||
*/ |
|||
private static JsonNode ruleChainContent(RuleChainMetaData metadata) { |
|||
ObjectNode content = JacksonUtil.newObjectNode(); |
|||
ArrayNode nodes = content.putArray("nodes"); |
|||
if (metadata.getNodes() != null) { |
|||
for (RuleNode node : metadata.getNodes()) { |
|||
ObjectNode n = nodes.addObject(); |
|||
n.put("type", node.getType()); |
|||
n.put("name", node.getName()); |
|||
n.set("configuration", node.getConfiguration()); |
|||
n.put("singletonMode", node.isSingletonMode()); |
|||
n.put("queueName", node.getQueueName()); |
|||
} |
|||
} |
|||
content.set("connections", JacksonUtil.valueToTree(metadata.getConnections())); |
|||
content.set("ruleChainConnections", JacksonUtil.valueToTree(metadata.getRuleChainConnections())); |
|||
content.set("firstNodeIndex", JacksonUtil.valueToTree(metadata.getFirstNodeIndex())); |
|||
return content; |
|||
} |
|||
|
|||
/** JSON with the keys sorted, so the same entity always gives the same text. */ |
|||
private static void appendCanonical(StringBuilder out, JsonNode node, boolean topLevel) { |
|||
if (node == null || node.isNull() || node.isMissingNode()) { |
|||
out.append("null"); |
|||
} else if (node.isObject()) { |
|||
List<String> keys = new ArrayList<>(); |
|||
for (Iterator<String> it = node.fieldNames(); it.hasNext(); ) { |
|||
String key = it.next(); |
|||
if (!topLevel || !SKIPPED_KEYS.contains(key)) { |
|||
keys.add(key); |
|||
} |
|||
} |
|||
keys.sort(null); |
|||
out.append('{'); |
|||
for (int i = 0; i < keys.size(); i++) { |
|||
if (i > 0) { |
|||
out.append(','); |
|||
} |
|||
out.append(JacksonUtil.toString(keys.get(i))).append(':'); |
|||
appendCanonical(out, node.get(keys.get(i)), false); |
|||
} |
|||
out.append('}'); |
|||
} else if (node.isArray()) { |
|||
out.append('['); |
|||
for (int i = 0; i < node.size(); i++) { |
|||
if (i > 0) { |
|||
out.append(','); |
|||
} |
|||
appendCanonical(out, node.get(i), false); |
|||
} |
|||
out.append(']'); |
|||
} else { |
|||
out.append(node.toString()); |
|||
} |
|||
} |
|||
|
|||
} |
|||
@ -0,0 +1,32 @@ |
|||
// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc.
|
|||
// SPDX-License-Identifier: BUSL-1.1
|
|||
package org.thingsboard.server.service.iot_hub; |
|||
|
|||
import lombok.AllArgsConstructor; |
|||
import lombok.Data; |
|||
import lombok.NoArgsConstructor; |
|||
import org.thingsboard.server.common.data.id.EntityId; |
|||
|
|||
import java.util.List; |
|||
|
|||
/** What deleting an installed item keeps: what other installed items use too, and what the user had before it. */ |
|||
@Data |
|||
@NoArgsConstructor |
|||
@AllArgsConstructor |
|||
public class InstalledItemKeptEntities { |
|||
|
|||
private List<KeptEntity> entities; |
|||
// How many other installed items use at least one of the kept entities
|
|||
private int usedByItemsCount; |
|||
// How many of the kept entities the user had before and the package took as they were (use existing)
|
|||
private int usedExistingCount; |
|||
|
|||
@Data |
|||
@NoArgsConstructor |
|||
@AllArgsConstructor |
|||
public static class KeptEntity { |
|||
private EntityId entityId; |
|||
private String name; |
|||
} |
|||
|
|||
} |
|||
@ -0,0 +1,10 @@ |
|||
// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc.
|
|||
// SPDX-License-Identifier: BUSL-1.1
|
|||
package org.thingsboard.server.service.security.system; |
|||
|
|||
/** |
|||
* Base URL as returned by {@link SystemSecurityService#getBaseUrl}, and whether it was built from |
|||
* the request rather than taken from the Base URL in General settings. |
|||
*/ |
|||
public record ResolvedBaseUrl(String url, boolean fromRequest) { |
|||
} |
|||
Some files were not shown because too many files changed in this diff
Loading…
Reference in new issue