From 54284ed89d12c67ddb2a5c5f410c8993bb0e62b8 Mon Sep 17 00:00:00 2001 From: Nikita Mazurenko Date: Fri, 17 Jul 2026 15:30:13 +0300 Subject: [PATCH 01/16] Receive mail/SMS/notification uplink requests from edge --- .../service/edge/EdgeContextComponent.java | 4 + .../service/edge/rpc/EdgeGrpcSession.java | 74 +++++++- .../service/edge/rpc/EdgeSyncCursor.java | 5 +- .../settings/AdminSettingsEdgeProcessor.java | 89 ++++++++++ .../rpc/sync/DefaultEdgeRequestsService.java | 168 ++++++++++++++++++ .../edge/rpc/sync/EdgeRequestsService.java | 9 + .../server/service/mail/EdgeMailRequest.java | 80 +++++++++ .../notification/EdgeNotificationRequest.java | 76 ++++++++ .../server/service/sms/EdgeSmsRequest.java | 51 ++++++ .../server/controller/EdgeControllerTest.java | 20 --- .../server/edge/AbstractEdgeTest.java | 8 +- .../server/edge/AdminSettingsEdgeTest.java | 79 -------- .../server/edge/SendEmailEdgeTest.java | 99 +++++++++++ .../server/edge/SendNotificationEdgeTest.java | 134 ++++++++++++++ .../thingsboard/server/edge/SmsEdgeTest.java | 94 ++++++++++ common/edge-api/src/main/proto/edge.proto | 21 +++ 16 files changed, 904 insertions(+), 107 deletions(-) create mode 100644 application/src/main/java/org/thingsboard/server/service/mail/EdgeMailRequest.java create mode 100644 application/src/main/java/org/thingsboard/server/service/notification/EdgeNotificationRequest.java create mode 100644 application/src/main/java/org/thingsboard/server/service/sms/EdgeSmsRequest.java delete mode 100644 application/src/test/java/org/thingsboard/server/edge/AdminSettingsEdgeTest.java create mode 100644 application/src/test/java/org/thingsboard/server/edge/SendEmailEdgeTest.java create mode 100644 application/src/test/java/org/thingsboard/server/edge/SendNotificationEdgeTest.java create mode 100644 application/src/test/java/org/thingsboard/server/edge/SmsEdgeTest.java diff --git a/application/src/main/java/org/thingsboard/server/service/edge/EdgeContextComponent.java b/application/src/main/java/org/thingsboard/server/service/edge/EdgeContextComponent.java index fbb3591bb5..804f8b8567 100644 --- a/application/src/main/java/org/thingsboard/server/service/edge/EdgeContextComponent.java +++ b/application/src/main/java/org/thingsboard/server/service/edge/EdgeContextComponent.java @@ -72,6 +72,7 @@ import org.thingsboard.server.service.edge.rpc.processor.relation.RelationEdgePr import org.thingsboard.server.service.edge.rpc.processor.resource.ResourceEdgeProcessor; import org.thingsboard.server.service.edge.rpc.processor.rule.RuleChainEdgeProcessor; import org.thingsboard.server.service.edge.rpc.processor.rule.RuleChainMetadataEdgeProcessor; +import org.thingsboard.server.service.edge.rpc.processor.settings.AdminSettingsEdgeProcessor; import org.thingsboard.server.service.edge.rpc.processor.telemetry.TelemetryEdgeProcessor; import org.thingsboard.server.service.edge.rpc.sync.EdgeRequestsService; import org.thingsboard.server.service.executors.GrpcCallbackExecutorService; @@ -205,6 +206,9 @@ public class EdgeContextComponent { // processors + @Autowired + private AdminSettingsEdgeProcessor adminSettingsProcessor; + @Autowired private AlarmProcessor alarmProcessor; diff --git a/application/src/main/java/org/thingsboard/server/service/edge/rpc/EdgeGrpcSession.java b/application/src/main/java/org/thingsboard/server/service/edge/rpc/EdgeGrpcSession.java index fb420d080a..ad8550cddb 100644 --- a/application/src/main/java/org/thingsboard/server/service/edge/rpc/EdgeGrpcSession.java +++ b/application/src/main/java/org/thingsboard/server/service/edge/rpc/EdgeGrpcSession.java @@ -37,6 +37,7 @@ import org.thingsboard.server.common.data.id.TenantId; import org.thingsboard.server.common.data.kv.AttributeKvEntry; import org.thingsboard.server.common.data.kv.AttributesSaveResult; import org.thingsboard.server.common.data.kv.BaseAttributeKvEntry; +import org.thingsboard.server.common.data.kv.BooleanDataEntry; import org.thingsboard.server.common.data.kv.LongDataEntry; import org.thingsboard.server.common.data.kv.StringDataEntry; import org.thingsboard.server.common.data.limit.LimitedApi; @@ -77,6 +78,9 @@ import org.thingsboard.server.gen.edge.v1.RequestMsgType; import org.thingsboard.server.gen.edge.v1.ResourceUpdateMsg; import org.thingsboard.server.gen.edge.v1.ResponseMsg; import org.thingsboard.server.gen.edge.v1.RuleChainMetadataRequestMsg; +import org.thingsboard.server.gen.edge.v1.SendEmailUplinkMsg; +import org.thingsboard.server.gen.edge.v1.SendNotificationUplinkMsg; +import org.thingsboard.server.gen.edge.v1.SendSmsUplinkMsg; import org.thingsboard.server.gen.edge.v1.RuleChainMetadataUpdateMsg; import org.thingsboard.server.gen.edge.v1.RuleChainUpdateMsg; import org.thingsboard.server.gen.edge.v1.SyncCompletedMsg; @@ -109,6 +113,7 @@ public abstract class EdgeGrpcSession implements Closeable { private static final String QUEUE_START_TS_ATTR_KEY = "queueStartTs"; private static final String QUEUE_START_SEQ_ID_ATTR_KEY = "queueStartSeqId"; + private static final String ADMIN_SETTINGS_CLEANUP_COMPLETED_ATTR_KEY = "adminSettingsCleanupCompleted"; private static final int MAX_DOWNLINK_ATTEMPTS = 3; private static final String RATE_LIMIT_REACHED = "Rate limit reached"; @@ -249,12 +254,64 @@ public abstract class EdgeGrpcSession implements Closeable { log.info("[{}][{}][{}] Staring edge sync process", tenantId, edge.getId(), sessionId); syncInProgress = true; interruptGeneralProcessingOnSync(); - doSync(new EdgeSyncCursor(ctx, edge, fullSync)); + sendOneTimeAdminSettingsCleanupIfNeeded(() -> doSync(new EdgeSyncCursor(ctx, edge, fullSync))); } else { log.info("[{}][{}][{}] Sync is already started, skipping starting it now", tenantId, edge.getId(), sessionId); } } + private void sendOneTimeAdminSettingsCleanupIfNeeded(Runnable continuation) { + if (!EdgeVersionUtils.isEdgeVersionOlderThan(edgeVersion, EdgeVersion.V_4_2_2_4)) { + continuation.run(); + return; + } + try { + ListenableFuture> isCleanupCompletedAttrFuture = ctx.getAttributesService() + .find(tenantId, edge.getId(), AttributeScope.SERVER_SCOPE, ADMIN_SETTINGS_CLEANUP_COMPLETED_ATTR_KEY); + + ListenableFuture cleanupFuture = Futures.transformAsync( + isCleanupCompletedAttrFuture, + attr -> { + boolean alreadyCompleted = attr.isPresent() && attr.flatMap(AttributeKvEntry::getBooleanValue).orElse(false); + if (alreadyCompleted) { + return Futures.immediateFuture(false); + } + List cleanupMsgs = ctx.getAdminSettingsProcessor().convertAdminSettingsCleanupToDownlinks(edge); + if (cleanupMsgs.isEmpty()) { + return Futures.immediateFuture(true); + } + // send the cleanup pack; mark completed only if it was not interrupted, so it retries on next sync otherwise + return Futures.transform(sendDownlinkMsgsPack(cleanupMsgs), + isInterrupted -> !Boolean.TRUE.equals(isInterrupted), ctx.getGrpcCallbackExecutorService()); + }, ctx.getGrpcCallbackExecutorService()); + + Futures.addCallback(cleanupFuture, new FutureCallback<>() { + @Override + public void onSuccess(@Nullable Boolean markCompleted) { + if (Boolean.TRUE.equals(markCompleted)) { + markAdminSettingsCleanupCompleted(); + } + continuation.run(); + } + + @Override + public void onFailure(Throwable t) { + log.error("[{}][{}] Failed to run one-time admin settings cleanup for edge", tenantId, edge.getId(), t); + continuation.run(); + } + }, ctx.getGrpcCallbackExecutorService()); + } catch (Exception e) { + log.error("[{}][{}] Failed to start admin settings cleanup", tenantId, edge.getId(), e); + continuation.run(); + } + } + + private void markAdminSettingsCleanupCompleted() { + AttributeKvEntry attributeKvEntry = new BaseAttributeKvEntry( + new BooleanDataEntry(ADMIN_SETTINGS_CLEANUP_COMPLETED_ATTR_KEY, true), System.currentTimeMillis()); + ctx.getAttributesService().save(tenantId, edge.getId(), AttributeScope.SERVER_SCOPE, attributeKvEntry); + } + private void doSync(EdgeSyncCursor cursor) { if (cursor.hasNext()) { EdgeEventFetcher next = cursor.getNext(); @@ -918,6 +975,21 @@ public abstract class EdgeGrpcSession implements Closeable { result.add(ctx.getDeviceProcessor().processDeviceRpcCallFromEdge(edge.getTenantId(), edge, deviceRpcCallMsg)); } } + if (uplinkMsg.getSendEmailUplinkMsgCount() > 0) { + for (SendEmailUplinkMsg sendEmailUplinkMsg : uplinkMsg.getSendEmailUplinkMsgList()) { + result.add(ctx.getEdgeRequestsService().processSendEmailMsg(edge.getTenantId(), edge, sendEmailUplinkMsg)); + } + } + if (uplinkMsg.getSendSmsUplinkMsgCount() > 0) { + for (SendSmsUplinkMsg sendSmsUplinkMsg : uplinkMsg.getSendSmsUplinkMsgList()) { + result.add(ctx.getEdgeRequestsService().processSendSmsMsg(edge.getTenantId(), edge, sendSmsUplinkMsg)); + } + } + if (uplinkMsg.getSendNotificationUplinkMsgCount() > 0) { + for (SendNotificationUplinkMsg sendNotificationUplinkMsg : uplinkMsg.getSendNotificationUplinkMsgList()) { + result.add(ctx.getEdgeRequestsService().processSendNotificationMsg(edge.getTenantId(), edge, sendNotificationUplinkMsg)); + } + } if (uplinkMsg.getWidgetBundleTypesRequestMsgCount() > 0) { for (WidgetBundleTypesRequestMsg widgetBundleTypesRequestMsg : uplinkMsg.getWidgetBundleTypesRequestMsgList()) { result.add(ctx.getEdgeRequestsService().processWidgetBundleTypesRequestMsg(edge.getTenantId(), edge, widgetBundleTypesRequestMsg)); diff --git a/application/src/main/java/org/thingsboard/server/service/edge/rpc/EdgeSyncCursor.java b/application/src/main/java/org/thingsboard/server/service/edge/rpc/EdgeSyncCursor.java index ce175957f6..8e84357721 100644 --- a/application/src/main/java/org/thingsboard/server/service/edge/rpc/EdgeSyncCursor.java +++ b/application/src/main/java/org/thingsboard/server/service/edge/rpc/EdgeSyncCursor.java @@ -21,7 +21,6 @@ import org.thingsboard.server.common.data.edge.Edge; import org.thingsboard.server.common.data.id.EntityId; import org.thingsboard.server.common.data.id.TenantId; import org.thingsboard.server.service.edge.EdgeContextComponent; -import org.thingsboard.server.service.edge.rpc.fetch.AdminSettingsEdgeEventFetcher; import org.thingsboard.server.service.edge.rpc.fetch.AssetProfilesEdgeEventFetcher; import org.thingsboard.server.service.edge.rpc.fetch.AssetsEdgeEventFetcher; import org.thingsboard.server.service.edge.rpc.fetch.CustomerEdgeEventFetcher; @@ -63,8 +62,8 @@ public class EdgeSyncCursor { fetchers.add(new TenantEdgeEventFetcher(ctx.getTenantService())); fetchers.add(new QueuesEdgeEventFetcher(ctx.getQueueService())); fetchers.add(new RuleChainsEdgeEventFetcher(ctx.getRuleChainService())); - fetchers.add(new AdminSettingsEdgeEventFetcher(ctx.getAdminSettingsService(), TenantId.SYS_TENANT_ID)); - fetchers.add(new AdminSettingsEdgeEventFetcher(ctx.getAdminSettingsService(), edge.getTenantId())); + // Admin settings are not synced to the edge: 'general'/'connectivity' are system-scoped and the edge + // auto-generates its own on install, while 'mail'/'sms'/'notifications' are delegated to the cloud. fetchers.add(new TenantAdminUsersEdgeEventFetcher(ctx.getUserService())); } Customer publicCustomer = ctx.getCustomerService().findPublicCustomer(edge.getTenantId()); diff --git a/application/src/main/java/org/thingsboard/server/service/edge/rpc/processor/settings/AdminSettingsEdgeProcessor.java b/application/src/main/java/org/thingsboard/server/service/edge/rpc/processor/settings/AdminSettingsEdgeProcessor.java index 2e0a65f324..2bf55f7c1a 100644 --- a/application/src/main/java/org/thingsboard/server/service/edge/rpc/processor/settings/AdminSettingsEdgeProcessor.java +++ b/application/src/main/java/org/thingsboard/server/service/edge/rpc/processor/settings/AdminSettingsEdgeProcessor.java @@ -15,25 +15,53 @@ */ package org.thingsboard.server.service.edge.rpc.processor.settings; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.node.ObjectNode; import lombok.extern.slf4j.Slf4j; +import org.apache.commons.lang3.RandomStringUtils; +import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; import org.thingsboard.common.util.JacksonUtil; import org.thingsboard.server.common.data.AdminSettings; import org.thingsboard.server.common.data.EdgeUtils; +import org.thingsboard.server.common.data.edge.Edge; import org.thingsboard.server.common.data.edge.EdgeEvent; import org.thingsboard.server.common.data.edge.EdgeEventType; import org.thingsboard.server.common.data.id.AdminSettingsId; +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.common.data.security.model.JwtSettings; import org.thingsboard.server.gen.edge.v1.AdminSettingsUpdateMsg; import org.thingsboard.server.gen.edge.v1.DownlinkMsg; import org.thingsboard.server.gen.edge.v1.EdgeVersion; import org.thingsboard.server.queue.util.TbCoreComponent; import org.thingsboard.server.service.edge.rpc.processor.BaseEdgeProcessor; +import org.thingsboard.server.service.security.auth.jwt.settings.JwtSettingsService; + +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.Base64; +import java.util.HashSet; +import java.util.List; +import java.util.Set; @Slf4j @Component @TbCoreComponent public class AdminSettingsEdgeProcessor extends BaseEdgeProcessor { + private static final Set EDGE_SYNCED_SETTINGS_KEYS = Set.of("general", "connectivity"); + + private static final int DEFAULT_PAGE_SIZE = 1000; + + @Value("${security.jwt.tokenExpirationTime:9000}") + private Integer tokenExpirationTime; + @Value("${security.jwt.refreshTokenExpTime:604800}") + private Integer refreshTokenExpTime; + @Value("${security.jwt.tokenIssuer:thingsboard.io}") + private String tokenIssuer; + @Override public DownlinkMsg convertEdgeEventToDownlink(EdgeEvent edgeEvent, EdgeVersion edgeVersion) { AdminSettings adminSettings = null; @@ -47,6 +75,12 @@ public class AdminSettingsEdgeProcessor extends BaseEdgeProcessor { if (adminSettings == null) { return null; } + if (TenantId.SYS_TENANT_ID.equals(adminSettings.getTenantId()) + || !EDGE_SYNCED_SETTINGS_KEYS.contains(adminSettings.getKey())) { + log.trace("Skipping admin settings [{}] sync to edge [{}] - not in the edge allow-list", + adminSettings.getKey(), edgeEvent.getEdgeId()); + return null; + } AdminSettingsUpdateMsg msg = AdminSettingsUpdateMsg.newBuilder().setEntity(JacksonUtil.toString(adminSettings)).build(); return DownlinkMsg.newBuilder() .setDownlinkMsgId(EdgeUtils.nextPositiveInt()) @@ -54,6 +88,61 @@ public class AdminSettingsEdgeProcessor extends BaseEdgeProcessor { .build(); } + public List convertAdminSettingsCleanupToDownlinks(Edge edge) { + List result = new ArrayList<>(); + Set cleanedKeys = new HashSet<>(); + + Set tenantScopes = Set.of(TenantId.SYS_TENANT_ID, edge.getTenantId()); + for (TenantId scope : tenantScopes) { + PageLink pageLink = new PageLink(DEFAULT_PAGE_SIZE); + PageData page; + do { + page = edgeCtx.getAdminSettingsService().findAllByTenantId(scope, pageLink); + for (AdminSettings adminSettings : page.getData()) { + String key = adminSettings.getKey(); + if (EDGE_SYNCED_SETTINGS_KEYS.contains(key) || !cleanedKeys.add(key)) { + continue; + } + result.add(buildAdminSettingsCleanupDownlink(key)); + } + pageLink = pageLink.nextPageLink(); + } while (page.hasNext()); + } + log.info("[{}][{}] Prepared {} one-time admin settings cleanup message(s): {}", + edge.getTenantId(), edge.getId(), result.size(), cleanedKeys); + return result; + } + + private DownlinkMsg buildAdminSettingsCleanupDownlink(String key) { + AdminSettings adminSettings = new AdminSettings(); + adminSettings.setTenantId(TenantId.SYS_TENANT_ID); + adminSettings.setKey(key); + adminSettings.setJsonValue(buildAdminSettingsCleanupValue(key)); + AdminSettingsUpdateMsg msg = AdminSettingsUpdateMsg.newBuilder().setEntity(JacksonUtil.toString(adminSettings)).build(); + return DownlinkMsg.newBuilder() + .setDownlinkMsgId(EdgeUtils.nextPositiveInt()) + .addAdminSettingsUpdateMsg(msg) + .build(); + } + + private JsonNode buildAdminSettingsCleanupValue(String key) { + if (JwtSettingsService.ADMIN_SETTINGS_JWT_KEY.equals(key)) { + return JacksonUtil.valueToTree(generateRandomJwtSettings()); + } + ObjectNode value = JacksonUtil.newObjectNode(); + if ("mail".equals(key)) { + value.put("password", ""); + value.put("refreshToken", ""); + } + return value; + } + + private JwtSettings generateRandomJwtSettings() { + String randomSigningKey = Base64.getEncoder().encodeToString( + RandomStringUtils.secure().nextAlphanumeric(64).getBytes(StandardCharsets.UTF_8)); + return new JwtSettings(tokenExpirationTime, refreshTokenExpTime, tokenIssuer, randomSigningKey); + } + @Override public EdgeEventType getEdgeEventType() { return EdgeEventType.ADMIN_SETTINGS; diff --git a/application/src/main/java/org/thingsboard/server/service/edge/rpc/sync/DefaultEdgeRequestsService.java b/application/src/main/java/org/thingsboard/server/service/edge/rpc/sync/DefaultEdgeRequestsService.java index 74de2132b4..823d3b6b9d 100644 --- a/application/src/main/java/org/thingsboard/server/service/edge/rpc/sync/DefaultEdgeRequestsService.java +++ b/application/src/main/java/org/thingsboard/server/service/edge/rpc/sync/DefaultEdgeRequestsService.java @@ -27,6 +27,10 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Lazy; import org.springframework.stereotype.Service; import org.thingsboard.common.util.JacksonUtil; +import org.thingsboard.rule.engine.api.MailService; +import org.thingsboard.rule.engine.api.SmsService; +import org.thingsboard.rule.engine.api.notification.FirebaseService; +import org.thingsboard.rule.engine.api.notification.SlackService; import org.thingsboard.server.common.data.AttributeScope; import org.thingsboard.server.common.data.EdgeUtils; import org.thingsboard.server.common.data.EntityType; @@ -46,6 +50,10 @@ import org.thingsboard.server.common.data.id.WidgetsBundleId; import org.thingsboard.server.common.data.kv.AttributeKvEntry; import org.thingsboard.server.common.data.kv.DataType; import org.thingsboard.server.common.data.kv.TsKvEntry; +import org.thingsboard.server.common.data.notification.NotificationDeliveryMethod; +import org.thingsboard.server.common.data.notification.settings.MobileAppNotificationDeliveryMethodConfig; +import org.thingsboard.server.common.data.notification.settings.NotificationSettings; +import org.thingsboard.server.common.data.notification.settings.SlackNotificationDeliveryMethodConfig; import org.thingsboard.server.common.data.relation.EntityRelation; import org.thingsboard.server.common.data.relation.EntityRelationsQuery; import org.thingsboard.server.common.data.relation.EntitySearchDirection; @@ -56,6 +64,7 @@ import org.thingsboard.server.common.data.widget.WidgetsBundle; import org.thingsboard.server.dao.attributes.AttributesService; import org.thingsboard.server.dao.cf.CalculatedFieldService; import org.thingsboard.server.dao.edge.EdgeEventService; +import org.thingsboard.server.dao.notification.NotificationSettingsService; import org.thingsboard.server.dao.relation.RelationService; import org.thingsboard.server.dao.timeseries.TimeseriesService; import org.thingsboard.server.dao.widget.WidgetTypeService; @@ -66,10 +75,16 @@ import org.thingsboard.server.gen.edge.v1.DeviceCredentialsRequestMsg; import org.thingsboard.server.gen.edge.v1.EntityViewsRequestMsg; import org.thingsboard.server.gen.edge.v1.RelationRequestMsg; import org.thingsboard.server.gen.edge.v1.RuleChainMetadataRequestMsg; +import org.thingsboard.server.gen.edge.v1.SendEmailUplinkMsg; +import org.thingsboard.server.gen.edge.v1.SendNotificationUplinkMsg; +import org.thingsboard.server.gen.edge.v1.SendSmsUplinkMsg; import org.thingsboard.server.gen.edge.v1.UserCredentialsRequestMsg; import org.thingsboard.server.gen.edge.v1.WidgetBundleTypesRequestMsg; import org.thingsboard.server.queue.util.TbCoreComponent; import org.thingsboard.server.service.entitiy.entityview.TbEntityViewService; +import org.thingsboard.server.service.mail.EdgeMailRequest; +import org.thingsboard.server.service.notification.EdgeNotificationRequest; +import org.thingsboard.server.service.sms.EdgeSmsRequest; import org.thingsboard.server.service.executors.DbCallbackExecutorService; import org.thingsboard.server.service.state.DefaultDeviceStateService; @@ -112,6 +127,21 @@ public class DefaultEdgeRequestsService implements EdgeRequestsService { @Autowired private DbCallbackExecutorService dbCallbackExecutorService; + @Autowired + private MailService mailService; + + @Autowired + private SmsService smsService; + + @Autowired + private SlackService slackService; + + @Autowired + private FirebaseService firebaseService; + + @Autowired + private NotificationSettingsService notificationSettingsService; + @Override public ListenableFuture processRuleChainMetadataRequestMsg(TenantId tenantId, Edge edge, RuleChainMetadataRequestMsg ruleChainMetadataRequestMsg) { log.trace("[{}] processRuleChainMetadataRequestMsg [{}][{}]", tenantId, edge.getName(), ruleChainMetadataRequestMsg); @@ -433,6 +463,144 @@ public class DefaultEdgeRequestsService implements EdgeRequestsService { return futureToSet; } + @Override + public ListenableFuture processSendEmailMsg(TenantId tenantId, Edge edge, SendEmailUplinkMsg sendEmailUplinkMsg) { + log.trace("[{}] processSendEmailMsg [{}]", tenantId, edge.getName()); + dbCallbackExecutorService.submit(() -> { + try { + sendEmailForEdge(tenantId, sendEmailUplinkMsg); + } catch (Exception e) { + log.warn("[{}] Failed to send email requested by edge [{}]", tenantId, edge.getName(), e); + } + return null; + }); + return Futures.immediateFuture(null); + } + + private void sendEmailForEdge(TenantId tenantId, SendEmailUplinkMsg sendEmailUplinkMsg) throws Exception { + EdgeMailRequest request = JacksonUtil.fromString(sendEmailUplinkMsg.getRequest(), EdgeMailRequest.class); + if (request == null || request.getMethod() == null) { + log.warn("[{}] Received empty send email request from edge", tenantId); + return; + } + switch (request.getMethod()) { + case SEND_BASIC -> + mailService.sendEmail(tenantId, request.getTo(), request.getSubject(), request.getMessage()); + case SEND_TB_EMAIL -> + mailService.send(tenantId, null, request.getTbEmail()); + case ACTIVATION -> + mailService.sendActivationEmail(request.getActivationLink(), request.getTtlMs(), request.getTo()); + case ACCOUNT_ACTIVATED -> + mailService.sendAccountActivatedEmail(request.getLoginLink(), request.getTo()); + case RESET_PASSWORD -> + mailService.sendResetPasswordEmail(request.getPasswordResetLink(), request.getTtlMs(), request.getTo()); + case PASSWORD_WAS_RESET -> + mailService.sendPasswordWasResetEmail(request.getLoginLink(), request.getTo()); + case TWO_FA -> + mailService.sendTwoFaVerificationEmail(request.getTo(), request.getVerificationCode(), request.getExpirationTimeSeconds()); + case ACCOUNT_LOCKOUT -> + mailService.sendAccountLockoutEmail(request.getLockoutEmail(), request.getTo(), request.getMaxFailedLoginAttempts()); + case API_USAGE_STATE -> + mailService.sendApiFeatureStateEmail(request.getApiFeature(), request.getStateValue(), request.getTo(), request.getRecordState()); + case TEST_MAIL -> + mailService.sendTestMail(request.getTestConfig(), request.getTo()); + } + } + + @Override + public ListenableFuture processSendSmsMsg(TenantId tenantId, Edge edge, SendSmsUplinkMsg sendSmsUplinkMsg) { + log.trace("[{}] processSendSmsMsg [{}]", tenantId, edge.getName()); + dbCallbackExecutorService.submit(() -> { + try { + sendSmsForEdge(tenantId, sendSmsUplinkMsg); + } catch (Exception e) { + log.warn("[{}] Failed to send sms requested by edge [{}]", tenantId, edge.getName(), e); + } + return null; + }); + return Futures.immediateFuture(null); + } + + private void sendSmsForEdge(TenantId tenantId, SendSmsUplinkMsg sendSmsUplinkMsg) throws Exception { + EdgeSmsRequest request = JacksonUtil.fromString(sendSmsUplinkMsg.getRequest(), EdgeSmsRequest.class); + if (request == null || request.getMethod() == null) { + log.warn("[{}] Received empty send sms request from edge", tenantId); + return; + } + switch (request.getMethod()) { + case SEND_SMS -> + smsService.sendSms(tenantId, null, request.getNumbers(), request.getMessage()); + case SEND_TEST_SMS -> + smsService.sendTestSms(request.getTestSmsRequest()); + } + } + + @Override + public ListenableFuture processSendNotificationMsg(TenantId tenantId, Edge edge, SendNotificationUplinkMsg sendNotificationUplinkMsg) { + log.trace("[{}] processSendNotificationMsg [{}]", tenantId, edge.getName()); + dbCallbackExecutorService.submit(() -> { + try { + sendNotificationForEdge(tenantId, sendNotificationUplinkMsg); + } catch (Exception e) { + log.warn("[{}] Failed to send notification requested by edge [{}]", tenantId, edge.getName(), e); + } + return null; + }); + return Futures.immediateFuture(null); + } + + private void sendNotificationForEdge(TenantId tenantId, SendNotificationUplinkMsg sendNotificationUplinkMsg) throws Exception { + EdgeNotificationRequest request = JacksonUtil.fromString(sendNotificationUplinkMsg.getRequest(), EdgeNotificationRequest.class); + if (request == null || request.getMethod() == null) { + log.warn("[{}] Received empty send notification request from edge", tenantId); + return; + } + switch (request.getMethod()) { + case SEND_SLACK -> sendSlackForEdge(tenantId, request); + case SEND_MOBILE_PUSH -> sendMobilePushForEdge(tenantId, request); + } + } + + private void sendSlackForEdge(TenantId tenantId, EdgeNotificationRequest request) { + SlackNotificationDeliveryMethodConfig config = getSlackConfig(tenantId); + if (config == null) { + log.warn("[{}] Slack is not configured on the cloud; dropping edge-delegated notification", tenantId); + return; + } + slackService.sendMessage(tenantId, config.getBotToken(), request.getConversationId(), request.getMessage()); + } + + private void sendMobilePushForEdge(TenantId tenantId, EdgeNotificationRequest request) { + MobileAppNotificationDeliveryMethodConfig config = getMobileAppConfig(tenantId); + if (config == null || request.getFcmTokens() == null) { + log.warn("[{}] Mobile app notifications are not configured on the cloud; dropping edge-delegated push", tenantId); + return; + } + String credentials = config.getFirebaseServiceAccountCredentials(); + for (String fcmToken : request.getFcmTokens()) { + try { + firebaseService.sendMessage(tenantId, credentials, fcmToken, request.getSubject(), request.getBody(), request.getData(), request.getBadge()); + } catch (Exception e) { + log.warn("[{}] Failed to push edge-delegated notification to FCM token", tenantId, e); + } + } + } + + private SlackNotificationDeliveryMethodConfig getSlackConfig(TenantId tenantId) { + NotificationSettings settings = notificationSettingsService.findNotificationSettings(tenantId); + return (SlackNotificationDeliveryMethodConfig) settings.getDeliveryMethodsConfigs().get(NotificationDeliveryMethod.SLACK); + } + + private MobileAppNotificationDeliveryMethodConfig getMobileAppConfig(TenantId tenantId) { + NotificationSettings settings = notificationSettingsService.findNotificationSettings(tenantId); + var config = (MobileAppNotificationDeliveryMethodConfig) settings.getDeliveryMethodsConfigs().get(NotificationDeliveryMethod.MOBILE_APP); + if (config == null && !tenantId.isSysTenantId()) { + settings = notificationSettingsService.findNotificationSettings(TenantId.SYS_TENANT_ID); + config = (MobileAppNotificationDeliveryMethodConfig) settings.getDeliveryMethodsConfigs().get(NotificationDeliveryMethod.MOBILE_APP); + } + return config; + } + private ListenableFuture saveEdgeEvent(TenantId tenantId, EdgeId edgeId, EdgeEventType type, diff --git a/application/src/main/java/org/thingsboard/server/service/edge/rpc/sync/EdgeRequestsService.java b/application/src/main/java/org/thingsboard/server/service/edge/rpc/sync/EdgeRequestsService.java index 09599ba7a5..4f03d57112 100644 --- a/application/src/main/java/org/thingsboard/server/service/edge/rpc/sync/EdgeRequestsService.java +++ b/application/src/main/java/org/thingsboard/server/service/edge/rpc/sync/EdgeRequestsService.java @@ -24,6 +24,9 @@ import org.thingsboard.server.gen.edge.v1.DeviceCredentialsRequestMsg; import org.thingsboard.server.gen.edge.v1.EntityViewsRequestMsg; import org.thingsboard.server.gen.edge.v1.RelationRequestMsg; import org.thingsboard.server.gen.edge.v1.RuleChainMetadataRequestMsg; +import org.thingsboard.server.gen.edge.v1.SendEmailUplinkMsg; +import org.thingsboard.server.gen.edge.v1.SendNotificationUplinkMsg; +import org.thingsboard.server.gen.edge.v1.SendSmsUplinkMsg; import org.thingsboard.server.gen.edge.v1.UserCredentialsRequestMsg; import org.thingsboard.server.gen.edge.v1.WidgetBundleTypesRequestMsg; @@ -50,4 +53,10 @@ public interface EdgeRequestsService { @Deprecated(since = "3.9.1", forRemoval = true) ListenableFuture processEntityViewsRequestMsg(TenantId tenantId, Edge edge, EntityViewsRequestMsg entityViewsRequestMsg); + ListenableFuture processSendEmailMsg(TenantId tenantId, Edge edge, SendEmailUplinkMsg sendEmailUplinkMsg); + + ListenableFuture processSendSmsMsg(TenantId tenantId, Edge edge, SendSmsUplinkMsg sendSmsUplinkMsg); + + ListenableFuture processSendNotificationMsg(TenantId tenantId, Edge edge, SendNotificationUplinkMsg sendNotificationUplinkMsg); + } diff --git a/application/src/main/java/org/thingsboard/server/service/mail/EdgeMailRequest.java b/application/src/main/java/org/thingsboard/server/service/mail/EdgeMailRequest.java new file mode 100644 index 0000000000..733f824b0e --- /dev/null +++ b/application/src/main/java/org/thingsboard/server/service/mail/EdgeMailRequest.java @@ -0,0 +1,80 @@ +/** + * Copyright © 2016-2026 The Thingsboard Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.thingsboard.server.service.mail; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.databind.JsonNode; +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; +import lombok.NoArgsConstructor; +import org.thingsboard.rule.engine.api.TbEmail; +import org.thingsboard.server.common.data.ApiFeature; +import org.thingsboard.server.common.data.ApiUsageRecordState; +import org.thingsboard.server.common.data.ApiUsageStateValue; + +/** + * Describes a mail send that the Edge delegates to the Cloud. On the Edge, a mail send that depends + * on admin-configured (tenant/system) mail settings is packaged into this request and enqueued as a + * SEND_EMAIL cloud event. On the Cloud, {@code method} selects the matching {@code MailService} call + * so the Cloud resolves the config, renders the template and transmits via its own SMTP. + */ +@Data +@Builder +@NoArgsConstructor +@AllArgsConstructor +@JsonInclude(JsonInclude.Include.NON_NULL) +public class EdgeMailRequest { + + public enum MailMethod { + SEND_BASIC, // sendEmail(to, subject, message) + SEND_TB_EMAIL, // send(TbEmail) + ACTIVATION, // sendActivationEmail(activationLink, ttlMs, to) + ACCOUNT_ACTIVATED, // sendAccountActivatedEmail(loginLink, to) + RESET_PASSWORD, // sendResetPasswordEmail(passwordResetLink, ttlMs, to) + PASSWORD_WAS_RESET,// sendPasswordWasResetEmail(loginLink, to) + TWO_FA, // sendTwoFaVerificationEmail(to, verificationCode, expirationTimeSeconds) + ACCOUNT_LOCKOUT, // sendAccountLockoutEmail(lockoutEmail, to, maxFailedLoginAttempts) + API_USAGE_STATE, // sendApiFeatureStateEmail(apiFeature, stateValue, to, recordState) + TEST_MAIL // sendTestMail(config, to) + } + + private MailMethod method; + + private String to; + private String subject; + private String message; + + private TbEmail tbEmail; + + private String activationLink; + private String loginLink; + private String passwordResetLink; + private Long ttlMs; + + private String verificationCode; + private Integer expirationTimeSeconds; + + private String lockoutEmail; + private Integer maxFailedLoginAttempts; + + private ApiFeature apiFeature; + private ApiUsageStateValue stateValue; + private ApiUsageRecordState recordState; + + private JsonNode testConfig; + +} diff --git a/application/src/main/java/org/thingsboard/server/service/notification/EdgeNotificationRequest.java b/application/src/main/java/org/thingsboard/server/service/notification/EdgeNotificationRequest.java new file mode 100644 index 0000000000..b135c574e8 --- /dev/null +++ b/application/src/main/java/org/thingsboard/server/service/notification/EdgeNotificationRequest.java @@ -0,0 +1,76 @@ +/** + * Copyright © 2016-2026 The Thingsboard Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.thingsboard.server.service.notification; + +import com.fasterxml.jackson.annotation.JsonInclude; +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; +import lombok.NoArgsConstructor; + +import java.util.List; +import java.util.Map; +import java.util.Set; + +/** + * Describes a notification delivery that the Edge delegates to the Cloud, for channels whose credentials + * live only on the Cloud (they are stored in the {@code notifications} admin settings that no longer sync + * to the Edge). {@code method} selects the channel: + *
    + *
  • {@code SEND_SLACK} - the Cloud resolves the Slack bot token and posts {@code message} (plus any + * {@code files}) to {@code conversationId}. The whole send is delegated.
  • + *
  • {@code SEND_MOBILE_PUSH} - the Edge keeps the notification record, device-token lookup and unread + * count locally and delegates only the FCM push: the Cloud resolves the Firebase credentials and pushes + * the already-built payload ({@code subject}/{@code body}/{@code data}/{@code badge}) to every + * {@code fcmToken}.
  • + *
+ */ +@Data +@Builder +@NoArgsConstructor +@AllArgsConstructor +@JsonInclude(JsonInclude.Include.NON_NULL) +public class EdgeNotificationRequest { + + public enum NotificationMethod { + SEND_SLACK, + SEND_MOBILE_PUSH + } + + private NotificationMethod method; + + // SEND_SLACK + private String conversationId; + private String message; + private List files; + + // SEND_MOBILE_PUSH + private Set fcmTokens; + private String subject; + private String body; + private Map data; + private Integer badge; + + @Data + @NoArgsConstructor + @AllArgsConstructor + public static class SlackFileData { + private String name; + private String type; + private byte[] data; + } + +} diff --git a/application/src/main/java/org/thingsboard/server/service/sms/EdgeSmsRequest.java b/application/src/main/java/org/thingsboard/server/service/sms/EdgeSmsRequest.java new file mode 100644 index 0000000000..649b8a5a85 --- /dev/null +++ b/application/src/main/java/org/thingsboard/server/service/sms/EdgeSmsRequest.java @@ -0,0 +1,51 @@ +/** + * Copyright © 2016-2026 The Thingsboard Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.thingsboard.server.service.sms; + +import com.fasterxml.jackson.annotation.JsonInclude; +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; +import lombok.NoArgsConstructor; +import org.thingsboard.server.common.data.sms.config.TestSmsRequest; + +/** + * Describes an SMS send that the Edge delegates to the Cloud. On the Edge, a send that depends on + * admin-configured (tenant/system) SMS provider settings cannot be resolved locally, so the call is + * packaged into this request and enqueued as a SEND_SMS cloud event; on the Cloud, {@code method} + * selects the matching {@code SmsService} call so the Cloud resolves the config and transmits via its + * own provider. + */ +@Data +@Builder +@NoArgsConstructor +@AllArgsConstructor +@JsonInclude(JsonInclude.Include.NON_NULL) +public class EdgeSmsRequest { + + public enum SmsMethod { + SEND_SMS, // sendSms(customerId, numbersTo, message) + SEND_TEST_SMS // sendTestSms(testSmsRequest) + } + + private SmsMethod method; + + private String[] numbers; + private String message; + + private TestSmsRequest testSmsRequest; + +} diff --git a/application/src/test/java/org/thingsboard/server/controller/EdgeControllerTest.java b/application/src/test/java/org/thingsboard/server/controller/EdgeControllerTest.java index fc65d67949..d7bf5a9fb3 100644 --- a/application/src/test/java/org/thingsboard/server/controller/EdgeControllerTest.java +++ b/application/src/test/java/org/thingsboard/server/controller/EdgeControllerTest.java @@ -42,7 +42,6 @@ import org.springframework.test.context.TestPropertySource; import org.springframework.test.util.TestSocketUtils; import org.thingsboard.common.util.JacksonUtil; import org.thingsboard.common.util.ThingsBoardExecutors; -import org.thingsboard.server.common.data.AdminSettings; import org.thingsboard.server.common.data.AttributeScope; import org.thingsboard.server.common.data.Customer; import org.thingsboard.server.common.data.Device; @@ -79,7 +78,6 @@ import org.thingsboard.server.dao.exception.DataValidationException; import org.thingsboard.server.dao.model.ModelConstants; import org.thingsboard.server.dao.service.DaoSqlTest; import org.thingsboard.server.edge.imitator.EdgeImitator; -import org.thingsboard.server.gen.edge.v1.AdminSettingsUpdateMsg; import org.thingsboard.server.gen.edge.v1.AssetProfileUpdateMsg; import org.thingsboard.server.gen.edge.v1.AssetUpdateMsg; import org.thingsboard.server.gen.edge.v1.CustomerUpdateMsg; @@ -1012,10 +1010,6 @@ public class EdgeControllerTest extends AbstractControllerTest { Assert.assertTrue(popQueueMsg(edgeImitator.getDownlinkMsgsDeque(), UpdateMsgType.ENTITY_CREATED_RPC_MESSAGE, "Main")); Assert.assertTrue(popRuleChainMsg(edgeImitator.getDownlinkMsgsDeque(), UpdateMsgType.ENTITY_CREATED_RPC_MESSAGE, "Edge Root Rule Chain")); Assert.assertTrue(popRuleChainMetadataMsg(edgeImitator.getDownlinkMsgsDeque(), UpdateMsgType.ENTITY_CREATED_RPC_MESSAGE, getEdgeRootRuleChainId(edgeImitator))); - Assert.assertTrue(popAdminSettingsMsg(edgeImitator.getDownlinkMsgsDeque(), "general")); - Assert.assertTrue(popAdminSettingsMsg(edgeImitator.getDownlinkMsgsDeque(), "mail")); - Assert.assertTrue(popAdminSettingsMsg(edgeImitator.getDownlinkMsgsDeque(), "connectivity")); - Assert.assertTrue(popAdminSettingsMsg(edgeImitator.getDownlinkMsgsDeque(), "jwt")); Assert.assertTrue(popDeviceProfileMsg(edgeImitator.getDownlinkMsgsDeque(), UpdateMsgType.ENTITY_CREATED_RPC_MESSAGE, "default")); Assert.assertTrue(popDeviceProfileMsg(edgeImitator.getDownlinkMsgsDeque(), UpdateMsgType.ENTITY_CREATED_RPC_MESSAGE, "default")); Assert.assertTrue(popAssetProfileMsg(edgeImitator.getDownlinkMsgsDeque(), UpdateMsgType.ENTITY_CREATED_RPC_MESSAGE, "default")); @@ -1079,20 +1073,6 @@ public class EdgeControllerTest extends AbstractControllerTest { return false; } - private boolean popAdminSettingsMsg(Deque messages, String key) { - for (AbstractMessage message : messages) { - if (message instanceof AdminSettingsUpdateMsg adminSettingsUpdateMsg) { - AdminSettings adminSettings = JacksonUtil.fromString(adminSettingsUpdateMsg.getEntity(), AdminSettings.class, true); - Assert.assertNotNull(adminSettings); - if (key.equals(adminSettings.getKey())) { - messages.remove(message); - return true; - } - } - } - return false; - } - private boolean popDeviceProfileMsg(Deque messages, UpdateMsgType msgType, String name) { for (AbstractMessage message : messages) { if (message instanceof DeviceProfileUpdateMsg deviceProfileUpdateMsg) { diff --git a/application/src/test/java/org/thingsboard/server/edge/AbstractEdgeTest.java b/application/src/test/java/org/thingsboard/server/edge/AbstractEdgeTest.java index b46811daf5..9c0bb682b2 100644 --- a/application/src/test/java/org/thingsboard/server/edge/AbstractEdgeTest.java +++ b/application/src/test/java/org/thingsboard/server/edge/AbstractEdgeTest.java @@ -128,7 +128,7 @@ abstract public class AbstractEdgeTest extends AbstractControllerTest { registry.add("edges.rpc.port", () -> EDGE_PORT); } - public static final Integer CONNECT_MESSAGE_COUNT = 17; + public static final Integer CONNECT_MESSAGE_COUNT = 13; public static final Integer INSTALLATION_MESSAGE_COUNT = 8; public static final Integer SYNC_MESSAGE_COUNT = CONNECT_MESSAGE_COUNT + INSTALLATION_MESSAGE_COUNT; private static final String THERMOSTAT_DEVICE_PROFILE_NAME = "Thermostat"; @@ -279,9 +279,9 @@ abstract public class AbstractEdgeTest extends AbstractControllerTest { validateMsgsCnt(RuleChainMetadataUpdateMsg.class, 1); validateRuleChainMetadataUpdates(ruleChainUUID); - // 4 messages ('general', 'mail', 'connectivity', 'jwt') - validateMsgsCnt(AdminSettingsUpdateMsg.class, 4); - validateAdminSettings(4); + // No admin settings are synced to the edge: 'general'/'connectivity' are system-scoped and the edge + // auto-generates its own, while 'mail'/'sms'/'notifications' are delegated to the cloud. + validateMsgsCnt(AdminSettingsUpdateMsg.class, 0); // 4 messages // - 1 from default profile fetcher diff --git a/application/src/test/java/org/thingsboard/server/edge/AdminSettingsEdgeTest.java b/application/src/test/java/org/thingsboard/server/edge/AdminSettingsEdgeTest.java deleted file mode 100644 index 43350f7e8f..0000000000 --- a/application/src/test/java/org/thingsboard/server/edge/AdminSettingsEdgeTest.java +++ /dev/null @@ -1,79 +0,0 @@ -/** - * Copyright © 2016-2026 The Thingsboard Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.thingsboard.server.edge; - -import com.fasterxml.jackson.databind.node.ObjectNode; -import com.google.protobuf.AbstractMessage; -import org.junit.Assert; -import org.junit.Test; -import org.springframework.beans.factory.annotation.Autowired; -import org.thingsboard.common.util.JacksonUtil; -import org.thingsboard.server.common.data.AdminSettings; -import org.thingsboard.server.dao.service.DaoSqlTest; -import org.thingsboard.server.dao.settings.AdminSettingsService; -import org.thingsboard.server.gen.edge.v1.AdminSettingsUpdateMsg; - -@DaoSqlTest -public class AdminSettingsEdgeTest extends AbstractEdgeTest { - - @Autowired - private AdminSettingsService adminSettingsService; - - @Test - public void testAdminSettings() throws Exception { - loginSysAdmin(); - - // save - AdminSettings adminSettings = new AdminSettings(); - adminSettings.setKey("edgeTest"); - ObjectNode jsonValue = JacksonUtil.newObjectNode(); - jsonValue.put("key1", "value1"); - adminSettings.setJsonValue(jsonValue); - - edgeImitator.expectMessageAmount(1); - AdminSettings savedAdminSettings = doPost("/api/admin/settings", adminSettings, AdminSettings.class); - Assert.assertTrue(edgeImitator.waitForMessages()); - - AbstractMessage latestMessage = edgeImitator.getLatestMessage(); - Assert.assertTrue(latestMessage instanceof AdminSettingsUpdateMsg); - AdminSettingsUpdateMsg adminSettingsUpdateMsg = (AdminSettingsUpdateMsg) latestMessage; - AdminSettings adminSettingsMsg = JacksonUtil.fromString(adminSettingsUpdateMsg.getEntity(), AdminSettings.class, true); - Assert.assertNotNull(adminSettingsMsg); - Assert.assertEquals("edgeTest", adminSettingsMsg.getKey()); - Assert.assertEquals("value1", adminSettingsMsg.getJsonValue().get("key1").asText()); - - // update - ObjectNode updatedJsonValue = (ObjectNode) savedAdminSettings.getJsonValue(); - updatedJsonValue.put("key2", "value2"); - savedAdminSettings.setJsonValue(updatedJsonValue); - - edgeImitator.expectMessageAmount(1); - doPost("/api/admin/settings", savedAdminSettings, AdminSettings.class); - Assert.assertTrue(edgeImitator.waitForMessages()); - - latestMessage = edgeImitator.getLatestMessage(); - Assert.assertTrue(latestMessage instanceof AdminSettingsUpdateMsg); - adminSettingsUpdateMsg = (AdminSettingsUpdateMsg) latestMessage; - adminSettingsMsg = JacksonUtil.fromString(adminSettingsUpdateMsg.getEntity(), AdminSettings.class, true); - Assert.assertNotNull(adminSettingsMsg); - Assert.assertEquals("edgeTest", adminSettingsMsg.getKey()); - Assert.assertEquals("value1", adminSettingsMsg.getJsonValue().get("key1").asText()); - Assert.assertEquals("value2", adminSettingsMsg.getJsonValue().get("key2").asText()); - - adminSettingsService.deleteAdminSettingsByTenantIdAndKey(savedAdminSettings.getTenantId(), "edgeTest"); - } - -} diff --git a/application/src/test/java/org/thingsboard/server/edge/SendEmailEdgeTest.java b/application/src/test/java/org/thingsboard/server/edge/SendEmailEdgeTest.java new file mode 100644 index 0000000000..89e31c38c7 --- /dev/null +++ b/application/src/test/java/org/thingsboard/server/edge/SendEmailEdgeTest.java @@ -0,0 +1,99 @@ +/** + * Copyright © 2016-2026 The Thingsboard Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.thingsboard.server.edge; + +import org.junit.Assert; +import org.junit.Test; +import org.springframework.test.context.bean.override.mockito.MockitoBean; +import org.thingsboard.common.util.JacksonUtil; +import org.thingsboard.rule.engine.api.MailService; +import org.thingsboard.rule.engine.api.TbEmail; +import org.thingsboard.server.common.data.EdgeUtils; +import org.thingsboard.server.dao.service.DaoSqlTest; +import org.thingsboard.server.gen.edge.v1.SendEmailUplinkMsg; +import org.thingsboard.server.gen.edge.v1.UplinkMsg; +import org.thingsboard.server.service.mail.EdgeMailRequest; + +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.ArgumentMatchers.isNull; +import static org.mockito.Mockito.timeout; +import static org.mockito.Mockito.verify; + +/** + * Verifies the send-email uplink: when the Edge delegates a mail send, the Cloud receives the + * SendEmailUplinkMsg and invokes its MailService (which resolves the config, renders and transmits). Here + * the EdgeImitator plays the Edge and sends the uplink; the Cloud's MailService is mocked so we can assert + * the delegated call arrives with the expected arguments (the Cloud, not the Edge, uses the tenant id of + * the connected edge). + */ +@DaoSqlTest +public class SendEmailEdgeTest extends AbstractEdgeTest { + + @MockitoBean + private MailService mailService; + + @Test + public void testSendBasicEmailFromEdgeProcessedByCloud() throws Exception { + EdgeMailRequest request = EdgeMailRequest.builder() + .method(EdgeMailRequest.MailMethod.SEND_BASIC) + .to("recipient@thingsboard.io") + .subject("Edge test subject") + .message("Edge test body") + .build(); + + sendEmailUplink(request); + + verify(mailService, timeout(30000)) + .sendEmail(eq(tenantId), eq("recipient@thingsboard.io"), eq("Edge test subject"), eq("Edge test body")); + } + + @Test + public void testSendTbEmailFromEdgeProcessedByCloud() throws Exception { + TbEmail tbEmail = TbEmail.builder() + .from("noreply@thingsboard.io") + .to("recipient@thingsboard.io") + .subject("Rule chain email") + .body("Alarm!") + .html(false) + .build(); + EdgeMailRequest request = EdgeMailRequest.builder() + .method(EdgeMailRequest.MailMethod.SEND_TB_EMAIL) + .tbEmail(tbEmail) + .build(); + + sendEmailUplink(request); + + verify(mailService, timeout(30000)).send(eq(tenantId), isNull(), any(TbEmail.class)); + } + + private void sendEmailUplink(EdgeMailRequest request) throws Exception { + SendEmailUplinkMsg sendEmailUplinkMsg = SendEmailUplinkMsg.newBuilder() + .setTenantIdMSB(tenantId.getId().getMostSignificantBits()) + .setTenantIdLSB(tenantId.getId().getLeastSignificantBits()) + .setRequest(JacksonUtil.toString(request)) + .build(); + + UplinkMsg.Builder uplinkMsgBuilder = UplinkMsg.newBuilder(); + uplinkMsgBuilder.setUplinkMsgId(EdgeUtils.nextPositiveInt()); + uplinkMsgBuilder.addSendEmailUplinkMsg(sendEmailUplinkMsg); + + edgeImitator.expectResponsesAmount(1); + edgeImitator.sendUplinkMsg(uplinkMsgBuilder.build()); + Assert.assertTrue(edgeImitator.waitForResponses()); + } + +} diff --git a/application/src/test/java/org/thingsboard/server/edge/SendNotificationEdgeTest.java b/application/src/test/java/org/thingsboard/server/edge/SendNotificationEdgeTest.java new file mode 100644 index 0000000000..3c8802f07e --- /dev/null +++ b/application/src/test/java/org/thingsboard/server/edge/SendNotificationEdgeTest.java @@ -0,0 +1,134 @@ +/** + * Copyright © 2016-2026 The Thingsboard Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.thingsboard.server.edge; + +import org.junit.Assert; +import org.junit.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.test.context.bean.override.mockito.MockitoBean; +import org.thingsboard.common.util.JacksonUtil; +import org.thingsboard.rule.engine.api.notification.FirebaseService; +import org.thingsboard.rule.engine.api.notification.SlackService; +import org.thingsboard.server.common.data.EdgeUtils; +import org.thingsboard.server.common.data.id.TenantId; +import org.thingsboard.server.common.data.notification.NotificationDeliveryMethod; +import org.thingsboard.server.common.data.notification.settings.MobileAppNotificationDeliveryMethodConfig; +import org.thingsboard.server.common.data.notification.settings.NotificationDeliveryMethodConfig; +import org.thingsboard.server.common.data.notification.settings.NotificationSettings; +import org.thingsboard.server.common.data.notification.settings.SlackNotificationDeliveryMethodConfig; +import org.thingsboard.server.dao.notification.NotificationSettingsService; +import org.thingsboard.server.dao.service.DaoSqlTest; +import org.thingsboard.server.gen.edge.v1.SendNotificationUplinkMsg; +import org.thingsboard.server.gen.edge.v1.UplinkMsg; +import org.thingsboard.server.service.notification.EdgeNotificationRequest; + +import java.util.HashMap; +import java.util.Map; +import java.util.Set; + +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.timeout; +import static org.mockito.Mockito.verify; + +/** + * Verifies the send-notification uplink: when the Edge delegates a Slack or mobile-push notification, the + * Cloud receives the SendNotificationUplinkMsg, resolves the channel credentials from its own notification + * settings and delivers. The EdgeImitator plays the Edge and sends the uplink; the Cloud's SlackService and + * FirebaseService are mocked so we can assert the delegated call arrives with the expected arguments. + */ +@DaoSqlTest +public class SendNotificationEdgeTest extends AbstractEdgeTest { + + @MockitoBean + private SlackService slackService; + + @MockitoBean + private FirebaseService firebaseService; + + @Autowired + private NotificationSettingsService notificationSettingsService; + + private void prepareNotificationSettings() { + // Slack is configured at tenant level. + SlackNotificationDeliveryMethodConfig slack = new SlackNotificationDeliveryMethodConfig(); + slack.setBotToken("xoxb-edge-test-token"); + NotificationSettings tenantSettings = new NotificationSettings(); + Map tenantConfigs = new HashMap<>(); + tenantConfigs.put(NotificationDeliveryMethod.SLACK, slack); + tenantSettings.setDeliveryMethodsConfigs(tenantConfigs); + notificationSettingsService.saveNotificationSettings(tenantId, tenantSettings); + + // Mobile app credentials can only be configured at system level. + MobileAppNotificationDeliveryMethodConfig mobile = new MobileAppNotificationDeliveryMethodConfig(); + mobile.setFirebaseServiceAccountCredentials("{\"type\":\"service_account\"}"); + NotificationSettings systemSettings = new NotificationSettings(); + Map systemConfigs = new HashMap<>(); + systemConfigs.put(NotificationDeliveryMethod.MOBILE_APP, mobile); + systemSettings.setDeliveryMethodsConfigs(systemConfigs); + notificationSettingsService.saveNotificationSettings(TenantId.SYS_TENANT_ID, systemSettings); + } + + @Test + public void testSendSlackNotificationFromEdgeProcessedByCloud() throws Exception { + prepareNotificationSettings(); + EdgeNotificationRequest request = EdgeNotificationRequest.builder() + .method(EdgeNotificationRequest.NotificationMethod.SEND_SLACK) + .conversationId("C0123456789") + .message("Edge Slack notification") + .build(); + + sendNotificationUplink(request); + + verify(slackService, timeout(30000)) + .sendMessage(eq(tenantId), anyString(), eq("C0123456789"), eq("Edge Slack notification")); + } + + @Test + public void testSendMobilePushFromEdgeProcessedByCloud() throws Exception { + prepareNotificationSettings(); + EdgeNotificationRequest request = EdgeNotificationRequest.builder() + .method(EdgeNotificationRequest.NotificationMethod.SEND_MOBILE_PUSH) + .fcmTokens(Set.of("fcm-token-1")) + .subject("Edge subject") + .body("Edge body") + .badge(3) + .build(); + + sendNotificationUplink(request); + + verify(firebaseService, timeout(30000)) + .sendMessage(eq(tenantId), anyString(), eq("fcm-token-1"), eq("Edge subject"), eq("Edge body"), any(), eq(3)); + } + + private void sendNotificationUplink(EdgeNotificationRequest request) throws Exception { + SendNotificationUplinkMsg sendNotificationUplinkMsg = SendNotificationUplinkMsg.newBuilder() + .setTenantIdMSB(tenantId.getId().getMostSignificantBits()) + .setTenantIdLSB(tenantId.getId().getLeastSignificantBits()) + .setRequest(JacksonUtil.toString(request)) + .build(); + + UplinkMsg.Builder uplinkMsgBuilder = UplinkMsg.newBuilder(); + uplinkMsgBuilder.setUplinkMsgId(EdgeUtils.nextPositiveInt()); + uplinkMsgBuilder.addSendNotificationUplinkMsg(sendNotificationUplinkMsg); + + edgeImitator.expectResponsesAmount(1); + edgeImitator.sendUplinkMsg(uplinkMsgBuilder.build()); + Assert.assertTrue(edgeImitator.waitForResponses()); + } + +} diff --git a/application/src/test/java/org/thingsboard/server/edge/SmsEdgeTest.java b/application/src/test/java/org/thingsboard/server/edge/SmsEdgeTest.java new file mode 100644 index 0000000000..e8decbe7d2 --- /dev/null +++ b/application/src/test/java/org/thingsboard/server/edge/SmsEdgeTest.java @@ -0,0 +1,94 @@ +/** + * Copyright © 2016-2026 The Thingsboard Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.thingsboard.server.edge; + +import org.junit.Assert; +import org.junit.Test; +import org.springframework.test.context.bean.override.mockito.MockitoBean; +import org.thingsboard.common.util.JacksonUtil; +import org.thingsboard.rule.engine.api.SmsService; +import org.thingsboard.server.common.data.EdgeUtils; +import org.thingsboard.server.common.data.sms.config.TestSmsRequest; +import org.thingsboard.server.dao.service.DaoSqlTest; +import org.thingsboard.server.gen.edge.v1.SendSmsUplinkMsg; +import org.thingsboard.server.gen.edge.v1.UplinkMsg; +import org.thingsboard.server.service.sms.EdgeSmsRequest; + +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.ArgumentMatchers.isNull; +import static org.mockito.Mockito.timeout; +import static org.mockito.Mockito.verify; + +/** + * Verifies the send-sms uplink: when the Edge delegates an SMS send, the Cloud receives the + * SendSmsUplinkMsg and invokes its SmsService (which resolves the config and transmits). Here the + * EdgeImitator plays the Edge and sends the uplink; the Cloud's SmsService is mocked so we can assert the + * delegated call arrives with the expected arguments (the Cloud, not the Edge, uses the tenant id of the + * connected edge). + */ +@DaoSqlTest +public class SmsEdgeTest extends AbstractEdgeTest { + + @MockitoBean + private SmsService smsService; + + @Test + public void testSendSmsFromEdgeProcessedByCloud() throws Exception { + EdgeSmsRequest request = EdgeSmsRequest.builder() + .method(EdgeSmsRequest.SmsMethod.SEND_SMS) + .numbers(new String[]{"+15551234567"}) + .message("Edge test message") + .build(); + + sendSmsUplink(request); + + verify(smsService, timeout(30000)) + .sendSms(eq(tenantId), isNull(), any(String[].class), eq("Edge test message")); + } + + @Test + public void testSendTestSmsFromEdgeProcessedByCloud() throws Exception { + TestSmsRequest testSmsRequest = new TestSmsRequest(); + testSmsRequest.setNumberTo("+15551234567"); + testSmsRequest.setMessage("Test message"); + EdgeSmsRequest request = EdgeSmsRequest.builder() + .method(EdgeSmsRequest.SmsMethod.SEND_TEST_SMS) + .testSmsRequest(testSmsRequest) + .build(); + + sendSmsUplink(request); + + verify(smsService, timeout(30000)).sendTestSms(any(TestSmsRequest.class)); + } + + private void sendSmsUplink(EdgeSmsRequest request) throws Exception { + SendSmsUplinkMsg sendSmsUplinkMsg = SendSmsUplinkMsg.newBuilder() + .setTenantIdMSB(tenantId.getId().getMostSignificantBits()) + .setTenantIdLSB(tenantId.getId().getLeastSignificantBits()) + .setRequest(JacksonUtil.toString(request)) + .build(); + + UplinkMsg.Builder uplinkMsgBuilder = UplinkMsg.newBuilder(); + uplinkMsgBuilder.setUplinkMsgId(EdgeUtils.nextPositiveInt()); + uplinkMsgBuilder.addSendSmsUplinkMsg(sendSmsUplinkMsg); + + edgeImitator.expectResponsesAmount(1); + edgeImitator.sendUplinkMsg(uplinkMsgBuilder.build()); + Assert.assertTrue(edgeImitator.waitForResponses()); + } + +} diff --git a/common/edge-api/src/main/proto/edge.proto b/common/edge-api/src/main/proto/edge.proto index 376a4d8c5b..50a02da5d5 100644 --- a/common/edge-api/src/main/proto/edge.proto +++ b/common/edge-api/src/main/proto/edge.proto @@ -347,6 +347,24 @@ message CalculatedFieldRequestMsg { string entityType = 3; } +message SendEmailUplinkMsg { + int64 tenantIdMSB = 1; + int64 tenantIdLSB = 2; + string request = 3; +} + +message SendSmsUplinkMsg { + int64 tenantIdMSB = 1; + int64 tenantIdLSB = 2; + string request = 3; +} + +message SendNotificationUplinkMsg { + int64 tenantIdMSB = 1; + int64 tenantIdLSB = 2; + string request = 3; +} + // DEPRECATED. FOR REMOVAL message UserCredentialsRequestMsg { option deprecated = true; @@ -447,6 +465,9 @@ message UplinkMsg { repeated RuleChainMetadataUpdateMsg ruleChainMetadataUpdateMsg = 24; repeated CalculatedFieldUpdateMsg calculatedFieldUpdateMsg = 25; repeated CalculatedFieldRequestMsg calculatedFieldRequestMsg = 26; + repeated SendEmailUplinkMsg sendEmailUplinkMsg = 35; + repeated SendSmsUplinkMsg sendSmsUplinkMsg = 36; + repeated SendNotificationUplinkMsg sendNotificationUplinkMsg = 37; } message UplinkResponseMsg { From 3ca5273b0bef2ac0d648a195d898476c0930268f Mon Sep 17 00:00:00 2001 From: Nikita Mazurenko Date: Fri, 17 Jul 2026 15:30:13 +0300 Subject: [PATCH 02/16] Receive mail/SMS/notification uplink requests from edge --- .../service/edge/EdgeContextComponent.java | 4 + .../service/edge/rpc/EdgeGrpcSession.java | 73 +++++++- .../service/edge/rpc/EdgeSyncCursor.java | 5 +- .../settings/AdminSettingsEdgeProcessor.java | 89 ++++++++++ .../rpc/sync/DefaultEdgeRequestsService.java | 168 ++++++++++++++++++ .../edge/rpc/sync/EdgeRequestsService.java | 9 + .../server/service/mail/EdgeMailRequest.java | 80 +++++++++ .../notification/EdgeNotificationRequest.java | 76 ++++++++ .../server/service/sms/EdgeSmsRequest.java | 51 ++++++ .../server/controller/EdgeControllerTest.java | 20 --- .../server/edge/AbstractEdgeTest.java | 8 +- .../server/edge/AdminSettingsEdgeTest.java | 79 -------- .../server/edge/SendEmailEdgeTest.java | 99 +++++++++++ .../server/edge/SendNotificationEdgeTest.java | 134 ++++++++++++++ .../thingsboard/server/edge/SmsEdgeTest.java | 94 ++++++++++ common/edge-api/src/main/proto/edge.proto | 21 +++ 16 files changed, 903 insertions(+), 107 deletions(-) create mode 100644 application/src/main/java/org/thingsboard/server/service/mail/EdgeMailRequest.java create mode 100644 application/src/main/java/org/thingsboard/server/service/notification/EdgeNotificationRequest.java create mode 100644 application/src/main/java/org/thingsboard/server/service/sms/EdgeSmsRequest.java delete mode 100644 application/src/test/java/org/thingsboard/server/edge/AdminSettingsEdgeTest.java create mode 100644 application/src/test/java/org/thingsboard/server/edge/SendEmailEdgeTest.java create mode 100644 application/src/test/java/org/thingsboard/server/edge/SendNotificationEdgeTest.java create mode 100644 application/src/test/java/org/thingsboard/server/edge/SmsEdgeTest.java diff --git a/application/src/main/java/org/thingsboard/server/service/edge/EdgeContextComponent.java b/application/src/main/java/org/thingsboard/server/service/edge/EdgeContextComponent.java index c99261b249..15c81fff8d 100644 --- a/application/src/main/java/org/thingsboard/server/service/edge/EdgeContextComponent.java +++ b/application/src/main/java/org/thingsboard/server/service/edge/EdgeContextComponent.java @@ -76,6 +76,7 @@ import org.thingsboard.server.service.edge.rpc.processor.relation.RelationEdgePr import org.thingsboard.server.service.edge.rpc.processor.resource.ResourceEdgeProcessor; import org.thingsboard.server.service.edge.rpc.processor.rule.RuleChainEdgeProcessor; import org.thingsboard.server.service.edge.rpc.processor.rule.RuleChainMetadataEdgeProcessor; +import org.thingsboard.server.service.edge.rpc.processor.settings.AdminSettingsEdgeProcessor; import org.thingsboard.server.service.edge.rpc.processor.telemetry.TelemetryEdgeProcessor; import org.thingsboard.server.service.edge.rpc.processor.user.UserProcessor; import org.thingsboard.server.service.edge.rpc.sync.EdgeRequestsService; @@ -213,6 +214,9 @@ public class EdgeContextComponent { private Optional statsCounterService; // processors + @Autowired + private AdminSettingsEdgeProcessor adminSettingsProcessor; + @Autowired private AlarmProcessor alarmProcessor; diff --git a/application/src/main/java/org/thingsboard/server/service/edge/rpc/EdgeGrpcSession.java b/application/src/main/java/org/thingsboard/server/service/edge/rpc/EdgeGrpcSession.java index de4a92ae8c..950acead39 100644 --- a/application/src/main/java/org/thingsboard/server/service/edge/rpc/EdgeGrpcSession.java +++ b/application/src/main/java/org/thingsboard/server/service/edge/rpc/EdgeGrpcSession.java @@ -81,6 +81,9 @@ import org.thingsboard.server.gen.edge.v1.RequestMsgType; import org.thingsboard.server.gen.edge.v1.ResourceUpdateMsg; import org.thingsboard.server.gen.edge.v1.ResponseMsg; import org.thingsboard.server.gen.edge.v1.RuleChainMetadataRequestMsg; +import org.thingsboard.server.gen.edge.v1.SendEmailUplinkMsg; +import org.thingsboard.server.gen.edge.v1.SendNotificationUplinkMsg; +import org.thingsboard.server.gen.edge.v1.SendSmsUplinkMsg; import org.thingsboard.server.gen.edge.v1.RuleChainMetadataUpdateMsg; import org.thingsboard.server.gen.edge.v1.RuleChainUpdateMsg; import org.thingsboard.server.gen.edge.v1.SyncCompletedMsg; @@ -116,6 +119,7 @@ public abstract class EdgeGrpcSession implements Closeable { private static final String QUEUE_START_TS_ATTR_KEY = "queueStartTs"; private static final String QUEUE_START_SEQ_ID_ATTR_KEY = "queueStartSeqId"; + private static final String ADMIN_SETTINGS_CLEANUP_COMPLETED_ATTR_KEY = "adminSettingsCleanupCompleted"; private static final int MAX_DOWNLINK_ATTEMPTS = 3; private static final String RATE_LIMIT_REACHED = "Rate limit reached"; @@ -262,12 +266,64 @@ public abstract class EdgeGrpcSession implements Closeable { log.info("[{}][{}][{}] Staring edge sync process", tenantId, edge.getId(), sessionId); updateSyncInProgress(true); interruptGeneralProcessingOnSync(); - doSync(new EdgeSyncCursor(ctx, edge, fullSync)); + sendOneTimeAdminSettingsCleanupIfNeeded(() -> doSync(new EdgeSyncCursor(ctx, edge, fullSync))); } else { log.info("[{}][{}][{}] Sync is already started, skipping starting it now", tenantId, edge.getId(), sessionId); } } + private void sendOneTimeAdminSettingsCleanupIfNeeded(Runnable continuation) { + if (!EdgeVersionUtils.isEdgeVersionOlderThan(edgeVersion, EdgeVersion.V_4_3_1_4)) { + continuation.run(); + return; + } + try { + ListenableFuture> isCleanupCompletedAttrFuture = ctx.getAttributesService() + .find(tenantId, edge.getId(), AttributeScope.SERVER_SCOPE, ADMIN_SETTINGS_CLEANUP_COMPLETED_ATTR_KEY); + + ListenableFuture cleanupFuture = Futures.transformAsync( + isCleanupCompletedAttrFuture, + attr -> { + boolean alreadyCompleted = attr.isPresent() && attr.flatMap(AttributeKvEntry::getBooleanValue).orElse(false); + if (alreadyCompleted) { + return Futures.immediateFuture(false); + } + List cleanupMsgs = ctx.getAdminSettingsProcessor().convertAdminSettingsCleanupToDownlinks(edge); + if (cleanupMsgs.isEmpty()) { + return Futures.immediateFuture(true); + } + // send the cleanup pack; mark completed only if it was not interrupted, so it retries on next sync otherwise + return Futures.transform(sendDownlinkMsgsPack(cleanupMsgs), + isInterrupted -> !Boolean.TRUE.equals(isInterrupted), ctx.getGrpcCallbackExecutorService()); + }, ctx.getGrpcCallbackExecutorService()); + + Futures.addCallback(cleanupFuture, new FutureCallback<>() { + @Override + public void onSuccess(@Nullable Boolean markCompleted) { + if (Boolean.TRUE.equals(markCompleted)) { + markAdminSettingsCleanupCompleted(); + } + continuation.run(); + } + + @Override + public void onFailure(Throwable t) { + log.error("[{}][{}] Failed to run one-time admin settings cleanup for edge", tenantId, edge.getId(), t); + continuation.run(); + } + }, ctx.getGrpcCallbackExecutorService()); + } catch (Exception e) { + log.error("[{}][{}] Failed to start admin settings cleanup", tenantId, edge.getId(), e); + continuation.run(); + } + } + + private void markAdminSettingsCleanupCompleted() { + AttributeKvEntry attributeKvEntry = new BaseAttributeKvEntry( + new BooleanDataEntry(ADMIN_SETTINGS_CLEANUP_COMPLETED_ATTR_KEY, true), System.currentTimeMillis()); + ctx.getAttributesService().save(tenantId, edge.getId(), AttributeScope.SERVER_SCOPE, attributeKvEntry); + } + private void doSync(EdgeSyncCursor cursor) { if (cursor.hasNext()) { EdgeEventFetcher next = cursor.getNext(); @@ -949,6 +1005,21 @@ public abstract class EdgeGrpcSession implements Closeable { result.add(ctx.getDeviceProcessor().processDeviceRpcCallFromEdge(edge.getTenantId(), edge, deviceRpcCallMsg)); } } + if (uplinkMsg.getSendEmailUplinkMsgCount() > 0) { + for (SendEmailUplinkMsg sendEmailUplinkMsg : uplinkMsg.getSendEmailUplinkMsgList()) { + result.add(ctx.getEdgeRequestsService().processSendEmailMsg(edge.getTenantId(), edge, sendEmailUplinkMsg)); + } + } + if (uplinkMsg.getSendSmsUplinkMsgCount() > 0) { + for (SendSmsUplinkMsg sendSmsUplinkMsg : uplinkMsg.getSendSmsUplinkMsgList()) { + result.add(ctx.getEdgeRequestsService().processSendSmsMsg(edge.getTenantId(), edge, sendSmsUplinkMsg)); + } + } + if (uplinkMsg.getSendNotificationUplinkMsgCount() > 0) { + for (SendNotificationUplinkMsg sendNotificationUplinkMsg : uplinkMsg.getSendNotificationUplinkMsgList()) { + result.add(ctx.getEdgeRequestsService().processSendNotificationMsg(edge.getTenantId(), edge, sendNotificationUplinkMsg)); + } + } if (uplinkMsg.getWidgetBundleTypesRequestMsgCount() > 0) { for (WidgetBundleTypesRequestMsg widgetBundleTypesRequestMsg : uplinkMsg.getWidgetBundleTypesRequestMsgList()) { result.add(ctx.getEdgeRequestsService().processWidgetBundleTypesRequestMsg(edge.getTenantId(), edge, widgetBundleTypesRequestMsg)); diff --git a/application/src/main/java/org/thingsboard/server/service/edge/rpc/EdgeSyncCursor.java b/application/src/main/java/org/thingsboard/server/service/edge/rpc/EdgeSyncCursor.java index e9134a0b60..d650be2a26 100644 --- a/application/src/main/java/org/thingsboard/server/service/edge/rpc/EdgeSyncCursor.java +++ b/application/src/main/java/org/thingsboard/server/service/edge/rpc/EdgeSyncCursor.java @@ -21,7 +21,6 @@ import org.thingsboard.server.common.data.edge.Edge; import org.thingsboard.server.common.data.id.EntityId; import org.thingsboard.server.common.data.id.TenantId; import org.thingsboard.server.service.edge.EdgeContextComponent; -import org.thingsboard.server.service.edge.rpc.fetch.AdminSettingsEdgeEventFetcher; import org.thingsboard.server.service.edge.rpc.fetch.AiModelEdgeEventFetcher; import org.thingsboard.server.service.edge.rpc.fetch.AssetProfilesEdgeEventFetcher; import org.thingsboard.server.service.edge.rpc.fetch.AssetsEdgeEventFetcher; @@ -64,8 +63,8 @@ public class EdgeSyncCursor { fetchers.add(new TenantEdgeEventFetcher(ctx.getTenantService())); fetchers.add(new QueuesEdgeEventFetcher(ctx.getQueueService())); fetchers.add(new RuleChainsEdgeEventFetcher(ctx.getRuleChainService())); - fetchers.add(new AdminSettingsEdgeEventFetcher(ctx.getAdminSettingsService(), TenantId.SYS_TENANT_ID)); - fetchers.add(new AdminSettingsEdgeEventFetcher(ctx.getAdminSettingsService(), edge.getTenantId())); + // Admin settings are not synced to the edge: 'general'/'connectivity' are system-scoped and the edge + // auto-generates its own on install, while 'mail'/'sms'/'notifications' are delegated to the cloud. fetchers.add(new TenantAdminUsersEdgeEventFetcher(ctx.getUserService())); fetchers.add(new OAuth2EdgeEventFetcher(ctx.getDomainService())); fetchers.add(new SystemWidgetTypesEdgeEventFetcher(ctx.getWidgetTypeService())); diff --git a/application/src/main/java/org/thingsboard/server/service/edge/rpc/processor/settings/AdminSettingsEdgeProcessor.java b/application/src/main/java/org/thingsboard/server/service/edge/rpc/processor/settings/AdminSettingsEdgeProcessor.java index 2e0a65f324..2bf55f7c1a 100644 --- a/application/src/main/java/org/thingsboard/server/service/edge/rpc/processor/settings/AdminSettingsEdgeProcessor.java +++ b/application/src/main/java/org/thingsboard/server/service/edge/rpc/processor/settings/AdminSettingsEdgeProcessor.java @@ -15,25 +15,53 @@ */ package org.thingsboard.server.service.edge.rpc.processor.settings; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.node.ObjectNode; import lombok.extern.slf4j.Slf4j; +import org.apache.commons.lang3.RandomStringUtils; +import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; import org.thingsboard.common.util.JacksonUtil; import org.thingsboard.server.common.data.AdminSettings; import org.thingsboard.server.common.data.EdgeUtils; +import org.thingsboard.server.common.data.edge.Edge; import org.thingsboard.server.common.data.edge.EdgeEvent; import org.thingsboard.server.common.data.edge.EdgeEventType; import org.thingsboard.server.common.data.id.AdminSettingsId; +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.common.data.security.model.JwtSettings; import org.thingsboard.server.gen.edge.v1.AdminSettingsUpdateMsg; import org.thingsboard.server.gen.edge.v1.DownlinkMsg; import org.thingsboard.server.gen.edge.v1.EdgeVersion; import org.thingsboard.server.queue.util.TbCoreComponent; import org.thingsboard.server.service.edge.rpc.processor.BaseEdgeProcessor; +import org.thingsboard.server.service.security.auth.jwt.settings.JwtSettingsService; + +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.Base64; +import java.util.HashSet; +import java.util.List; +import java.util.Set; @Slf4j @Component @TbCoreComponent public class AdminSettingsEdgeProcessor extends BaseEdgeProcessor { + private static final Set EDGE_SYNCED_SETTINGS_KEYS = Set.of("general", "connectivity"); + + private static final int DEFAULT_PAGE_SIZE = 1000; + + @Value("${security.jwt.tokenExpirationTime:9000}") + private Integer tokenExpirationTime; + @Value("${security.jwt.refreshTokenExpTime:604800}") + private Integer refreshTokenExpTime; + @Value("${security.jwt.tokenIssuer:thingsboard.io}") + private String tokenIssuer; + @Override public DownlinkMsg convertEdgeEventToDownlink(EdgeEvent edgeEvent, EdgeVersion edgeVersion) { AdminSettings adminSettings = null; @@ -47,6 +75,12 @@ public class AdminSettingsEdgeProcessor extends BaseEdgeProcessor { if (adminSettings == null) { return null; } + if (TenantId.SYS_TENANT_ID.equals(adminSettings.getTenantId()) + || !EDGE_SYNCED_SETTINGS_KEYS.contains(adminSettings.getKey())) { + log.trace("Skipping admin settings [{}] sync to edge [{}] - not in the edge allow-list", + adminSettings.getKey(), edgeEvent.getEdgeId()); + return null; + } AdminSettingsUpdateMsg msg = AdminSettingsUpdateMsg.newBuilder().setEntity(JacksonUtil.toString(adminSettings)).build(); return DownlinkMsg.newBuilder() .setDownlinkMsgId(EdgeUtils.nextPositiveInt()) @@ -54,6 +88,61 @@ public class AdminSettingsEdgeProcessor extends BaseEdgeProcessor { .build(); } + public List convertAdminSettingsCleanupToDownlinks(Edge edge) { + List result = new ArrayList<>(); + Set cleanedKeys = new HashSet<>(); + + Set tenantScopes = Set.of(TenantId.SYS_TENANT_ID, edge.getTenantId()); + for (TenantId scope : tenantScopes) { + PageLink pageLink = new PageLink(DEFAULT_PAGE_SIZE); + PageData page; + do { + page = edgeCtx.getAdminSettingsService().findAllByTenantId(scope, pageLink); + for (AdminSettings adminSettings : page.getData()) { + String key = adminSettings.getKey(); + if (EDGE_SYNCED_SETTINGS_KEYS.contains(key) || !cleanedKeys.add(key)) { + continue; + } + result.add(buildAdminSettingsCleanupDownlink(key)); + } + pageLink = pageLink.nextPageLink(); + } while (page.hasNext()); + } + log.info("[{}][{}] Prepared {} one-time admin settings cleanup message(s): {}", + edge.getTenantId(), edge.getId(), result.size(), cleanedKeys); + return result; + } + + private DownlinkMsg buildAdminSettingsCleanupDownlink(String key) { + AdminSettings adminSettings = new AdminSettings(); + adminSettings.setTenantId(TenantId.SYS_TENANT_ID); + adminSettings.setKey(key); + adminSettings.setJsonValue(buildAdminSettingsCleanupValue(key)); + AdminSettingsUpdateMsg msg = AdminSettingsUpdateMsg.newBuilder().setEntity(JacksonUtil.toString(adminSettings)).build(); + return DownlinkMsg.newBuilder() + .setDownlinkMsgId(EdgeUtils.nextPositiveInt()) + .addAdminSettingsUpdateMsg(msg) + .build(); + } + + private JsonNode buildAdminSettingsCleanupValue(String key) { + if (JwtSettingsService.ADMIN_SETTINGS_JWT_KEY.equals(key)) { + return JacksonUtil.valueToTree(generateRandomJwtSettings()); + } + ObjectNode value = JacksonUtil.newObjectNode(); + if ("mail".equals(key)) { + value.put("password", ""); + value.put("refreshToken", ""); + } + return value; + } + + private JwtSettings generateRandomJwtSettings() { + String randomSigningKey = Base64.getEncoder().encodeToString( + RandomStringUtils.secure().nextAlphanumeric(64).getBytes(StandardCharsets.UTF_8)); + return new JwtSettings(tokenExpirationTime, refreshTokenExpTime, tokenIssuer, randomSigningKey); + } + @Override public EdgeEventType getEdgeEventType() { return EdgeEventType.ADMIN_SETTINGS; diff --git a/application/src/main/java/org/thingsboard/server/service/edge/rpc/sync/DefaultEdgeRequestsService.java b/application/src/main/java/org/thingsboard/server/service/edge/rpc/sync/DefaultEdgeRequestsService.java index 74de2132b4..823d3b6b9d 100644 --- a/application/src/main/java/org/thingsboard/server/service/edge/rpc/sync/DefaultEdgeRequestsService.java +++ b/application/src/main/java/org/thingsboard/server/service/edge/rpc/sync/DefaultEdgeRequestsService.java @@ -27,6 +27,10 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Lazy; import org.springframework.stereotype.Service; import org.thingsboard.common.util.JacksonUtil; +import org.thingsboard.rule.engine.api.MailService; +import org.thingsboard.rule.engine.api.SmsService; +import org.thingsboard.rule.engine.api.notification.FirebaseService; +import org.thingsboard.rule.engine.api.notification.SlackService; import org.thingsboard.server.common.data.AttributeScope; import org.thingsboard.server.common.data.EdgeUtils; import org.thingsboard.server.common.data.EntityType; @@ -46,6 +50,10 @@ import org.thingsboard.server.common.data.id.WidgetsBundleId; import org.thingsboard.server.common.data.kv.AttributeKvEntry; import org.thingsboard.server.common.data.kv.DataType; import org.thingsboard.server.common.data.kv.TsKvEntry; +import org.thingsboard.server.common.data.notification.NotificationDeliveryMethod; +import org.thingsboard.server.common.data.notification.settings.MobileAppNotificationDeliveryMethodConfig; +import org.thingsboard.server.common.data.notification.settings.NotificationSettings; +import org.thingsboard.server.common.data.notification.settings.SlackNotificationDeliveryMethodConfig; import org.thingsboard.server.common.data.relation.EntityRelation; import org.thingsboard.server.common.data.relation.EntityRelationsQuery; import org.thingsboard.server.common.data.relation.EntitySearchDirection; @@ -56,6 +64,7 @@ import org.thingsboard.server.common.data.widget.WidgetsBundle; import org.thingsboard.server.dao.attributes.AttributesService; import org.thingsboard.server.dao.cf.CalculatedFieldService; import org.thingsboard.server.dao.edge.EdgeEventService; +import org.thingsboard.server.dao.notification.NotificationSettingsService; import org.thingsboard.server.dao.relation.RelationService; import org.thingsboard.server.dao.timeseries.TimeseriesService; import org.thingsboard.server.dao.widget.WidgetTypeService; @@ -66,10 +75,16 @@ import org.thingsboard.server.gen.edge.v1.DeviceCredentialsRequestMsg; import org.thingsboard.server.gen.edge.v1.EntityViewsRequestMsg; import org.thingsboard.server.gen.edge.v1.RelationRequestMsg; import org.thingsboard.server.gen.edge.v1.RuleChainMetadataRequestMsg; +import org.thingsboard.server.gen.edge.v1.SendEmailUplinkMsg; +import org.thingsboard.server.gen.edge.v1.SendNotificationUplinkMsg; +import org.thingsboard.server.gen.edge.v1.SendSmsUplinkMsg; import org.thingsboard.server.gen.edge.v1.UserCredentialsRequestMsg; import org.thingsboard.server.gen.edge.v1.WidgetBundleTypesRequestMsg; import org.thingsboard.server.queue.util.TbCoreComponent; import org.thingsboard.server.service.entitiy.entityview.TbEntityViewService; +import org.thingsboard.server.service.mail.EdgeMailRequest; +import org.thingsboard.server.service.notification.EdgeNotificationRequest; +import org.thingsboard.server.service.sms.EdgeSmsRequest; import org.thingsboard.server.service.executors.DbCallbackExecutorService; import org.thingsboard.server.service.state.DefaultDeviceStateService; @@ -112,6 +127,21 @@ public class DefaultEdgeRequestsService implements EdgeRequestsService { @Autowired private DbCallbackExecutorService dbCallbackExecutorService; + @Autowired + private MailService mailService; + + @Autowired + private SmsService smsService; + + @Autowired + private SlackService slackService; + + @Autowired + private FirebaseService firebaseService; + + @Autowired + private NotificationSettingsService notificationSettingsService; + @Override public ListenableFuture processRuleChainMetadataRequestMsg(TenantId tenantId, Edge edge, RuleChainMetadataRequestMsg ruleChainMetadataRequestMsg) { log.trace("[{}] processRuleChainMetadataRequestMsg [{}][{}]", tenantId, edge.getName(), ruleChainMetadataRequestMsg); @@ -433,6 +463,144 @@ public class DefaultEdgeRequestsService implements EdgeRequestsService { return futureToSet; } + @Override + public ListenableFuture processSendEmailMsg(TenantId tenantId, Edge edge, SendEmailUplinkMsg sendEmailUplinkMsg) { + log.trace("[{}] processSendEmailMsg [{}]", tenantId, edge.getName()); + dbCallbackExecutorService.submit(() -> { + try { + sendEmailForEdge(tenantId, sendEmailUplinkMsg); + } catch (Exception e) { + log.warn("[{}] Failed to send email requested by edge [{}]", tenantId, edge.getName(), e); + } + return null; + }); + return Futures.immediateFuture(null); + } + + private void sendEmailForEdge(TenantId tenantId, SendEmailUplinkMsg sendEmailUplinkMsg) throws Exception { + EdgeMailRequest request = JacksonUtil.fromString(sendEmailUplinkMsg.getRequest(), EdgeMailRequest.class); + if (request == null || request.getMethod() == null) { + log.warn("[{}] Received empty send email request from edge", tenantId); + return; + } + switch (request.getMethod()) { + case SEND_BASIC -> + mailService.sendEmail(tenantId, request.getTo(), request.getSubject(), request.getMessage()); + case SEND_TB_EMAIL -> + mailService.send(tenantId, null, request.getTbEmail()); + case ACTIVATION -> + mailService.sendActivationEmail(request.getActivationLink(), request.getTtlMs(), request.getTo()); + case ACCOUNT_ACTIVATED -> + mailService.sendAccountActivatedEmail(request.getLoginLink(), request.getTo()); + case RESET_PASSWORD -> + mailService.sendResetPasswordEmail(request.getPasswordResetLink(), request.getTtlMs(), request.getTo()); + case PASSWORD_WAS_RESET -> + mailService.sendPasswordWasResetEmail(request.getLoginLink(), request.getTo()); + case TWO_FA -> + mailService.sendTwoFaVerificationEmail(request.getTo(), request.getVerificationCode(), request.getExpirationTimeSeconds()); + case ACCOUNT_LOCKOUT -> + mailService.sendAccountLockoutEmail(request.getLockoutEmail(), request.getTo(), request.getMaxFailedLoginAttempts()); + case API_USAGE_STATE -> + mailService.sendApiFeatureStateEmail(request.getApiFeature(), request.getStateValue(), request.getTo(), request.getRecordState()); + case TEST_MAIL -> + mailService.sendTestMail(request.getTestConfig(), request.getTo()); + } + } + + @Override + public ListenableFuture processSendSmsMsg(TenantId tenantId, Edge edge, SendSmsUplinkMsg sendSmsUplinkMsg) { + log.trace("[{}] processSendSmsMsg [{}]", tenantId, edge.getName()); + dbCallbackExecutorService.submit(() -> { + try { + sendSmsForEdge(tenantId, sendSmsUplinkMsg); + } catch (Exception e) { + log.warn("[{}] Failed to send sms requested by edge [{}]", tenantId, edge.getName(), e); + } + return null; + }); + return Futures.immediateFuture(null); + } + + private void sendSmsForEdge(TenantId tenantId, SendSmsUplinkMsg sendSmsUplinkMsg) throws Exception { + EdgeSmsRequest request = JacksonUtil.fromString(sendSmsUplinkMsg.getRequest(), EdgeSmsRequest.class); + if (request == null || request.getMethod() == null) { + log.warn("[{}] Received empty send sms request from edge", tenantId); + return; + } + switch (request.getMethod()) { + case SEND_SMS -> + smsService.sendSms(tenantId, null, request.getNumbers(), request.getMessage()); + case SEND_TEST_SMS -> + smsService.sendTestSms(request.getTestSmsRequest()); + } + } + + @Override + public ListenableFuture processSendNotificationMsg(TenantId tenantId, Edge edge, SendNotificationUplinkMsg sendNotificationUplinkMsg) { + log.trace("[{}] processSendNotificationMsg [{}]", tenantId, edge.getName()); + dbCallbackExecutorService.submit(() -> { + try { + sendNotificationForEdge(tenantId, sendNotificationUplinkMsg); + } catch (Exception e) { + log.warn("[{}] Failed to send notification requested by edge [{}]", tenantId, edge.getName(), e); + } + return null; + }); + return Futures.immediateFuture(null); + } + + private void sendNotificationForEdge(TenantId tenantId, SendNotificationUplinkMsg sendNotificationUplinkMsg) throws Exception { + EdgeNotificationRequest request = JacksonUtil.fromString(sendNotificationUplinkMsg.getRequest(), EdgeNotificationRequest.class); + if (request == null || request.getMethod() == null) { + log.warn("[{}] Received empty send notification request from edge", tenantId); + return; + } + switch (request.getMethod()) { + case SEND_SLACK -> sendSlackForEdge(tenantId, request); + case SEND_MOBILE_PUSH -> sendMobilePushForEdge(tenantId, request); + } + } + + private void sendSlackForEdge(TenantId tenantId, EdgeNotificationRequest request) { + SlackNotificationDeliveryMethodConfig config = getSlackConfig(tenantId); + if (config == null) { + log.warn("[{}] Slack is not configured on the cloud; dropping edge-delegated notification", tenantId); + return; + } + slackService.sendMessage(tenantId, config.getBotToken(), request.getConversationId(), request.getMessage()); + } + + private void sendMobilePushForEdge(TenantId tenantId, EdgeNotificationRequest request) { + MobileAppNotificationDeliveryMethodConfig config = getMobileAppConfig(tenantId); + if (config == null || request.getFcmTokens() == null) { + log.warn("[{}] Mobile app notifications are not configured on the cloud; dropping edge-delegated push", tenantId); + return; + } + String credentials = config.getFirebaseServiceAccountCredentials(); + for (String fcmToken : request.getFcmTokens()) { + try { + firebaseService.sendMessage(tenantId, credentials, fcmToken, request.getSubject(), request.getBody(), request.getData(), request.getBadge()); + } catch (Exception e) { + log.warn("[{}] Failed to push edge-delegated notification to FCM token", tenantId, e); + } + } + } + + private SlackNotificationDeliveryMethodConfig getSlackConfig(TenantId tenantId) { + NotificationSettings settings = notificationSettingsService.findNotificationSettings(tenantId); + return (SlackNotificationDeliveryMethodConfig) settings.getDeliveryMethodsConfigs().get(NotificationDeliveryMethod.SLACK); + } + + private MobileAppNotificationDeliveryMethodConfig getMobileAppConfig(TenantId tenantId) { + NotificationSettings settings = notificationSettingsService.findNotificationSettings(tenantId); + var config = (MobileAppNotificationDeliveryMethodConfig) settings.getDeliveryMethodsConfigs().get(NotificationDeliveryMethod.MOBILE_APP); + if (config == null && !tenantId.isSysTenantId()) { + settings = notificationSettingsService.findNotificationSettings(TenantId.SYS_TENANT_ID); + config = (MobileAppNotificationDeliveryMethodConfig) settings.getDeliveryMethodsConfigs().get(NotificationDeliveryMethod.MOBILE_APP); + } + return config; + } + private ListenableFuture saveEdgeEvent(TenantId tenantId, EdgeId edgeId, EdgeEventType type, diff --git a/application/src/main/java/org/thingsboard/server/service/edge/rpc/sync/EdgeRequestsService.java b/application/src/main/java/org/thingsboard/server/service/edge/rpc/sync/EdgeRequestsService.java index 09599ba7a5..4f03d57112 100644 --- a/application/src/main/java/org/thingsboard/server/service/edge/rpc/sync/EdgeRequestsService.java +++ b/application/src/main/java/org/thingsboard/server/service/edge/rpc/sync/EdgeRequestsService.java @@ -24,6 +24,9 @@ import org.thingsboard.server.gen.edge.v1.DeviceCredentialsRequestMsg; import org.thingsboard.server.gen.edge.v1.EntityViewsRequestMsg; import org.thingsboard.server.gen.edge.v1.RelationRequestMsg; import org.thingsboard.server.gen.edge.v1.RuleChainMetadataRequestMsg; +import org.thingsboard.server.gen.edge.v1.SendEmailUplinkMsg; +import org.thingsboard.server.gen.edge.v1.SendNotificationUplinkMsg; +import org.thingsboard.server.gen.edge.v1.SendSmsUplinkMsg; import org.thingsboard.server.gen.edge.v1.UserCredentialsRequestMsg; import org.thingsboard.server.gen.edge.v1.WidgetBundleTypesRequestMsg; @@ -50,4 +53,10 @@ public interface EdgeRequestsService { @Deprecated(since = "3.9.1", forRemoval = true) ListenableFuture processEntityViewsRequestMsg(TenantId tenantId, Edge edge, EntityViewsRequestMsg entityViewsRequestMsg); + ListenableFuture processSendEmailMsg(TenantId tenantId, Edge edge, SendEmailUplinkMsg sendEmailUplinkMsg); + + ListenableFuture processSendSmsMsg(TenantId tenantId, Edge edge, SendSmsUplinkMsg sendSmsUplinkMsg); + + ListenableFuture processSendNotificationMsg(TenantId tenantId, Edge edge, SendNotificationUplinkMsg sendNotificationUplinkMsg); + } diff --git a/application/src/main/java/org/thingsboard/server/service/mail/EdgeMailRequest.java b/application/src/main/java/org/thingsboard/server/service/mail/EdgeMailRequest.java new file mode 100644 index 0000000000..733f824b0e --- /dev/null +++ b/application/src/main/java/org/thingsboard/server/service/mail/EdgeMailRequest.java @@ -0,0 +1,80 @@ +/** + * Copyright © 2016-2026 The Thingsboard Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.thingsboard.server.service.mail; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.databind.JsonNode; +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; +import lombok.NoArgsConstructor; +import org.thingsboard.rule.engine.api.TbEmail; +import org.thingsboard.server.common.data.ApiFeature; +import org.thingsboard.server.common.data.ApiUsageRecordState; +import org.thingsboard.server.common.data.ApiUsageStateValue; + +/** + * Describes a mail send that the Edge delegates to the Cloud. On the Edge, a mail send that depends + * on admin-configured (tenant/system) mail settings is packaged into this request and enqueued as a + * SEND_EMAIL cloud event. On the Cloud, {@code method} selects the matching {@code MailService} call + * so the Cloud resolves the config, renders the template and transmits via its own SMTP. + */ +@Data +@Builder +@NoArgsConstructor +@AllArgsConstructor +@JsonInclude(JsonInclude.Include.NON_NULL) +public class EdgeMailRequest { + + public enum MailMethod { + SEND_BASIC, // sendEmail(to, subject, message) + SEND_TB_EMAIL, // send(TbEmail) + ACTIVATION, // sendActivationEmail(activationLink, ttlMs, to) + ACCOUNT_ACTIVATED, // sendAccountActivatedEmail(loginLink, to) + RESET_PASSWORD, // sendResetPasswordEmail(passwordResetLink, ttlMs, to) + PASSWORD_WAS_RESET,// sendPasswordWasResetEmail(loginLink, to) + TWO_FA, // sendTwoFaVerificationEmail(to, verificationCode, expirationTimeSeconds) + ACCOUNT_LOCKOUT, // sendAccountLockoutEmail(lockoutEmail, to, maxFailedLoginAttempts) + API_USAGE_STATE, // sendApiFeatureStateEmail(apiFeature, stateValue, to, recordState) + TEST_MAIL // sendTestMail(config, to) + } + + private MailMethod method; + + private String to; + private String subject; + private String message; + + private TbEmail tbEmail; + + private String activationLink; + private String loginLink; + private String passwordResetLink; + private Long ttlMs; + + private String verificationCode; + private Integer expirationTimeSeconds; + + private String lockoutEmail; + private Integer maxFailedLoginAttempts; + + private ApiFeature apiFeature; + private ApiUsageStateValue stateValue; + private ApiUsageRecordState recordState; + + private JsonNode testConfig; + +} diff --git a/application/src/main/java/org/thingsboard/server/service/notification/EdgeNotificationRequest.java b/application/src/main/java/org/thingsboard/server/service/notification/EdgeNotificationRequest.java new file mode 100644 index 0000000000..b135c574e8 --- /dev/null +++ b/application/src/main/java/org/thingsboard/server/service/notification/EdgeNotificationRequest.java @@ -0,0 +1,76 @@ +/** + * Copyright © 2016-2026 The Thingsboard Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.thingsboard.server.service.notification; + +import com.fasterxml.jackson.annotation.JsonInclude; +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; +import lombok.NoArgsConstructor; + +import java.util.List; +import java.util.Map; +import java.util.Set; + +/** + * Describes a notification delivery that the Edge delegates to the Cloud, for channels whose credentials + * live only on the Cloud (they are stored in the {@code notifications} admin settings that no longer sync + * to the Edge). {@code method} selects the channel: + *
    + *
  • {@code SEND_SLACK} - the Cloud resolves the Slack bot token and posts {@code message} (plus any + * {@code files}) to {@code conversationId}. The whole send is delegated.
  • + *
  • {@code SEND_MOBILE_PUSH} - the Edge keeps the notification record, device-token lookup and unread + * count locally and delegates only the FCM push: the Cloud resolves the Firebase credentials and pushes + * the already-built payload ({@code subject}/{@code body}/{@code data}/{@code badge}) to every + * {@code fcmToken}.
  • + *
+ */ +@Data +@Builder +@NoArgsConstructor +@AllArgsConstructor +@JsonInclude(JsonInclude.Include.NON_NULL) +public class EdgeNotificationRequest { + + public enum NotificationMethod { + SEND_SLACK, + SEND_MOBILE_PUSH + } + + private NotificationMethod method; + + // SEND_SLACK + private String conversationId; + private String message; + private List files; + + // SEND_MOBILE_PUSH + private Set fcmTokens; + private String subject; + private String body; + private Map data; + private Integer badge; + + @Data + @NoArgsConstructor + @AllArgsConstructor + public static class SlackFileData { + private String name; + private String type; + private byte[] data; + } + +} diff --git a/application/src/main/java/org/thingsboard/server/service/sms/EdgeSmsRequest.java b/application/src/main/java/org/thingsboard/server/service/sms/EdgeSmsRequest.java new file mode 100644 index 0000000000..649b8a5a85 --- /dev/null +++ b/application/src/main/java/org/thingsboard/server/service/sms/EdgeSmsRequest.java @@ -0,0 +1,51 @@ +/** + * Copyright © 2016-2026 The Thingsboard Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.thingsboard.server.service.sms; + +import com.fasterxml.jackson.annotation.JsonInclude; +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; +import lombok.NoArgsConstructor; +import org.thingsboard.server.common.data.sms.config.TestSmsRequest; + +/** + * Describes an SMS send that the Edge delegates to the Cloud. On the Edge, a send that depends on + * admin-configured (tenant/system) SMS provider settings cannot be resolved locally, so the call is + * packaged into this request and enqueued as a SEND_SMS cloud event; on the Cloud, {@code method} + * selects the matching {@code SmsService} call so the Cloud resolves the config and transmits via its + * own provider. + */ +@Data +@Builder +@NoArgsConstructor +@AllArgsConstructor +@JsonInclude(JsonInclude.Include.NON_NULL) +public class EdgeSmsRequest { + + public enum SmsMethod { + SEND_SMS, // sendSms(customerId, numbersTo, message) + SEND_TEST_SMS // sendTestSms(testSmsRequest) + } + + private SmsMethod method; + + private String[] numbers; + private String message; + + private TestSmsRequest testSmsRequest; + +} diff --git a/application/src/test/java/org/thingsboard/server/controller/EdgeControllerTest.java b/application/src/test/java/org/thingsboard/server/controller/EdgeControllerTest.java index 9d50e3a62c..a6ed979119 100644 --- a/application/src/test/java/org/thingsboard/server/controller/EdgeControllerTest.java +++ b/application/src/test/java/org/thingsboard/server/controller/EdgeControllerTest.java @@ -42,7 +42,6 @@ import org.springframework.test.context.TestPropertySource; import org.springframework.test.util.TestSocketUtils; import org.thingsboard.common.util.JacksonUtil; import org.thingsboard.common.util.ThingsBoardExecutors; -import org.thingsboard.server.common.data.AdminSettings; import org.thingsboard.server.common.data.AttributeScope; import org.thingsboard.server.common.data.Customer; import org.thingsboard.server.common.data.Device; @@ -79,7 +78,6 @@ import org.thingsboard.server.exception.DataValidationException; import org.thingsboard.server.dao.model.ModelConstants; import org.thingsboard.server.dao.service.DaoSqlTest; import org.thingsboard.server.edge.imitator.EdgeImitator; -import org.thingsboard.server.gen.edge.v1.AdminSettingsUpdateMsg; import org.thingsboard.server.gen.edge.v1.AssetProfileUpdateMsg; import org.thingsboard.server.gen.edge.v1.AssetUpdateMsg; import org.thingsboard.server.gen.edge.v1.CustomerUpdateMsg; @@ -1012,10 +1010,6 @@ public class EdgeControllerTest extends AbstractControllerTest { Assert.assertTrue(popQueueMsg(edgeImitator.getDownlinkMsgsDeque(), UpdateMsgType.ENTITY_CREATED_RPC_MESSAGE, "Main")); Assert.assertTrue(popRuleChainMsg(edgeImitator.getDownlinkMsgsDeque(), UpdateMsgType.ENTITY_CREATED_RPC_MESSAGE, "Edge Root Rule Chain")); Assert.assertTrue(popRuleChainMetadataMsg(edgeImitator.getDownlinkMsgsDeque(), UpdateMsgType.ENTITY_CREATED_RPC_MESSAGE, getEdgeRootRuleChainId(edgeImitator))); - Assert.assertTrue(popAdminSettingsMsg(edgeImitator.getDownlinkMsgsDeque(), "general")); - Assert.assertTrue(popAdminSettingsMsg(edgeImitator.getDownlinkMsgsDeque(), "mail")); - Assert.assertTrue(popAdminSettingsMsg(edgeImitator.getDownlinkMsgsDeque(), "connectivity")); - Assert.assertTrue(popAdminSettingsMsg(edgeImitator.getDownlinkMsgsDeque(), "jwt")); Assert.assertTrue(popDeviceProfileMsg(edgeImitator.getDownlinkMsgsDeque(), UpdateMsgType.ENTITY_CREATED_RPC_MESSAGE, "default")); Assert.assertTrue(popDeviceProfileMsg(edgeImitator.getDownlinkMsgsDeque(), UpdateMsgType.ENTITY_CREATED_RPC_MESSAGE, "default")); Assert.assertTrue(popAssetProfileMsg(edgeImitator.getDownlinkMsgsDeque(), UpdateMsgType.ENTITY_CREATED_RPC_MESSAGE, "default")); @@ -1079,20 +1073,6 @@ public class EdgeControllerTest extends AbstractControllerTest { return false; } - private boolean popAdminSettingsMsg(Deque messages, String key) { - for (AbstractMessage message : messages) { - if (message instanceof AdminSettingsUpdateMsg adminSettingsUpdateMsg) { - AdminSettings adminSettings = JacksonUtil.fromString(adminSettingsUpdateMsg.getEntity(), AdminSettings.class, true); - Assert.assertNotNull(adminSettings); - if (key.equals(adminSettings.getKey())) { - messages.remove(message); - return true; - } - } - } - return false; - } - private boolean popDeviceProfileMsg(Deque messages, UpdateMsgType msgType, String name) { for (AbstractMessage message : messages) { if (message instanceof DeviceProfileUpdateMsg deviceProfileUpdateMsg) { diff --git a/application/src/test/java/org/thingsboard/server/edge/AbstractEdgeTest.java b/application/src/test/java/org/thingsboard/server/edge/AbstractEdgeTest.java index d75c7b8f59..156b561d63 100644 --- a/application/src/test/java/org/thingsboard/server/edge/AbstractEdgeTest.java +++ b/application/src/test/java/org/thingsboard/server/edge/AbstractEdgeTest.java @@ -131,7 +131,7 @@ abstract public class AbstractEdgeTest extends AbstractControllerTest { registry.add("edges.rpc.port", () -> EDGE_PORT); } - public static final Integer CONNECT_MESSAGE_COUNT = 17; + public static final Integer CONNECT_MESSAGE_COUNT = 13; public static final Integer INSTALLATION_MESSAGE_COUNT = 8; public static final Integer SYNC_MESSAGE_COUNT = CONNECT_MESSAGE_COUNT + INSTALLATION_MESSAGE_COUNT; private static final String THERMOSTAT_DEVICE_PROFILE_NAME = "Thermostat"; @@ -282,9 +282,9 @@ abstract public class AbstractEdgeTest extends AbstractControllerTest { validateMsgsCnt(RuleChainMetadataUpdateMsg.class, 1); validateRuleChainMetadataUpdates(ruleChainUUID); - // 4 messages ('general', 'mail', 'connectivity', 'jwt') - validateMsgsCnt(AdminSettingsUpdateMsg.class, 4); - validateAdminSettings(4); + // No admin settings are synced to the edge: 'general'/'connectivity' are system-scoped and the edge + // auto-generates its own, while 'mail'/'sms'/'notifications' are delegated to the cloud. + validateMsgsCnt(AdminSettingsUpdateMsg.class, 0); // 4 messages // - 1 from default profile fetcher diff --git a/application/src/test/java/org/thingsboard/server/edge/AdminSettingsEdgeTest.java b/application/src/test/java/org/thingsboard/server/edge/AdminSettingsEdgeTest.java deleted file mode 100644 index 43350f7e8f..0000000000 --- a/application/src/test/java/org/thingsboard/server/edge/AdminSettingsEdgeTest.java +++ /dev/null @@ -1,79 +0,0 @@ -/** - * Copyright © 2016-2026 The Thingsboard Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.thingsboard.server.edge; - -import com.fasterxml.jackson.databind.node.ObjectNode; -import com.google.protobuf.AbstractMessage; -import org.junit.Assert; -import org.junit.Test; -import org.springframework.beans.factory.annotation.Autowired; -import org.thingsboard.common.util.JacksonUtil; -import org.thingsboard.server.common.data.AdminSettings; -import org.thingsboard.server.dao.service.DaoSqlTest; -import org.thingsboard.server.dao.settings.AdminSettingsService; -import org.thingsboard.server.gen.edge.v1.AdminSettingsUpdateMsg; - -@DaoSqlTest -public class AdminSettingsEdgeTest extends AbstractEdgeTest { - - @Autowired - private AdminSettingsService adminSettingsService; - - @Test - public void testAdminSettings() throws Exception { - loginSysAdmin(); - - // save - AdminSettings adminSettings = new AdminSettings(); - adminSettings.setKey("edgeTest"); - ObjectNode jsonValue = JacksonUtil.newObjectNode(); - jsonValue.put("key1", "value1"); - adminSettings.setJsonValue(jsonValue); - - edgeImitator.expectMessageAmount(1); - AdminSettings savedAdminSettings = doPost("/api/admin/settings", adminSettings, AdminSettings.class); - Assert.assertTrue(edgeImitator.waitForMessages()); - - AbstractMessage latestMessage = edgeImitator.getLatestMessage(); - Assert.assertTrue(latestMessage instanceof AdminSettingsUpdateMsg); - AdminSettingsUpdateMsg adminSettingsUpdateMsg = (AdminSettingsUpdateMsg) latestMessage; - AdminSettings adminSettingsMsg = JacksonUtil.fromString(adminSettingsUpdateMsg.getEntity(), AdminSettings.class, true); - Assert.assertNotNull(adminSettingsMsg); - Assert.assertEquals("edgeTest", adminSettingsMsg.getKey()); - Assert.assertEquals("value1", adminSettingsMsg.getJsonValue().get("key1").asText()); - - // update - ObjectNode updatedJsonValue = (ObjectNode) savedAdminSettings.getJsonValue(); - updatedJsonValue.put("key2", "value2"); - savedAdminSettings.setJsonValue(updatedJsonValue); - - edgeImitator.expectMessageAmount(1); - doPost("/api/admin/settings", savedAdminSettings, AdminSettings.class); - Assert.assertTrue(edgeImitator.waitForMessages()); - - latestMessage = edgeImitator.getLatestMessage(); - Assert.assertTrue(latestMessage instanceof AdminSettingsUpdateMsg); - adminSettingsUpdateMsg = (AdminSettingsUpdateMsg) latestMessage; - adminSettingsMsg = JacksonUtil.fromString(adminSettingsUpdateMsg.getEntity(), AdminSettings.class, true); - Assert.assertNotNull(adminSettingsMsg); - Assert.assertEquals("edgeTest", adminSettingsMsg.getKey()); - Assert.assertEquals("value1", adminSettingsMsg.getJsonValue().get("key1").asText()); - Assert.assertEquals("value2", adminSettingsMsg.getJsonValue().get("key2").asText()); - - adminSettingsService.deleteAdminSettingsByTenantIdAndKey(savedAdminSettings.getTenantId(), "edgeTest"); - } - -} diff --git a/application/src/test/java/org/thingsboard/server/edge/SendEmailEdgeTest.java b/application/src/test/java/org/thingsboard/server/edge/SendEmailEdgeTest.java new file mode 100644 index 0000000000..89e31c38c7 --- /dev/null +++ b/application/src/test/java/org/thingsboard/server/edge/SendEmailEdgeTest.java @@ -0,0 +1,99 @@ +/** + * Copyright © 2016-2026 The Thingsboard Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.thingsboard.server.edge; + +import org.junit.Assert; +import org.junit.Test; +import org.springframework.test.context.bean.override.mockito.MockitoBean; +import org.thingsboard.common.util.JacksonUtil; +import org.thingsboard.rule.engine.api.MailService; +import org.thingsboard.rule.engine.api.TbEmail; +import org.thingsboard.server.common.data.EdgeUtils; +import org.thingsboard.server.dao.service.DaoSqlTest; +import org.thingsboard.server.gen.edge.v1.SendEmailUplinkMsg; +import org.thingsboard.server.gen.edge.v1.UplinkMsg; +import org.thingsboard.server.service.mail.EdgeMailRequest; + +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.ArgumentMatchers.isNull; +import static org.mockito.Mockito.timeout; +import static org.mockito.Mockito.verify; + +/** + * Verifies the send-email uplink: when the Edge delegates a mail send, the Cloud receives the + * SendEmailUplinkMsg and invokes its MailService (which resolves the config, renders and transmits). Here + * the EdgeImitator plays the Edge and sends the uplink; the Cloud's MailService is mocked so we can assert + * the delegated call arrives with the expected arguments (the Cloud, not the Edge, uses the tenant id of + * the connected edge). + */ +@DaoSqlTest +public class SendEmailEdgeTest extends AbstractEdgeTest { + + @MockitoBean + private MailService mailService; + + @Test + public void testSendBasicEmailFromEdgeProcessedByCloud() throws Exception { + EdgeMailRequest request = EdgeMailRequest.builder() + .method(EdgeMailRequest.MailMethod.SEND_BASIC) + .to("recipient@thingsboard.io") + .subject("Edge test subject") + .message("Edge test body") + .build(); + + sendEmailUplink(request); + + verify(mailService, timeout(30000)) + .sendEmail(eq(tenantId), eq("recipient@thingsboard.io"), eq("Edge test subject"), eq("Edge test body")); + } + + @Test + public void testSendTbEmailFromEdgeProcessedByCloud() throws Exception { + TbEmail tbEmail = TbEmail.builder() + .from("noreply@thingsboard.io") + .to("recipient@thingsboard.io") + .subject("Rule chain email") + .body("Alarm!") + .html(false) + .build(); + EdgeMailRequest request = EdgeMailRequest.builder() + .method(EdgeMailRequest.MailMethod.SEND_TB_EMAIL) + .tbEmail(tbEmail) + .build(); + + sendEmailUplink(request); + + verify(mailService, timeout(30000)).send(eq(tenantId), isNull(), any(TbEmail.class)); + } + + private void sendEmailUplink(EdgeMailRequest request) throws Exception { + SendEmailUplinkMsg sendEmailUplinkMsg = SendEmailUplinkMsg.newBuilder() + .setTenantIdMSB(tenantId.getId().getMostSignificantBits()) + .setTenantIdLSB(tenantId.getId().getLeastSignificantBits()) + .setRequest(JacksonUtil.toString(request)) + .build(); + + UplinkMsg.Builder uplinkMsgBuilder = UplinkMsg.newBuilder(); + uplinkMsgBuilder.setUplinkMsgId(EdgeUtils.nextPositiveInt()); + uplinkMsgBuilder.addSendEmailUplinkMsg(sendEmailUplinkMsg); + + edgeImitator.expectResponsesAmount(1); + edgeImitator.sendUplinkMsg(uplinkMsgBuilder.build()); + Assert.assertTrue(edgeImitator.waitForResponses()); + } + +} diff --git a/application/src/test/java/org/thingsboard/server/edge/SendNotificationEdgeTest.java b/application/src/test/java/org/thingsboard/server/edge/SendNotificationEdgeTest.java new file mode 100644 index 0000000000..3c8802f07e --- /dev/null +++ b/application/src/test/java/org/thingsboard/server/edge/SendNotificationEdgeTest.java @@ -0,0 +1,134 @@ +/** + * Copyright © 2016-2026 The Thingsboard Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.thingsboard.server.edge; + +import org.junit.Assert; +import org.junit.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.test.context.bean.override.mockito.MockitoBean; +import org.thingsboard.common.util.JacksonUtil; +import org.thingsboard.rule.engine.api.notification.FirebaseService; +import org.thingsboard.rule.engine.api.notification.SlackService; +import org.thingsboard.server.common.data.EdgeUtils; +import org.thingsboard.server.common.data.id.TenantId; +import org.thingsboard.server.common.data.notification.NotificationDeliveryMethod; +import org.thingsboard.server.common.data.notification.settings.MobileAppNotificationDeliveryMethodConfig; +import org.thingsboard.server.common.data.notification.settings.NotificationDeliveryMethodConfig; +import org.thingsboard.server.common.data.notification.settings.NotificationSettings; +import org.thingsboard.server.common.data.notification.settings.SlackNotificationDeliveryMethodConfig; +import org.thingsboard.server.dao.notification.NotificationSettingsService; +import org.thingsboard.server.dao.service.DaoSqlTest; +import org.thingsboard.server.gen.edge.v1.SendNotificationUplinkMsg; +import org.thingsboard.server.gen.edge.v1.UplinkMsg; +import org.thingsboard.server.service.notification.EdgeNotificationRequest; + +import java.util.HashMap; +import java.util.Map; +import java.util.Set; + +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.timeout; +import static org.mockito.Mockito.verify; + +/** + * Verifies the send-notification uplink: when the Edge delegates a Slack or mobile-push notification, the + * Cloud receives the SendNotificationUplinkMsg, resolves the channel credentials from its own notification + * settings and delivers. The EdgeImitator plays the Edge and sends the uplink; the Cloud's SlackService and + * FirebaseService are mocked so we can assert the delegated call arrives with the expected arguments. + */ +@DaoSqlTest +public class SendNotificationEdgeTest extends AbstractEdgeTest { + + @MockitoBean + private SlackService slackService; + + @MockitoBean + private FirebaseService firebaseService; + + @Autowired + private NotificationSettingsService notificationSettingsService; + + private void prepareNotificationSettings() { + // Slack is configured at tenant level. + SlackNotificationDeliveryMethodConfig slack = new SlackNotificationDeliveryMethodConfig(); + slack.setBotToken("xoxb-edge-test-token"); + NotificationSettings tenantSettings = new NotificationSettings(); + Map tenantConfigs = new HashMap<>(); + tenantConfigs.put(NotificationDeliveryMethod.SLACK, slack); + tenantSettings.setDeliveryMethodsConfigs(tenantConfigs); + notificationSettingsService.saveNotificationSettings(tenantId, tenantSettings); + + // Mobile app credentials can only be configured at system level. + MobileAppNotificationDeliveryMethodConfig mobile = new MobileAppNotificationDeliveryMethodConfig(); + mobile.setFirebaseServiceAccountCredentials("{\"type\":\"service_account\"}"); + NotificationSettings systemSettings = new NotificationSettings(); + Map systemConfigs = new HashMap<>(); + systemConfigs.put(NotificationDeliveryMethod.MOBILE_APP, mobile); + systemSettings.setDeliveryMethodsConfigs(systemConfigs); + notificationSettingsService.saveNotificationSettings(TenantId.SYS_TENANT_ID, systemSettings); + } + + @Test + public void testSendSlackNotificationFromEdgeProcessedByCloud() throws Exception { + prepareNotificationSettings(); + EdgeNotificationRequest request = EdgeNotificationRequest.builder() + .method(EdgeNotificationRequest.NotificationMethod.SEND_SLACK) + .conversationId("C0123456789") + .message("Edge Slack notification") + .build(); + + sendNotificationUplink(request); + + verify(slackService, timeout(30000)) + .sendMessage(eq(tenantId), anyString(), eq("C0123456789"), eq("Edge Slack notification")); + } + + @Test + public void testSendMobilePushFromEdgeProcessedByCloud() throws Exception { + prepareNotificationSettings(); + EdgeNotificationRequest request = EdgeNotificationRequest.builder() + .method(EdgeNotificationRequest.NotificationMethod.SEND_MOBILE_PUSH) + .fcmTokens(Set.of("fcm-token-1")) + .subject("Edge subject") + .body("Edge body") + .badge(3) + .build(); + + sendNotificationUplink(request); + + verify(firebaseService, timeout(30000)) + .sendMessage(eq(tenantId), anyString(), eq("fcm-token-1"), eq("Edge subject"), eq("Edge body"), any(), eq(3)); + } + + private void sendNotificationUplink(EdgeNotificationRequest request) throws Exception { + SendNotificationUplinkMsg sendNotificationUplinkMsg = SendNotificationUplinkMsg.newBuilder() + .setTenantIdMSB(tenantId.getId().getMostSignificantBits()) + .setTenantIdLSB(tenantId.getId().getLeastSignificantBits()) + .setRequest(JacksonUtil.toString(request)) + .build(); + + UplinkMsg.Builder uplinkMsgBuilder = UplinkMsg.newBuilder(); + uplinkMsgBuilder.setUplinkMsgId(EdgeUtils.nextPositiveInt()); + uplinkMsgBuilder.addSendNotificationUplinkMsg(sendNotificationUplinkMsg); + + edgeImitator.expectResponsesAmount(1); + edgeImitator.sendUplinkMsg(uplinkMsgBuilder.build()); + Assert.assertTrue(edgeImitator.waitForResponses()); + } + +} diff --git a/application/src/test/java/org/thingsboard/server/edge/SmsEdgeTest.java b/application/src/test/java/org/thingsboard/server/edge/SmsEdgeTest.java new file mode 100644 index 0000000000..e8decbe7d2 --- /dev/null +++ b/application/src/test/java/org/thingsboard/server/edge/SmsEdgeTest.java @@ -0,0 +1,94 @@ +/** + * Copyright © 2016-2026 The Thingsboard Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.thingsboard.server.edge; + +import org.junit.Assert; +import org.junit.Test; +import org.springframework.test.context.bean.override.mockito.MockitoBean; +import org.thingsboard.common.util.JacksonUtil; +import org.thingsboard.rule.engine.api.SmsService; +import org.thingsboard.server.common.data.EdgeUtils; +import org.thingsboard.server.common.data.sms.config.TestSmsRequest; +import org.thingsboard.server.dao.service.DaoSqlTest; +import org.thingsboard.server.gen.edge.v1.SendSmsUplinkMsg; +import org.thingsboard.server.gen.edge.v1.UplinkMsg; +import org.thingsboard.server.service.sms.EdgeSmsRequest; + +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.ArgumentMatchers.isNull; +import static org.mockito.Mockito.timeout; +import static org.mockito.Mockito.verify; + +/** + * Verifies the send-sms uplink: when the Edge delegates an SMS send, the Cloud receives the + * SendSmsUplinkMsg and invokes its SmsService (which resolves the config and transmits). Here the + * EdgeImitator plays the Edge and sends the uplink; the Cloud's SmsService is mocked so we can assert the + * delegated call arrives with the expected arguments (the Cloud, not the Edge, uses the tenant id of the + * connected edge). + */ +@DaoSqlTest +public class SmsEdgeTest extends AbstractEdgeTest { + + @MockitoBean + private SmsService smsService; + + @Test + public void testSendSmsFromEdgeProcessedByCloud() throws Exception { + EdgeSmsRequest request = EdgeSmsRequest.builder() + .method(EdgeSmsRequest.SmsMethod.SEND_SMS) + .numbers(new String[]{"+15551234567"}) + .message("Edge test message") + .build(); + + sendSmsUplink(request); + + verify(smsService, timeout(30000)) + .sendSms(eq(tenantId), isNull(), any(String[].class), eq("Edge test message")); + } + + @Test + public void testSendTestSmsFromEdgeProcessedByCloud() throws Exception { + TestSmsRequest testSmsRequest = new TestSmsRequest(); + testSmsRequest.setNumberTo("+15551234567"); + testSmsRequest.setMessage("Test message"); + EdgeSmsRequest request = EdgeSmsRequest.builder() + .method(EdgeSmsRequest.SmsMethod.SEND_TEST_SMS) + .testSmsRequest(testSmsRequest) + .build(); + + sendSmsUplink(request); + + verify(smsService, timeout(30000)).sendTestSms(any(TestSmsRequest.class)); + } + + private void sendSmsUplink(EdgeSmsRequest request) throws Exception { + SendSmsUplinkMsg sendSmsUplinkMsg = SendSmsUplinkMsg.newBuilder() + .setTenantIdMSB(tenantId.getId().getMostSignificantBits()) + .setTenantIdLSB(tenantId.getId().getLeastSignificantBits()) + .setRequest(JacksonUtil.toString(request)) + .build(); + + UplinkMsg.Builder uplinkMsgBuilder = UplinkMsg.newBuilder(); + uplinkMsgBuilder.setUplinkMsgId(EdgeUtils.nextPositiveInt()); + uplinkMsgBuilder.addSendSmsUplinkMsg(sendSmsUplinkMsg); + + edgeImitator.expectResponsesAmount(1); + edgeImitator.sendUplinkMsg(uplinkMsgBuilder.build()); + Assert.assertTrue(edgeImitator.waitForResponses()); + } + +} diff --git a/common/edge-api/src/main/proto/edge.proto b/common/edge-api/src/main/proto/edge.proto index b68597842d..f02af241d5 100644 --- a/common/edge-api/src/main/proto/edge.proto +++ b/common/edge-api/src/main/proto/edge.proto @@ -367,6 +367,24 @@ message CalculatedFieldRequestMsg { string entityType = 3; } +message SendEmailUplinkMsg { + int64 tenantIdMSB = 1; + int64 tenantIdLSB = 2; + string request = 3; +} + +message SendSmsUplinkMsg { + int64 tenantIdMSB = 1; + int64 tenantIdLSB = 2; + string request = 3; +} + +message SendNotificationUplinkMsg { + int64 tenantIdMSB = 1; + int64 tenantIdLSB = 2; + string request = 3; +} + // DEPRECATED. FOR REMOVAL message UserCredentialsRequestMsg { option deprecated = true; @@ -471,6 +489,9 @@ message UplinkMsg { repeated UserUpdateMsg userUpdateMsg = 28; repeated UserCredentialsUpdateMsg userCredentialsUpdateMsg = 29; repeated ApiKeyUpdateMsg apiKeyUpdateMsg = 30; + repeated SendEmailUplinkMsg sendEmailUplinkMsg = 35; + repeated SendSmsUplinkMsg sendSmsUplinkMsg = 36; + repeated SendNotificationUplinkMsg sendNotificationUplinkMsg = 37; } message UplinkResponseMsg { From 041b2635b549ecfbe2a57c51988d4c9fb3c44bb3 Mon Sep 17 00:00:00 2001 From: Nikita Mazurenko Date: Fri, 17 Jul 2026 16:22:13 +0300 Subject: [PATCH 03/16] Squashed commit of the following: commit 54284ed89d12c67ddb2a5c5f410c8993bb0e62b8 Author: Nikita Mazurenko Date: Fri Jul 17 15:30:13 2026 +0300 Receive mail/SMS/notification uplink requests from edge --- .../thingsboard/server/service/edge/rpc/EdgeSyncCursor.java | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/application/src/main/java/org/thingsboard/server/service/edge/rpc/EdgeSyncCursor.java b/application/src/main/java/org/thingsboard/server/service/edge/rpc/EdgeSyncCursor.java index d650be2a26..ca2d4e1f57 100644 --- a/application/src/main/java/org/thingsboard/server/service/edge/rpc/EdgeSyncCursor.java +++ b/application/src/main/java/org/thingsboard/server/service/edge/rpc/EdgeSyncCursor.java @@ -19,8 +19,7 @@ import lombok.Getter; import org.thingsboard.server.common.data.Customer; import org.thingsboard.server.common.data.edge.Edge; import org.thingsboard.server.common.data.id.EntityId; -import org.thingsboard.server.common.data.id.TenantId; -import org.thingsboard.server.service.edge.EdgeContextComponent; +import org.thingsboard.server.service.edge.EdgeContextComponent import org.thingsboard.server.service.edge.rpc.fetch.AiModelEdgeEventFetcher; import org.thingsboard.server.service.edge.rpc.fetch.AssetProfilesEdgeEventFetcher; import org.thingsboard.server.service.edge.rpc.fetch.AssetsEdgeEventFetcher; From 94fe58463850a3ad08e0708fab95e628eedfe478 Mon Sep 17 00:00:00 2001 From: Nikita Mazurenko Date: Fri, 17 Jul 2026 17:48:58 +0300 Subject: [PATCH 04/16] Refactor edge send-uplink handling and add mail/admin-settings test coverage --- .../rpc/sync/DefaultEdgeRequestsService.java | 37 ++-- .../server/edge/AbstractEdgeTest.java | 13 ++ .../server/edge/SendEmailEdgeTest.java | 133 ++++++++++++-- .../server/edge/SendNotificationEdgeTest.java | 12 +- ...{SmsEdgeTest.java => SendSmsEdgeTest.java} | 14 +- .../AdminSettingsEdgeProcessorTest.java | 163 ++++++++++++++++++ common/edge-api/src/main/proto/edge.proto | 4 + 7 files changed, 319 insertions(+), 57 deletions(-) rename application/src/test/java/org/thingsboard/server/edge/{SmsEdgeTest.java => SendSmsEdgeTest.java} (85%) create mode 100644 application/src/test/java/org/thingsboard/server/service/edge/rpc/processor/settings/AdminSettingsEdgeProcessorTest.java diff --git a/application/src/main/java/org/thingsboard/server/service/edge/rpc/sync/DefaultEdgeRequestsService.java b/application/src/main/java/org/thingsboard/server/service/edge/rpc/sync/DefaultEdgeRequestsService.java index 823d3b6b9d..a974dcaf0c 100644 --- a/application/src/main/java/org/thingsboard/server/service/edge/rpc/sync/DefaultEdgeRequestsService.java +++ b/application/src/main/java/org/thingsboard/server/service/edge/rpc/sync/DefaultEdgeRequestsService.java @@ -465,16 +465,7 @@ public class DefaultEdgeRequestsService implements EdgeRequestsService { @Override public ListenableFuture processSendEmailMsg(TenantId tenantId, Edge edge, SendEmailUplinkMsg sendEmailUplinkMsg) { - log.trace("[{}] processSendEmailMsg [{}]", tenantId, edge.getName()); - dbCallbackExecutorService.submit(() -> { - try { - sendEmailForEdge(tenantId, sendEmailUplinkMsg); - } catch (Exception e) { - log.warn("[{}] Failed to send email requested by edge [{}]", tenantId, edge.getName(), e); - } - return null; - }); - return Futures.immediateFuture(null); + return submitEdgeSend(tenantId, edge, "email", () -> sendEmailForEdge(tenantId, sendEmailUplinkMsg)); } private void sendEmailForEdge(TenantId tenantId, SendEmailUplinkMsg sendEmailUplinkMsg) throws Exception { @@ -509,16 +500,7 @@ public class DefaultEdgeRequestsService implements EdgeRequestsService { @Override public ListenableFuture processSendSmsMsg(TenantId tenantId, Edge edge, SendSmsUplinkMsg sendSmsUplinkMsg) { - log.trace("[{}] processSendSmsMsg [{}]", tenantId, edge.getName()); - dbCallbackExecutorService.submit(() -> { - try { - sendSmsForEdge(tenantId, sendSmsUplinkMsg); - } catch (Exception e) { - log.warn("[{}] Failed to send sms requested by edge [{}]", tenantId, edge.getName(), e); - } - return null; - }); - return Futures.immediateFuture(null); + return submitEdgeSend(tenantId, edge, "sms", () -> sendSmsForEdge(tenantId, sendSmsUplinkMsg)); } private void sendSmsForEdge(TenantId tenantId, SendSmsUplinkMsg sendSmsUplinkMsg) throws Exception { @@ -537,12 +519,16 @@ public class DefaultEdgeRequestsService implements EdgeRequestsService { @Override public ListenableFuture processSendNotificationMsg(TenantId tenantId, Edge edge, SendNotificationUplinkMsg sendNotificationUplinkMsg) { - log.trace("[{}] processSendNotificationMsg [{}]", tenantId, edge.getName()); + return submitEdgeSend(tenantId, edge, "notification", () -> sendNotificationForEdge(tenantId, sendNotificationUplinkMsg)); + } + + private ListenableFuture submitEdgeSend(TenantId tenantId, Edge edge, String what, EdgeSendTask task) { + log.trace("[{}] processing edge-delegated {} send [{}]", tenantId, what, edge.getName()); dbCallbackExecutorService.submit(() -> { try { - sendNotificationForEdge(tenantId, sendNotificationUplinkMsg); + task.execute(); } catch (Exception e) { - log.warn("[{}] Failed to send notification requested by edge [{}]", tenantId, edge.getName(), e); + log.warn("[{}] Failed to send {} requested by edge [{}]", tenantId, what, edge.getName(), e); } return null; }); @@ -614,4 +600,9 @@ public class DefaultEdgeRequestsService implements EdgeRequestsService { return edgeEventService.saveAsync(edgeEvent); } + @FunctionalInterface + private interface EdgeSendTask { + void execute() throws Exception; + } + } diff --git a/application/src/test/java/org/thingsboard/server/edge/AbstractEdgeTest.java b/application/src/test/java/org/thingsboard/server/edge/AbstractEdgeTest.java index 9c0bb682b2..c062e49a17 100644 --- a/application/src/test/java/org/thingsboard/server/edge/AbstractEdgeTest.java +++ b/application/src/test/java/org/thingsboard/server/edge/AbstractEdgeTest.java @@ -36,6 +36,7 @@ import org.thingsboard.server.common.data.Customer; import org.thingsboard.server.common.data.Dashboard; import org.thingsboard.server.common.data.DataConstants; import org.thingsboard.server.common.data.Device; +import org.thingsboard.server.common.data.EdgeUtils; import org.thingsboard.server.common.data.DeviceInfo; import org.thingsboard.server.common.data.DeviceProfile; import org.thingsboard.server.common.data.OtaPackageInfo; @@ -99,6 +100,7 @@ import org.thingsboard.server.gen.edge.v1.RuleChainUpdateMsg; import org.thingsboard.server.gen.edge.v1.SyncCompletedMsg; import org.thingsboard.server.gen.edge.v1.TenantProfileUpdateMsg; import org.thingsboard.server.gen.edge.v1.TenantUpdateMsg; +import org.thingsboard.server.gen.edge.v1.UplinkMsg; import org.thingsboard.server.gen.edge.v1.UpdateMsgType; import org.thingsboard.server.gen.edge.v1.UserCredentialsUpdateMsg; import org.thingsboard.server.gen.edge.v1.UserUpdateMsg; @@ -109,6 +111,7 @@ import java.util.Optional; import java.util.TreeMap; import java.util.UUID; import java.util.concurrent.TimeUnit; +import java.util.function.Consumer; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; @@ -141,6 +144,16 @@ abstract public class AbstractEdgeTest extends AbstractControllerTest { @Autowired protected EdgeEventService edgeEventService; + protected void sendUplinkMsgAndWaitForResponse(Consumer customizer) throws Exception { + UplinkMsg.Builder uplinkMsgBuilder = UplinkMsg.newBuilder(); + uplinkMsgBuilder.setUplinkMsgId(EdgeUtils.nextPositiveInt()); + customizer.accept(uplinkMsgBuilder); + + edgeImitator.expectResponsesAmount(1); + edgeImitator.sendUplinkMsg(uplinkMsgBuilder.build()); + Assert.assertTrue(edgeImitator.waitForResponses()); + } + @Before public void setupEdgeTest() throws Exception { loginSysAdmin(); diff --git a/application/src/test/java/org/thingsboard/server/edge/SendEmailEdgeTest.java b/application/src/test/java/org/thingsboard/server/edge/SendEmailEdgeTest.java index 89e31c38c7..edab6722ac 100644 --- a/application/src/test/java/org/thingsboard/server/edge/SendEmailEdgeTest.java +++ b/application/src/test/java/org/thingsboard/server/edge/SendEmailEdgeTest.java @@ -15,16 +15,16 @@ */ package org.thingsboard.server.edge; -import org.junit.Assert; +import com.fasterxml.jackson.databind.JsonNode; import org.junit.Test; import org.springframework.test.context.bean.override.mockito.MockitoBean; import org.thingsboard.common.util.JacksonUtil; import org.thingsboard.rule.engine.api.MailService; import org.thingsboard.rule.engine.api.TbEmail; -import org.thingsboard.server.common.data.EdgeUtils; +import org.thingsboard.server.common.data.ApiFeature; +import org.thingsboard.server.common.data.ApiUsageStateValue; import org.thingsboard.server.dao.service.DaoSqlTest; import org.thingsboard.server.gen.edge.v1.SendEmailUplinkMsg; -import org.thingsboard.server.gen.edge.v1.UplinkMsg; import org.thingsboard.server.service.mail.EdgeMailRequest; import static org.mockito.ArgumentMatchers.any; @@ -80,20 +80,131 @@ public class SendEmailEdgeTest extends AbstractEdgeTest { verify(mailService, timeout(30000)).send(eq(tenantId), isNull(), any(TbEmail.class)); } + @Test + public void testSendActivationEmailFromEdgeProcessedByCloud() throws Exception { + EdgeMailRequest request = EdgeMailRequest.builder() + .method(EdgeMailRequest.MailMethod.ACTIVATION) + .activationLink("http://localhost/activate?token=abc") + .ttlMs(60000L) + .to("recipient@thingsboard.io") + .build(); + + sendEmailUplink(request); + + verify(mailService, timeout(30000)) + .sendActivationEmail(eq("http://localhost/activate?token=abc"), eq(60000L), eq("recipient@thingsboard.io")); + } + + @Test + public void testSendAccountActivatedEmailFromEdgeProcessedByCloud() throws Exception { + EdgeMailRequest request = EdgeMailRequest.builder() + .method(EdgeMailRequest.MailMethod.ACCOUNT_ACTIVATED) + .loginLink("http://localhost/login") + .to("recipient@thingsboard.io") + .build(); + + sendEmailUplink(request); + + verify(mailService, timeout(30000)) + .sendAccountActivatedEmail(eq("http://localhost/login"), eq("recipient@thingsboard.io")); + } + + @Test + public void testSendResetPasswordEmailFromEdgeProcessedByCloud() throws Exception { + EdgeMailRequest request = EdgeMailRequest.builder() + .method(EdgeMailRequest.MailMethod.RESET_PASSWORD) + .passwordResetLink("http://localhost/reset?token=abc") + .ttlMs(60000L) + .to("recipient@thingsboard.io") + .build(); + + sendEmailUplink(request); + + verify(mailService, timeout(30000)) + .sendResetPasswordEmail(eq("http://localhost/reset?token=abc"), eq(60000L), eq("recipient@thingsboard.io")); + } + + @Test + public void testSendPasswordWasResetEmailFromEdgeProcessedByCloud() throws Exception { + EdgeMailRequest request = EdgeMailRequest.builder() + .method(EdgeMailRequest.MailMethod.PASSWORD_WAS_RESET) + .loginLink("http://localhost/login") + .to("recipient@thingsboard.io") + .build(); + + sendEmailUplink(request); + + verify(mailService, timeout(30000)) + .sendPasswordWasResetEmail(eq("http://localhost/login"), eq("recipient@thingsboard.io")); + } + + @Test + public void testSendTwoFaVerificationEmailFromEdgeProcessedByCloud() throws Exception { + EdgeMailRequest request = EdgeMailRequest.builder() + .method(EdgeMailRequest.MailMethod.TWO_FA) + .to("recipient@thingsboard.io") + .verificationCode("123456") + .expirationTimeSeconds(120) + .build(); + + sendEmailUplink(request); + + verify(mailService, timeout(30000)) + .sendTwoFaVerificationEmail(eq("recipient@thingsboard.io"), eq("123456"), eq(120)); + } + + @Test + public void testSendAccountLockoutEmailFromEdgeProcessedByCloud() throws Exception { + EdgeMailRequest request = EdgeMailRequest.builder() + .method(EdgeMailRequest.MailMethod.ACCOUNT_LOCKOUT) + .lockoutEmail("locked@thingsboard.io") + .to("recipient@thingsboard.io") + .maxFailedLoginAttempts(5) + .build(); + + sendEmailUplink(request); + + verify(mailService, timeout(30000)) + .sendAccountLockoutEmail(eq("locked@thingsboard.io"), eq("recipient@thingsboard.io"), eq(5)); + } + + @Test + public void testSendApiUsageStateEmailFromEdgeProcessedByCloud() throws Exception { + EdgeMailRequest request = EdgeMailRequest.builder() + .method(EdgeMailRequest.MailMethod.API_USAGE_STATE) + .apiFeature(ApiFeature.EMAIL) + .stateValue(ApiUsageStateValue.DISABLED) + .to("recipient@thingsboard.io") + .build(); + + sendEmailUplink(request); + + verify(mailService, timeout(30000)) + .sendApiFeatureStateEmail(eq(ApiFeature.EMAIL), eq(ApiUsageStateValue.DISABLED), eq("recipient@thingsboard.io"), isNull()); + } + + @Test + public void testSendTestMailFromEdgeProcessedByCloud() throws Exception { + JsonNode testConfig = JacksonUtil.newObjectNode().put("smtpHost", "localhost"); + EdgeMailRequest request = EdgeMailRequest.builder() + .method(EdgeMailRequest.MailMethod.TEST_MAIL) + .testConfig(testConfig) + .to("recipient@thingsboard.io") + .build(); + + sendEmailUplink(request); + + verify(mailService, timeout(30000)) + .sendTestMail(any(JsonNode.class), eq("recipient@thingsboard.io")); + } + private void sendEmailUplink(EdgeMailRequest request) throws Exception { SendEmailUplinkMsg sendEmailUplinkMsg = SendEmailUplinkMsg.newBuilder() .setTenantIdMSB(tenantId.getId().getMostSignificantBits()) .setTenantIdLSB(tenantId.getId().getLeastSignificantBits()) .setRequest(JacksonUtil.toString(request)) .build(); - - UplinkMsg.Builder uplinkMsgBuilder = UplinkMsg.newBuilder(); - uplinkMsgBuilder.setUplinkMsgId(EdgeUtils.nextPositiveInt()); - uplinkMsgBuilder.addSendEmailUplinkMsg(sendEmailUplinkMsg); - - edgeImitator.expectResponsesAmount(1); - edgeImitator.sendUplinkMsg(uplinkMsgBuilder.build()); - Assert.assertTrue(edgeImitator.waitForResponses()); + sendUplinkMsgAndWaitForResponse(builder -> builder.addSendEmailUplinkMsg(sendEmailUplinkMsg)); } } diff --git a/application/src/test/java/org/thingsboard/server/edge/SendNotificationEdgeTest.java b/application/src/test/java/org/thingsboard/server/edge/SendNotificationEdgeTest.java index 3c8802f07e..362b7a6403 100644 --- a/application/src/test/java/org/thingsboard/server/edge/SendNotificationEdgeTest.java +++ b/application/src/test/java/org/thingsboard/server/edge/SendNotificationEdgeTest.java @@ -15,14 +15,12 @@ */ package org.thingsboard.server.edge; -import org.junit.Assert; import org.junit.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.bean.override.mockito.MockitoBean; import org.thingsboard.common.util.JacksonUtil; import org.thingsboard.rule.engine.api.notification.FirebaseService; import org.thingsboard.rule.engine.api.notification.SlackService; -import org.thingsboard.server.common.data.EdgeUtils; import org.thingsboard.server.common.data.id.TenantId; import org.thingsboard.server.common.data.notification.NotificationDeliveryMethod; import org.thingsboard.server.common.data.notification.settings.MobileAppNotificationDeliveryMethodConfig; @@ -32,7 +30,6 @@ import org.thingsboard.server.common.data.notification.settings.SlackNotificatio import org.thingsboard.server.dao.notification.NotificationSettingsService; import org.thingsboard.server.dao.service.DaoSqlTest; import org.thingsboard.server.gen.edge.v1.SendNotificationUplinkMsg; -import org.thingsboard.server.gen.edge.v1.UplinkMsg; import org.thingsboard.server.service.notification.EdgeNotificationRequest; import java.util.HashMap; @@ -121,14 +118,7 @@ public class SendNotificationEdgeTest extends AbstractEdgeTest { .setTenantIdLSB(tenantId.getId().getLeastSignificantBits()) .setRequest(JacksonUtil.toString(request)) .build(); - - UplinkMsg.Builder uplinkMsgBuilder = UplinkMsg.newBuilder(); - uplinkMsgBuilder.setUplinkMsgId(EdgeUtils.nextPositiveInt()); - uplinkMsgBuilder.addSendNotificationUplinkMsg(sendNotificationUplinkMsg); - - edgeImitator.expectResponsesAmount(1); - edgeImitator.sendUplinkMsg(uplinkMsgBuilder.build()); - Assert.assertTrue(edgeImitator.waitForResponses()); + sendUplinkMsgAndWaitForResponse(builder -> builder.addSendNotificationUplinkMsg(sendNotificationUplinkMsg)); } } diff --git a/application/src/test/java/org/thingsboard/server/edge/SmsEdgeTest.java b/application/src/test/java/org/thingsboard/server/edge/SendSmsEdgeTest.java similarity index 85% rename from application/src/test/java/org/thingsboard/server/edge/SmsEdgeTest.java rename to application/src/test/java/org/thingsboard/server/edge/SendSmsEdgeTest.java index e8decbe7d2..190a973481 100644 --- a/application/src/test/java/org/thingsboard/server/edge/SmsEdgeTest.java +++ b/application/src/test/java/org/thingsboard/server/edge/SendSmsEdgeTest.java @@ -15,16 +15,13 @@ */ package org.thingsboard.server.edge; -import org.junit.Assert; import org.junit.Test; import org.springframework.test.context.bean.override.mockito.MockitoBean; import org.thingsboard.common.util.JacksonUtil; import org.thingsboard.rule.engine.api.SmsService; -import org.thingsboard.server.common.data.EdgeUtils; import org.thingsboard.server.common.data.sms.config.TestSmsRequest; import org.thingsboard.server.dao.service.DaoSqlTest; import org.thingsboard.server.gen.edge.v1.SendSmsUplinkMsg; -import org.thingsboard.server.gen.edge.v1.UplinkMsg; import org.thingsboard.server.service.sms.EdgeSmsRequest; import static org.mockito.ArgumentMatchers.any; @@ -41,7 +38,7 @@ import static org.mockito.Mockito.verify; * connected edge). */ @DaoSqlTest -public class SmsEdgeTest extends AbstractEdgeTest { +public class SendSmsEdgeTest extends AbstractEdgeTest { @MockitoBean private SmsService smsService; @@ -81,14 +78,7 @@ public class SmsEdgeTest extends AbstractEdgeTest { .setTenantIdLSB(tenantId.getId().getLeastSignificantBits()) .setRequest(JacksonUtil.toString(request)) .build(); - - UplinkMsg.Builder uplinkMsgBuilder = UplinkMsg.newBuilder(); - uplinkMsgBuilder.setUplinkMsgId(EdgeUtils.nextPositiveInt()); - uplinkMsgBuilder.addSendSmsUplinkMsg(sendSmsUplinkMsg); - - edgeImitator.expectResponsesAmount(1); - edgeImitator.sendUplinkMsg(uplinkMsgBuilder.build()); - Assert.assertTrue(edgeImitator.waitForResponses()); + sendUplinkMsgAndWaitForResponse(builder -> builder.addSendSmsUplinkMsg(sendSmsUplinkMsg)); } } diff --git a/application/src/test/java/org/thingsboard/server/service/edge/rpc/processor/settings/AdminSettingsEdgeProcessorTest.java b/application/src/test/java/org/thingsboard/server/service/edge/rpc/processor/settings/AdminSettingsEdgeProcessorTest.java new file mode 100644 index 0000000000..e3453ea618 --- /dev/null +++ b/application/src/test/java/org/thingsboard/server/service/edge/rpc/processor/settings/AdminSettingsEdgeProcessorTest.java @@ -0,0 +1,163 @@ +/** + * Copyright © 2016-2026 The Thingsboard Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.thingsboard.server.service.edge.rpc.processor.settings; + +import com.fasterxml.jackson.databind.JsonNode; +import org.junit.jupiter.api.Assertions; +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.springframework.test.util.ReflectionTestUtils; +import org.thingsboard.common.util.JacksonUtil; +import org.thingsboard.server.common.data.AdminSettings; +import org.thingsboard.server.common.data.edge.Edge; +import org.thingsboard.server.common.data.edge.EdgeEvent; +import org.thingsboard.server.common.data.id.AdminSettingsId; +import org.thingsboard.server.common.data.id.EdgeId; +import org.thingsboard.server.common.data.id.TenantId; +import org.thingsboard.server.common.data.page.PageData; +import org.thingsboard.server.dao.settings.AdminSettingsService; +import org.thingsboard.server.gen.edge.v1.DownlinkMsg; +import org.thingsboard.server.gen.edge.v1.EdgeVersion; +import org.thingsboard.server.service.edge.EdgeContextComponent; + +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.UUID; +import java.util.stream.Collectors; + +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.lenient; +import static org.mockito.Mockito.when; + +@ExtendWith(MockitoExtension.class) +public class AdminSettingsEdgeProcessorTest { + + @Mock + private EdgeContextComponent edgeCtx; + @Mock + private AdminSettingsService adminSettingsService; + + private final TenantId tenantId = new TenantId(UUID.randomUUID()); + private AdminSettingsEdgeProcessor processor; + + @BeforeEach + public void setUp() { + processor = new AdminSettingsEdgeProcessor(); + ReflectionTestUtils.setField(processor, "edgeCtx", edgeCtx); + ReflectionTestUtils.setField(processor, "tokenExpirationTime", 9000); + ReflectionTestUtils.setField(processor, "refreshTokenExpTime", 604800); + ReflectionTestUtils.setField(processor, "tokenIssuer", "thingsboard.io"); + lenient().when(edgeCtx.getAdminSettingsService()).thenReturn(adminSettingsService); + } + + @Test + public void testTenantScopedAllowListedKeyIsSyncedToEdge() { + AdminSettings general = adminSettings(tenantId, "general"); + when(adminSettingsService.findAdminSettingsById(any(), any())).thenReturn(general); + + DownlinkMsg downlink = processor.convertEdgeEventToDownlink(edgeEvent(tenantId), EdgeVersion.V_4_2_2_4); + + Assertions.assertNotNull(downlink); + Assertions.assertEquals(1, downlink.getAdminSettingsUpdateMsgCount()); + AdminSettings synced = JacksonUtil.fromString(downlink.getAdminSettingsUpdateMsg(0).getEntity(), AdminSettings.class, true); + Assertions.assertNotNull(synced); + Assertions.assertEquals("general", synced.getKey()); + } + + @Test + public void testTenantScopedNonAllowListedKeyIsNotSyncedToEdge() { + AdminSettings mail = adminSettings(tenantId, "mail"); + when(adminSettingsService.findAdminSettingsById(any(), any())).thenReturn(mail); + + DownlinkMsg downlink = processor.convertEdgeEventToDownlink(edgeEvent(tenantId), EdgeVersion.V_4_2_2_4); + + Assertions.assertNull(downlink); + } + + @Test + public void testSystemScopedAllowListedKeyIsNotSyncedToEdge() { + AdminSettings general = adminSettings(TenantId.SYS_TENANT_ID, "general"); + when(adminSettingsService.findAdminSettingsById(any(), any())).thenReturn(general); + + DownlinkMsg downlink = processor.convertEdgeEventToDownlink(edgeEvent(TenantId.SYS_TENANT_ID), EdgeVersion.V_4_2_2_4); + + Assertions.assertNull(downlink); + } + + @Test + public void testCleanupClearsSecretsAndSkipsAllowListedKeys() { + Edge edge = new Edge(); + edge.setId(new EdgeId(UUID.randomUUID())); + edge.setTenantId(tenantId); + + when(adminSettingsService.findAllByTenantId(eq(TenantId.SYS_TENANT_ID), any())) + .thenReturn(page(adminSettings(TenantId.SYS_TENANT_ID, "mail"), + adminSettings(TenantId.SYS_TENANT_ID, "jwt"), + adminSettings(TenantId.SYS_TENANT_ID, "general"))); + when(adminSettingsService.findAllByTenantId(eq(tenantId), any())) + .thenReturn(page(adminSettings(tenantId, "sms"), + adminSettings(tenantId, "connectivity"))); + + List downlinks = processor.convertAdminSettingsCleanupToDownlinks(edge); + + Map cleanupByKey = downlinks.stream() + .map(d -> JacksonUtil.fromString(d.getAdminSettingsUpdateMsg(0).getEntity(), AdminSettings.class, true)) + .collect(Collectors.toMap(AdminSettings::getKey, s -> s)); + + // Allow-listed keys (general/connectivity) are never wiped; every other key is. + Assertions.assertEquals(Set.of("mail", "jwt", "sms"), cleanupByKey.keySet()); + + // Mail secrets are blanked. + JsonNode mailValue = cleanupByKey.get("mail").getJsonValue(); + Assertions.assertEquals("", mailValue.get("password").asText()); + Assertions.assertEquals("", mailValue.get("refreshToken").asText()); + + // JWT signing key is re-randomized to a non-empty value. + JsonNode jwtValue = cleanupByKey.get("jwt").getJsonValue(); + Assertions.assertFalse(jwtValue.get("tokenSigningKey").asText().isEmpty()); + + // Other non-allow-listed keys are wiped to an empty object. + Assertions.assertTrue(cleanupByKey.get("sms").getJsonValue().isEmpty()); + } + + private EdgeEvent edgeEvent(TenantId eventTenantId) { + EdgeEvent edgeEvent = new EdgeEvent(); + edgeEvent.setTenantId(eventTenantId); + edgeEvent.setEdgeId(new EdgeId(UUID.randomUUID())); + edgeEvent.setEntityId(UUID.randomUUID()); + return edgeEvent; + } + + private AdminSettings adminSettings(TenantId settingsTenantId, String key) { + AdminSettings adminSettings = new AdminSettings(); + adminSettings.setId(new AdminSettingsId(UUID.randomUUID())); + adminSettings.setTenantId(settingsTenantId); + adminSettings.setKey(key); + adminSettings.setJsonValue(JacksonUtil.newObjectNode()); + return adminSettings; + } + + private PageData page(AdminSettings... settings) { + List data = List.of(settings); + return new PageData<>(data, 1, data.size(), false); + } + +} diff --git a/common/edge-api/src/main/proto/edge.proto b/common/edge-api/src/main/proto/edge.proto index 50a02da5d5..350a1b1cb4 100644 --- a/common/edge-api/src/main/proto/edge.proto +++ b/common/edge-api/src/main/proto/edge.proto @@ -347,6 +347,10 @@ message CalculatedFieldRequestMsg { string entityType = 3; } +// Edge-delegated send requests (mail/sms/notification). The Cloud always resolves the tenant from the +// authenticated edge session (edge.getTenantId()) and ignores tenantIdMSB/tenantIdLSB below - they are kept +// only for symmetry with other uplink messages and must not be treated as authoritative by the receiver. +// 'request' is the JSON-serialized Edge{Mail,Sms,Notification}Request payload. message SendEmailUplinkMsg { int64 tenantIdMSB = 1; int64 tenantIdLSB = 2; From 964b1628649270ade4907ad52d6c1f01bc909e44 Mon Sep 17 00:00:00 2001 From: Nikita Mazurenko Date: Fri, 17 Jul 2026 18:19:17 +0300 Subject: [PATCH 05/16] Remove leftover SmsEdgeTest duplicated by SendSmsEdgeTest rename SmsEdgeTest was renamed to SendSmsEdgeTest but the old file was left behind on this branch, duplicating the SMS uplink tests. --- .../thingsboard/server/edge/SmsEdgeTest.java | 94 ------------------- 1 file changed, 94 deletions(-) delete mode 100644 application/src/test/java/org/thingsboard/server/edge/SmsEdgeTest.java diff --git a/application/src/test/java/org/thingsboard/server/edge/SmsEdgeTest.java b/application/src/test/java/org/thingsboard/server/edge/SmsEdgeTest.java deleted file mode 100644 index e8decbe7d2..0000000000 --- a/application/src/test/java/org/thingsboard/server/edge/SmsEdgeTest.java +++ /dev/null @@ -1,94 +0,0 @@ -/** - * Copyright © 2016-2026 The Thingsboard Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.thingsboard.server.edge; - -import org.junit.Assert; -import org.junit.Test; -import org.springframework.test.context.bean.override.mockito.MockitoBean; -import org.thingsboard.common.util.JacksonUtil; -import org.thingsboard.rule.engine.api.SmsService; -import org.thingsboard.server.common.data.EdgeUtils; -import org.thingsboard.server.common.data.sms.config.TestSmsRequest; -import org.thingsboard.server.dao.service.DaoSqlTest; -import org.thingsboard.server.gen.edge.v1.SendSmsUplinkMsg; -import org.thingsboard.server.gen.edge.v1.UplinkMsg; -import org.thingsboard.server.service.sms.EdgeSmsRequest; - -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.eq; -import static org.mockito.ArgumentMatchers.isNull; -import static org.mockito.Mockito.timeout; -import static org.mockito.Mockito.verify; - -/** - * Verifies the send-sms uplink: when the Edge delegates an SMS send, the Cloud receives the - * SendSmsUplinkMsg and invokes its SmsService (which resolves the config and transmits). Here the - * EdgeImitator plays the Edge and sends the uplink; the Cloud's SmsService is mocked so we can assert the - * delegated call arrives with the expected arguments (the Cloud, not the Edge, uses the tenant id of the - * connected edge). - */ -@DaoSqlTest -public class SmsEdgeTest extends AbstractEdgeTest { - - @MockitoBean - private SmsService smsService; - - @Test - public void testSendSmsFromEdgeProcessedByCloud() throws Exception { - EdgeSmsRequest request = EdgeSmsRequest.builder() - .method(EdgeSmsRequest.SmsMethod.SEND_SMS) - .numbers(new String[]{"+15551234567"}) - .message("Edge test message") - .build(); - - sendSmsUplink(request); - - verify(smsService, timeout(30000)) - .sendSms(eq(tenantId), isNull(), any(String[].class), eq("Edge test message")); - } - - @Test - public void testSendTestSmsFromEdgeProcessedByCloud() throws Exception { - TestSmsRequest testSmsRequest = new TestSmsRequest(); - testSmsRequest.setNumberTo("+15551234567"); - testSmsRequest.setMessage("Test message"); - EdgeSmsRequest request = EdgeSmsRequest.builder() - .method(EdgeSmsRequest.SmsMethod.SEND_TEST_SMS) - .testSmsRequest(testSmsRequest) - .build(); - - sendSmsUplink(request); - - verify(smsService, timeout(30000)).sendTestSms(any(TestSmsRequest.class)); - } - - private void sendSmsUplink(EdgeSmsRequest request) throws Exception { - SendSmsUplinkMsg sendSmsUplinkMsg = SendSmsUplinkMsg.newBuilder() - .setTenantIdMSB(tenantId.getId().getMostSignificantBits()) - .setTenantIdLSB(tenantId.getId().getLeastSignificantBits()) - .setRequest(JacksonUtil.toString(request)) - .build(); - - UplinkMsg.Builder uplinkMsgBuilder = UplinkMsg.newBuilder(); - uplinkMsgBuilder.setUplinkMsgId(EdgeUtils.nextPositiveInt()); - uplinkMsgBuilder.addSendSmsUplinkMsg(sendSmsUplinkMsg); - - edgeImitator.expectResponsesAmount(1); - edgeImitator.sendUplinkMsg(uplinkMsgBuilder.build()); - Assert.assertTrue(edgeImitator.waitForResponses()); - } - -} From 0bc8ce0f8e2257e6bbab1358e1476156d3180897 Mon Sep 17 00:00:00 2001 From: Nikita Mazurenko Date: Fri, 11 Sep 2026 16:15:22 +0300 Subject: [PATCH 06/16] Adopt SPDX license headers in newly added files --- .../server/service/mail/EdgeMailRequest.java | 17 ++--------------- .../notification/EdgeNotificationRequest.java | 17 ++--------------- .../server/service/sms/EdgeSmsRequest.java | 17 ++--------------- .../server/edge/SendEmailEdgeTest.java | 17 ++--------------- .../server/edge/SendNotificationEdgeTest.java | 17 ++--------------- .../server/edge/SendSmsEdgeTest.java | 17 ++--------------- .../AdminSettingsEdgeProcessorTest.java | 17 ++--------------- 7 files changed, 14 insertions(+), 105 deletions(-) diff --git a/application/src/main/java/org/thingsboard/server/service/mail/EdgeMailRequest.java b/application/src/main/java/org/thingsboard/server/service/mail/EdgeMailRequest.java index 733f824b0e..2f2c020ab4 100644 --- a/application/src/main/java/org/thingsboard/server/service/mail/EdgeMailRequest.java +++ b/application/src/main/java/org/thingsboard/server/service/mail/EdgeMailRequest.java @@ -1,18 +1,5 @@ -/** - * Copyright © 2016-2026 The Thingsboard Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ +// SPDX-FileCopyrightText: Copyright The Thingsboard Authors +// SPDX-License-Identifier: Apache-2.0 package org.thingsboard.server.service.mail; import com.fasterxml.jackson.annotation.JsonInclude; diff --git a/application/src/main/java/org/thingsboard/server/service/notification/EdgeNotificationRequest.java b/application/src/main/java/org/thingsboard/server/service/notification/EdgeNotificationRequest.java index b135c574e8..50a06aad49 100644 --- a/application/src/main/java/org/thingsboard/server/service/notification/EdgeNotificationRequest.java +++ b/application/src/main/java/org/thingsboard/server/service/notification/EdgeNotificationRequest.java @@ -1,18 +1,5 @@ -/** - * Copyright © 2016-2026 The Thingsboard Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ +// SPDX-FileCopyrightText: Copyright The Thingsboard Authors +// SPDX-License-Identifier: Apache-2.0 package org.thingsboard.server.service.notification; import com.fasterxml.jackson.annotation.JsonInclude; diff --git a/application/src/main/java/org/thingsboard/server/service/sms/EdgeSmsRequest.java b/application/src/main/java/org/thingsboard/server/service/sms/EdgeSmsRequest.java index 649b8a5a85..c3696b21be 100644 --- a/application/src/main/java/org/thingsboard/server/service/sms/EdgeSmsRequest.java +++ b/application/src/main/java/org/thingsboard/server/service/sms/EdgeSmsRequest.java @@ -1,18 +1,5 @@ -/** - * Copyright © 2016-2026 The Thingsboard Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ +// SPDX-FileCopyrightText: Copyright The Thingsboard Authors +// SPDX-License-Identifier: Apache-2.0 package org.thingsboard.server.service.sms; import com.fasterxml.jackson.annotation.JsonInclude; diff --git a/application/src/test/java/org/thingsboard/server/edge/SendEmailEdgeTest.java b/application/src/test/java/org/thingsboard/server/edge/SendEmailEdgeTest.java index edab6722ac..d8c35b1676 100644 --- a/application/src/test/java/org/thingsboard/server/edge/SendEmailEdgeTest.java +++ b/application/src/test/java/org/thingsboard/server/edge/SendEmailEdgeTest.java @@ -1,18 +1,5 @@ -/** - * Copyright © 2016-2026 The Thingsboard Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ +// SPDX-FileCopyrightText: Copyright The Thingsboard Authors +// SPDX-License-Identifier: Apache-2.0 package org.thingsboard.server.edge; import com.fasterxml.jackson.databind.JsonNode; diff --git a/application/src/test/java/org/thingsboard/server/edge/SendNotificationEdgeTest.java b/application/src/test/java/org/thingsboard/server/edge/SendNotificationEdgeTest.java index 362b7a6403..8787bcde19 100644 --- a/application/src/test/java/org/thingsboard/server/edge/SendNotificationEdgeTest.java +++ b/application/src/test/java/org/thingsboard/server/edge/SendNotificationEdgeTest.java @@ -1,18 +1,5 @@ -/** - * Copyright © 2016-2026 The Thingsboard Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ +// SPDX-FileCopyrightText: Copyright The Thingsboard Authors +// SPDX-License-Identifier: Apache-2.0 package org.thingsboard.server.edge; import org.junit.Test; diff --git a/application/src/test/java/org/thingsboard/server/edge/SendSmsEdgeTest.java b/application/src/test/java/org/thingsboard/server/edge/SendSmsEdgeTest.java index 190a973481..408bbfc43d 100644 --- a/application/src/test/java/org/thingsboard/server/edge/SendSmsEdgeTest.java +++ b/application/src/test/java/org/thingsboard/server/edge/SendSmsEdgeTest.java @@ -1,18 +1,5 @@ -/** - * Copyright © 2016-2026 The Thingsboard Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ +// SPDX-FileCopyrightText: Copyright The Thingsboard Authors +// SPDX-License-Identifier: Apache-2.0 package org.thingsboard.server.edge; import org.junit.Test; diff --git a/application/src/test/java/org/thingsboard/server/service/edge/rpc/processor/settings/AdminSettingsEdgeProcessorTest.java b/application/src/test/java/org/thingsboard/server/service/edge/rpc/processor/settings/AdminSettingsEdgeProcessorTest.java index e3453ea618..9a9d0a9ca8 100644 --- a/application/src/test/java/org/thingsboard/server/service/edge/rpc/processor/settings/AdminSettingsEdgeProcessorTest.java +++ b/application/src/test/java/org/thingsboard/server/service/edge/rpc/processor/settings/AdminSettingsEdgeProcessorTest.java @@ -1,18 +1,5 @@ -/** - * Copyright © 2016-2026 The Thingsboard Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ +// SPDX-FileCopyrightText: Copyright The Thingsboard Authors +// SPDX-License-Identifier: Apache-2.0 package org.thingsboard.server.service.edge.rpc.processor.settings; import com.fasterxml.jackson.databind.JsonNode; From 8959c6d40e1df1330dd889ee30db6c1a7cbb51ec Mon Sep 17 00:00:00 2001 From: Nikita Mazurenko Date: Fri, 11 Sep 2026 16:15:23 +0300 Subject: [PATCH 07/16] Adopt SPDX license headers in newly added files --- .../server/service/mail/EdgeMailRequest.java | 17 ++--------------- .../notification/EdgeNotificationRequest.java | 17 ++--------------- .../server/service/sms/EdgeSmsRequest.java | 17 ++--------------- .../server/edge/SendEmailEdgeTest.java | 17 ++--------------- .../server/edge/SendNotificationEdgeTest.java | 17 ++--------------- .../server/edge/SendSmsEdgeTest.java | 17 ++--------------- .../AdminSettingsEdgeProcessorTest.java | 17 ++--------------- 7 files changed, 14 insertions(+), 105 deletions(-) diff --git a/application/src/main/java/org/thingsboard/server/service/mail/EdgeMailRequest.java b/application/src/main/java/org/thingsboard/server/service/mail/EdgeMailRequest.java index 733f824b0e..2f2c020ab4 100644 --- a/application/src/main/java/org/thingsboard/server/service/mail/EdgeMailRequest.java +++ b/application/src/main/java/org/thingsboard/server/service/mail/EdgeMailRequest.java @@ -1,18 +1,5 @@ -/** - * Copyright © 2016-2026 The Thingsboard Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ +// SPDX-FileCopyrightText: Copyright The Thingsboard Authors +// SPDX-License-Identifier: Apache-2.0 package org.thingsboard.server.service.mail; import com.fasterxml.jackson.annotation.JsonInclude; diff --git a/application/src/main/java/org/thingsboard/server/service/notification/EdgeNotificationRequest.java b/application/src/main/java/org/thingsboard/server/service/notification/EdgeNotificationRequest.java index b135c574e8..50a06aad49 100644 --- a/application/src/main/java/org/thingsboard/server/service/notification/EdgeNotificationRequest.java +++ b/application/src/main/java/org/thingsboard/server/service/notification/EdgeNotificationRequest.java @@ -1,18 +1,5 @@ -/** - * Copyright © 2016-2026 The Thingsboard Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ +// SPDX-FileCopyrightText: Copyright The Thingsboard Authors +// SPDX-License-Identifier: Apache-2.0 package org.thingsboard.server.service.notification; import com.fasterxml.jackson.annotation.JsonInclude; diff --git a/application/src/main/java/org/thingsboard/server/service/sms/EdgeSmsRequest.java b/application/src/main/java/org/thingsboard/server/service/sms/EdgeSmsRequest.java index 649b8a5a85..c3696b21be 100644 --- a/application/src/main/java/org/thingsboard/server/service/sms/EdgeSmsRequest.java +++ b/application/src/main/java/org/thingsboard/server/service/sms/EdgeSmsRequest.java @@ -1,18 +1,5 @@ -/** - * Copyright © 2016-2026 The Thingsboard Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ +// SPDX-FileCopyrightText: Copyright The Thingsboard Authors +// SPDX-License-Identifier: Apache-2.0 package org.thingsboard.server.service.sms; import com.fasterxml.jackson.annotation.JsonInclude; diff --git a/application/src/test/java/org/thingsboard/server/edge/SendEmailEdgeTest.java b/application/src/test/java/org/thingsboard/server/edge/SendEmailEdgeTest.java index edab6722ac..d8c35b1676 100644 --- a/application/src/test/java/org/thingsboard/server/edge/SendEmailEdgeTest.java +++ b/application/src/test/java/org/thingsboard/server/edge/SendEmailEdgeTest.java @@ -1,18 +1,5 @@ -/** - * Copyright © 2016-2026 The Thingsboard Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ +// SPDX-FileCopyrightText: Copyright The Thingsboard Authors +// SPDX-License-Identifier: Apache-2.0 package org.thingsboard.server.edge; import com.fasterxml.jackson.databind.JsonNode; diff --git a/application/src/test/java/org/thingsboard/server/edge/SendNotificationEdgeTest.java b/application/src/test/java/org/thingsboard/server/edge/SendNotificationEdgeTest.java index 5cfe5117f4..3d4fffd693 100644 --- a/application/src/test/java/org/thingsboard/server/edge/SendNotificationEdgeTest.java +++ b/application/src/test/java/org/thingsboard/server/edge/SendNotificationEdgeTest.java @@ -1,18 +1,5 @@ -/** - * Copyright © 2016-2026 The Thingsboard Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ +// SPDX-FileCopyrightText: Copyright The Thingsboard Authors +// SPDX-License-Identifier: Apache-2.0 package org.thingsboard.server.edge; import org.junit.Test; diff --git a/application/src/test/java/org/thingsboard/server/edge/SendSmsEdgeTest.java b/application/src/test/java/org/thingsboard/server/edge/SendSmsEdgeTest.java index 190a973481..408bbfc43d 100644 --- a/application/src/test/java/org/thingsboard/server/edge/SendSmsEdgeTest.java +++ b/application/src/test/java/org/thingsboard/server/edge/SendSmsEdgeTest.java @@ -1,18 +1,5 @@ -/** - * Copyright © 2016-2026 The Thingsboard Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ +// SPDX-FileCopyrightText: Copyright The Thingsboard Authors +// SPDX-License-Identifier: Apache-2.0 package org.thingsboard.server.edge; import org.junit.Test; diff --git a/application/src/test/java/org/thingsboard/server/service/edge/rpc/processor/settings/AdminSettingsEdgeProcessorTest.java b/application/src/test/java/org/thingsboard/server/service/edge/rpc/processor/settings/AdminSettingsEdgeProcessorTest.java index e3453ea618..9a9d0a9ca8 100644 --- a/application/src/test/java/org/thingsboard/server/service/edge/rpc/processor/settings/AdminSettingsEdgeProcessorTest.java +++ b/application/src/test/java/org/thingsboard/server/service/edge/rpc/processor/settings/AdminSettingsEdgeProcessorTest.java @@ -1,18 +1,5 @@ -/** - * Copyright © 2016-2026 The Thingsboard Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ +// SPDX-FileCopyrightText: Copyright The Thingsboard Authors +// SPDX-License-Identifier: Apache-2.0 package org.thingsboard.server.service.edge.rpc.processor.settings; import com.fasterxml.jackson.databind.JsonNode; From 0ea5f6a48f7ca13e62bd7bc981fad9430f97205b Mon Sep 17 00:00:00 2001 From: Nikita Mazurenko Date: Fri, 11 Sep 2026 16:59:48 +0300 Subject: [PATCH 08/16] Extract one-time admin settings cleanup into AdminSettingsCleanupUtils --- .../service/edge/rpc/EdgeGrpcSession.java | 59 +----------- .../rpc/utils/AdminSettingsCleanupUtils.java | 94 +++++++++++++++++++ 2 files changed, 98 insertions(+), 55 deletions(-) create mode 100644 application/src/main/java/org/thingsboard/server/service/edge/rpc/utils/AdminSettingsCleanupUtils.java diff --git a/application/src/main/java/org/thingsboard/server/service/edge/rpc/EdgeGrpcSession.java b/application/src/main/java/org/thingsboard/server/service/edge/rpc/EdgeGrpcSession.java index 71fdca3e06..e9b3a09734 100644 --- a/application/src/main/java/org/thingsboard/server/service/edge/rpc/EdgeGrpcSession.java +++ b/application/src/main/java/org/thingsboard/server/service/edge/rpc/EdgeGrpcSession.java @@ -24,7 +24,6 @@ import org.thingsboard.server.common.data.id.TenantId; import org.thingsboard.server.common.data.kv.AttributeKvEntry; import org.thingsboard.server.common.data.kv.AttributesSaveResult; import org.thingsboard.server.common.data.kv.BaseAttributeKvEntry; -import org.thingsboard.server.common.data.kv.BooleanDataEntry; import org.thingsboard.server.common.data.kv.LongDataEntry; import org.thingsboard.server.common.data.kv.StringDataEntry; import org.thingsboard.server.common.data.limit.LimitedApi; @@ -79,6 +78,7 @@ import org.thingsboard.server.service.edge.EdgeContextComponent; import org.thingsboard.server.service.edge.EdgeMsgConstructorUtils; import org.thingsboard.server.service.edge.rpc.fetch.EdgeEventFetcher; import org.thingsboard.server.service.edge.rpc.fetch.GeneralEdgeEventFetcher; +import org.thingsboard.server.service.edge.rpc.utils.AdminSettingsCleanupUtils; import org.thingsboard.server.service.edge.rpc.utils.EdgeVersionUtils; import java.io.Closeable; @@ -100,7 +100,6 @@ public abstract class EdgeGrpcSession implements Closeable { private static final String QUEUE_START_TS_ATTR_KEY = "queueStartTs"; private static final String QUEUE_START_SEQ_ID_ATTR_KEY = "queueStartSeqId"; - private static final String ADMIN_SETTINGS_CLEANUP_COMPLETED_ATTR_KEY = "adminSettingsCleanupCompleted"; private static final int MAX_DOWNLINK_ATTEMPTS = 3; private static final String RATE_LIMIT_REACHED = "Rate limit reached"; @@ -241,64 +240,14 @@ public abstract class EdgeGrpcSession implements Closeable { log.info("[{}][{}][{}] Staring edge sync process", tenantId, edge.getId(), sessionId); syncInProgress = true; interruptGeneralProcessingOnSync(); - sendOneTimeAdminSettingsCleanupIfNeeded(() -> doSync(new EdgeSyncCursor(ctx, edge, fullSync))); + AdminSettingsCleanupUtils.sendOneTimeAdminSettingsCleanupIfNeeded(ctx, edge, edgeVersion, + EdgeVersion.V_4_2_2_4, this::sendDownlinkMsgsPack, + () -> doSync(new EdgeSyncCursor(ctx, edge, fullSync))); } else { log.info("[{}][{}][{}] Sync is already started, skipping starting it now", tenantId, edge.getId(), sessionId); } } - private void sendOneTimeAdminSettingsCleanupIfNeeded(Runnable continuation) { - if (!EdgeVersionUtils.isEdgeVersionOlderThan(edgeVersion, EdgeVersion.V_4_2_2_4)) { - continuation.run(); - return; - } - try { - ListenableFuture> isCleanupCompletedAttrFuture = ctx.getAttributesService() - .find(tenantId, edge.getId(), AttributeScope.SERVER_SCOPE, ADMIN_SETTINGS_CLEANUP_COMPLETED_ATTR_KEY); - - ListenableFuture cleanupFuture = Futures.transformAsync( - isCleanupCompletedAttrFuture, - attr -> { - boolean alreadyCompleted = attr.isPresent() && attr.flatMap(AttributeKvEntry::getBooleanValue).orElse(false); - if (alreadyCompleted) { - return Futures.immediateFuture(false); - } - List cleanupMsgs = ctx.getAdminSettingsProcessor().convertAdminSettingsCleanupToDownlinks(edge); - if (cleanupMsgs.isEmpty()) { - return Futures.immediateFuture(true); - } - // send the cleanup pack; mark completed only if it was not interrupted, so it retries on next sync otherwise - return Futures.transform(sendDownlinkMsgsPack(cleanupMsgs), - isInterrupted -> !Boolean.TRUE.equals(isInterrupted), ctx.getGrpcCallbackExecutorService()); - }, ctx.getGrpcCallbackExecutorService()); - - Futures.addCallback(cleanupFuture, new FutureCallback<>() { - @Override - public void onSuccess(@Nullable Boolean markCompleted) { - if (Boolean.TRUE.equals(markCompleted)) { - markAdminSettingsCleanupCompleted(); - } - continuation.run(); - } - - @Override - public void onFailure(Throwable t) { - log.error("[{}][{}] Failed to run one-time admin settings cleanup for edge", tenantId, edge.getId(), t); - continuation.run(); - } - }, ctx.getGrpcCallbackExecutorService()); - } catch (Exception e) { - log.error("[{}][{}] Failed to start admin settings cleanup", tenantId, edge.getId(), e); - continuation.run(); - } - } - - private void markAdminSettingsCleanupCompleted() { - AttributeKvEntry attributeKvEntry = new BaseAttributeKvEntry( - new BooleanDataEntry(ADMIN_SETTINGS_CLEANUP_COMPLETED_ATTR_KEY, true), System.currentTimeMillis()); - ctx.getAttributesService().save(tenantId, edge.getId(), AttributeScope.SERVER_SCOPE, attributeKvEntry); - } - private void doSync(EdgeSyncCursor cursor) { if (cursor.hasNext()) { EdgeEventFetcher next = cursor.getNext(); diff --git a/application/src/main/java/org/thingsboard/server/service/edge/rpc/utils/AdminSettingsCleanupUtils.java b/application/src/main/java/org/thingsboard/server/service/edge/rpc/utils/AdminSettingsCleanupUtils.java new file mode 100644 index 0000000000..cd0fd2ec35 --- /dev/null +++ b/application/src/main/java/org/thingsboard/server/service/edge/rpc/utils/AdminSettingsCleanupUtils.java @@ -0,0 +1,94 @@ +// SPDX-FileCopyrightText: Copyright The Thingsboard Authors +// SPDX-License-Identifier: Apache-2.0 +package org.thingsboard.server.service.edge.rpc.utils; + +import com.google.common.util.concurrent.FutureCallback; +import com.google.common.util.concurrent.Futures; +import com.google.common.util.concurrent.ListenableFuture; +import lombok.extern.slf4j.Slf4j; +import org.checkerframework.checker.nullness.qual.Nullable; +import org.thingsboard.server.common.data.AttributeScope; +import org.thingsboard.server.common.data.edge.Edge; +import org.thingsboard.server.common.data.id.TenantId; +import org.thingsboard.server.common.data.kv.AttributeKvEntry; +import org.thingsboard.server.common.data.kv.BaseAttributeKvEntry; +import org.thingsboard.server.common.data.kv.BooleanDataEntry; +import org.thingsboard.server.gen.edge.v1.DownlinkMsg; +import org.thingsboard.server.gen.edge.v1.EdgeVersion; +import org.thingsboard.server.service.edge.EdgeContextComponent; + +import java.util.List; +import java.util.Optional; +import java.util.function.Function; + +@Slf4j +public final class AdminSettingsCleanupUtils { + + private static final String ADMIN_SETTINGS_CLEANUP_COMPLETED_ATTR_KEY = "adminSettingsCleanupCompleted"; + + /** + * Sends the one-time admin settings cleanup pack to edges that were provisioned before admin settings sync was + * removed, then runs {@code continuation}. Edges on {@code cleanupUpToVersion} or newer never received the + * settings, so they are skipped. The completion flag is stored as a server attribute on the edge, so the cleanup + * is sent once; if the pack is interrupted the flag is not set and the cleanup is retried on the next sync. + * + * @param downlinkMsgsPackSender sends a downlink pack, returning whether the send was interrupted + * @param continuation always invoked, whether or not the cleanup ran or failed + */ + public static void sendOneTimeAdminSettingsCleanupIfNeeded(EdgeContextComponent ctx, Edge edge, EdgeVersion edgeVersion, + EdgeVersion cleanupUpToVersion, + Function, ListenableFuture> downlinkMsgsPackSender, + Runnable continuation) { + if (!EdgeVersionUtils.isEdgeVersionOlderThan(edgeVersion, cleanupUpToVersion)) { + continuation.run(); + return; + } + TenantId tenantId = edge.getTenantId(); + try { + ListenableFuture> isCleanupCompletedAttrFuture = ctx.getAttributesService() + .find(tenantId, edge.getId(), AttributeScope.SERVER_SCOPE, ADMIN_SETTINGS_CLEANUP_COMPLETED_ATTR_KEY); + + ListenableFuture cleanupFuture = Futures.transformAsync( + isCleanupCompletedAttrFuture, + attr -> { + boolean alreadyCompleted = attr.isPresent() && attr.flatMap(AttributeKvEntry::getBooleanValue).orElse(false); + if (alreadyCompleted) { + return Futures.immediateFuture(false); + } + List cleanupMsgs = ctx.getAdminSettingsProcessor().convertAdminSettingsCleanupToDownlinks(edge); + if (cleanupMsgs.isEmpty()) { + return Futures.immediateFuture(true); + } + // send the cleanup pack; mark completed only if it was not interrupted, so it retries on next sync otherwise + return Futures.transform(downlinkMsgsPackSender.apply(cleanupMsgs), + isInterrupted -> !Boolean.TRUE.equals(isInterrupted), ctx.getGrpcCallbackExecutorService()); + }, ctx.getGrpcCallbackExecutorService()); + + Futures.addCallback(cleanupFuture, new FutureCallback<>() { + @Override + public void onSuccess(@Nullable Boolean markCompleted) { + if (Boolean.TRUE.equals(markCompleted)) { + markAdminSettingsCleanupCompleted(ctx, edge); + } + continuation.run(); + } + + @Override + public void onFailure(Throwable t) { + log.error("[{}][{}] Failed to run one-time admin settings cleanup for edge", tenantId, edge.getId(), t); + continuation.run(); + } + }, ctx.getGrpcCallbackExecutorService()); + } catch (Exception e) { + log.error("[{}][{}] Failed to start admin settings cleanup", tenantId, edge.getId(), e); + continuation.run(); + } + } + + private static void markAdminSettingsCleanupCompleted(EdgeContextComponent ctx, Edge edge) { + AttributeKvEntry attributeKvEntry = new BaseAttributeKvEntry( + new BooleanDataEntry(ADMIN_SETTINGS_CLEANUP_COMPLETED_ATTR_KEY, true), System.currentTimeMillis()); + ctx.getAttributesService().save(edge.getTenantId(), edge.getId(), AttributeScope.SERVER_SCOPE, attributeKvEntry); + } + +} From 405221cfb88162404417a7a3dbc29a5ba9d8fd06 Mon Sep 17 00:00:00 2001 From: Nikita Mazurenko Date: Fri, 11 Sep 2026 17:02:22 +0300 Subject: [PATCH 09/16] Extract one-time admin settings cleanup into AdminSettingsCleanupUtils --- .../service/edge/rpc/EdgeGrpcSession.java | 58 +----------- .../rpc/utils/AdminSettingsCleanupUtils.java | 94 +++++++++++++++++++ 2 files changed, 98 insertions(+), 54 deletions(-) create mode 100644 application/src/main/java/org/thingsboard/server/service/edge/rpc/utils/AdminSettingsCleanupUtils.java diff --git a/application/src/main/java/org/thingsboard/server/service/edge/rpc/EdgeGrpcSession.java b/application/src/main/java/org/thingsboard/server/service/edge/rpc/EdgeGrpcSession.java index 1299cf8e38..413de01b79 100644 --- a/application/src/main/java/org/thingsboard/server/service/edge/rpc/EdgeGrpcSession.java +++ b/application/src/main/java/org/thingsboard/server/service/edge/rpc/EdgeGrpcSession.java @@ -85,6 +85,7 @@ import org.thingsboard.server.service.edge.EdgeContextComponent; import org.thingsboard.server.service.edge.EdgeMsgConstructorUtils; import org.thingsboard.server.service.edge.rpc.fetch.EdgeEventFetcher; import org.thingsboard.server.service.edge.rpc.fetch.GeneralEdgeEventFetcher; +import org.thingsboard.server.service.edge.rpc.utils.AdminSettingsCleanupUtils; import org.thingsboard.server.service.edge.rpc.utils.EdgeVersionUtils; import java.io.Closeable; @@ -107,7 +108,6 @@ public abstract class EdgeGrpcSession implements Closeable { private static final String QUEUE_START_TS_ATTR_KEY = "queueStartTs"; private static final String QUEUE_START_SEQ_ID_ATTR_KEY = "queueStartSeqId"; - private static final String ADMIN_SETTINGS_CLEANUP_COMPLETED_ATTR_KEY = "adminSettingsCleanupCompleted"; private static final int MAX_DOWNLINK_ATTEMPTS = 3; private static final String RATE_LIMIT_REACHED = "Rate limit reached"; @@ -255,64 +255,14 @@ public abstract class EdgeGrpcSession implements Closeable { log.info("[{}][{}][{}] Staring edge sync process", tenantId, edge.getId(), sessionId); updateSyncInProgress(true); interruptGeneralProcessingOnSync(); - sendOneTimeAdminSettingsCleanupIfNeeded(() -> doSync(new EdgeSyncCursor(ctx, edge, fullSync))); + AdminSettingsCleanupUtils.sendOneTimeAdminSettingsCleanupIfNeeded(ctx, edge, edgeVersion, + EdgeVersion.V_4_3_1_4, this::sendDownlinkMsgsPack, + () -> doSync(new EdgeSyncCursor(ctx, edge, fullSync))); } else { log.info("[{}][{}][{}] Sync is already started, skipping starting it now", tenantId, edge.getId(), sessionId); } } - private void sendOneTimeAdminSettingsCleanupIfNeeded(Runnable continuation) { - if (!EdgeVersionUtils.isEdgeVersionOlderThan(edgeVersion, EdgeVersion.V_4_3_1_4)) { - continuation.run(); - return; - } - try { - ListenableFuture> isCleanupCompletedAttrFuture = ctx.getAttributesService() - .find(tenantId, edge.getId(), AttributeScope.SERVER_SCOPE, ADMIN_SETTINGS_CLEANUP_COMPLETED_ATTR_KEY); - - ListenableFuture cleanupFuture = Futures.transformAsync( - isCleanupCompletedAttrFuture, - attr -> { - boolean alreadyCompleted = attr.isPresent() && attr.flatMap(AttributeKvEntry::getBooleanValue).orElse(false); - if (alreadyCompleted) { - return Futures.immediateFuture(false); - } - List cleanupMsgs = ctx.getAdminSettingsProcessor().convertAdminSettingsCleanupToDownlinks(edge); - if (cleanupMsgs.isEmpty()) { - return Futures.immediateFuture(true); - } - // send the cleanup pack; mark completed only if it was not interrupted, so it retries on next sync otherwise - return Futures.transform(sendDownlinkMsgsPack(cleanupMsgs), - isInterrupted -> !Boolean.TRUE.equals(isInterrupted), ctx.getGrpcCallbackExecutorService()); - }, ctx.getGrpcCallbackExecutorService()); - - Futures.addCallback(cleanupFuture, new FutureCallback<>() { - @Override - public void onSuccess(@Nullable Boolean markCompleted) { - if (Boolean.TRUE.equals(markCompleted)) { - markAdminSettingsCleanupCompleted(); - } - continuation.run(); - } - - @Override - public void onFailure(Throwable t) { - log.error("[{}][{}] Failed to run one-time admin settings cleanup for edge", tenantId, edge.getId(), t); - continuation.run(); - } - }, ctx.getGrpcCallbackExecutorService()); - } catch (Exception e) { - log.error("[{}][{}] Failed to start admin settings cleanup", tenantId, edge.getId(), e); - continuation.run(); - } - } - - private void markAdminSettingsCleanupCompleted() { - AttributeKvEntry attributeKvEntry = new BaseAttributeKvEntry( - new BooleanDataEntry(ADMIN_SETTINGS_CLEANUP_COMPLETED_ATTR_KEY, true), System.currentTimeMillis()); - ctx.getAttributesService().save(tenantId, edge.getId(), AttributeScope.SERVER_SCOPE, attributeKvEntry); - } - private void doSync(EdgeSyncCursor cursor) { if (cursor.hasNext()) { EdgeEventFetcher next = cursor.getNext(); diff --git a/application/src/main/java/org/thingsboard/server/service/edge/rpc/utils/AdminSettingsCleanupUtils.java b/application/src/main/java/org/thingsboard/server/service/edge/rpc/utils/AdminSettingsCleanupUtils.java new file mode 100644 index 0000000000..cd0fd2ec35 --- /dev/null +++ b/application/src/main/java/org/thingsboard/server/service/edge/rpc/utils/AdminSettingsCleanupUtils.java @@ -0,0 +1,94 @@ +// SPDX-FileCopyrightText: Copyright The Thingsboard Authors +// SPDX-License-Identifier: Apache-2.0 +package org.thingsboard.server.service.edge.rpc.utils; + +import com.google.common.util.concurrent.FutureCallback; +import com.google.common.util.concurrent.Futures; +import com.google.common.util.concurrent.ListenableFuture; +import lombok.extern.slf4j.Slf4j; +import org.checkerframework.checker.nullness.qual.Nullable; +import org.thingsboard.server.common.data.AttributeScope; +import org.thingsboard.server.common.data.edge.Edge; +import org.thingsboard.server.common.data.id.TenantId; +import org.thingsboard.server.common.data.kv.AttributeKvEntry; +import org.thingsboard.server.common.data.kv.BaseAttributeKvEntry; +import org.thingsboard.server.common.data.kv.BooleanDataEntry; +import org.thingsboard.server.gen.edge.v1.DownlinkMsg; +import org.thingsboard.server.gen.edge.v1.EdgeVersion; +import org.thingsboard.server.service.edge.EdgeContextComponent; + +import java.util.List; +import java.util.Optional; +import java.util.function.Function; + +@Slf4j +public final class AdminSettingsCleanupUtils { + + private static final String ADMIN_SETTINGS_CLEANUP_COMPLETED_ATTR_KEY = "adminSettingsCleanupCompleted"; + + /** + * Sends the one-time admin settings cleanup pack to edges that were provisioned before admin settings sync was + * removed, then runs {@code continuation}. Edges on {@code cleanupUpToVersion} or newer never received the + * settings, so they are skipped. The completion flag is stored as a server attribute on the edge, so the cleanup + * is sent once; if the pack is interrupted the flag is not set and the cleanup is retried on the next sync. + * + * @param downlinkMsgsPackSender sends a downlink pack, returning whether the send was interrupted + * @param continuation always invoked, whether or not the cleanup ran or failed + */ + public static void sendOneTimeAdminSettingsCleanupIfNeeded(EdgeContextComponent ctx, Edge edge, EdgeVersion edgeVersion, + EdgeVersion cleanupUpToVersion, + Function, ListenableFuture> downlinkMsgsPackSender, + Runnable continuation) { + if (!EdgeVersionUtils.isEdgeVersionOlderThan(edgeVersion, cleanupUpToVersion)) { + continuation.run(); + return; + } + TenantId tenantId = edge.getTenantId(); + try { + ListenableFuture> isCleanupCompletedAttrFuture = ctx.getAttributesService() + .find(tenantId, edge.getId(), AttributeScope.SERVER_SCOPE, ADMIN_SETTINGS_CLEANUP_COMPLETED_ATTR_KEY); + + ListenableFuture cleanupFuture = Futures.transformAsync( + isCleanupCompletedAttrFuture, + attr -> { + boolean alreadyCompleted = attr.isPresent() && attr.flatMap(AttributeKvEntry::getBooleanValue).orElse(false); + if (alreadyCompleted) { + return Futures.immediateFuture(false); + } + List cleanupMsgs = ctx.getAdminSettingsProcessor().convertAdminSettingsCleanupToDownlinks(edge); + if (cleanupMsgs.isEmpty()) { + return Futures.immediateFuture(true); + } + // send the cleanup pack; mark completed only if it was not interrupted, so it retries on next sync otherwise + return Futures.transform(downlinkMsgsPackSender.apply(cleanupMsgs), + isInterrupted -> !Boolean.TRUE.equals(isInterrupted), ctx.getGrpcCallbackExecutorService()); + }, ctx.getGrpcCallbackExecutorService()); + + Futures.addCallback(cleanupFuture, new FutureCallback<>() { + @Override + public void onSuccess(@Nullable Boolean markCompleted) { + if (Boolean.TRUE.equals(markCompleted)) { + markAdminSettingsCleanupCompleted(ctx, edge); + } + continuation.run(); + } + + @Override + public void onFailure(Throwable t) { + log.error("[{}][{}] Failed to run one-time admin settings cleanup for edge", tenantId, edge.getId(), t); + continuation.run(); + } + }, ctx.getGrpcCallbackExecutorService()); + } catch (Exception e) { + log.error("[{}][{}] Failed to start admin settings cleanup", tenantId, edge.getId(), e); + continuation.run(); + } + } + + private static void markAdminSettingsCleanupCompleted(EdgeContextComponent ctx, Edge edge) { + AttributeKvEntry attributeKvEntry = new BaseAttributeKvEntry( + new BooleanDataEntry(ADMIN_SETTINGS_CLEANUP_COMPLETED_ATTR_KEY, true), System.currentTimeMillis()); + ctx.getAttributesService().save(edge.getTenantId(), edge.getId(), AttributeScope.SERVER_SCOPE, attributeKvEntry); + } + +} From 49afaa211e248cb5dbd710edce74e9674a6cef0e Mon Sep 17 00:00:00 2001 From: Nikita Mazurenko Date: Fri, 11 Sep 2026 18:22:14 +0300 Subject: [PATCH 10/16] Remove cloud-side admin settings cleanup in favor of edge-side migration --- .../service/edge/EdgeContextComponent.java | 4 - .../service/edge/rpc/EdgeGrpcSession.java | 5 +- .../settings/AdminSettingsEdgeProcessor.java | 78 --------------- .../rpc/utils/AdminSettingsCleanupUtils.java | 94 ------------------- .../AdminSettingsEdgeProcessorTest.java | 52 ---------- 5 files changed, 1 insertion(+), 232 deletions(-) delete mode 100644 application/src/main/java/org/thingsboard/server/service/edge/rpc/utils/AdminSettingsCleanupUtils.java diff --git a/application/src/main/java/org/thingsboard/server/service/edge/EdgeContextComponent.java b/application/src/main/java/org/thingsboard/server/service/edge/EdgeContextComponent.java index 7d9f5bb8db..58b4cf719d 100644 --- a/application/src/main/java/org/thingsboard/server/service/edge/EdgeContextComponent.java +++ b/application/src/main/java/org/thingsboard/server/service/edge/EdgeContextComponent.java @@ -59,7 +59,6 @@ import org.thingsboard.server.service.edge.rpc.processor.relation.RelationEdgePr import org.thingsboard.server.service.edge.rpc.processor.resource.ResourceEdgeProcessor; import org.thingsboard.server.service.edge.rpc.processor.rule.RuleChainEdgeProcessor; import org.thingsboard.server.service.edge.rpc.processor.rule.RuleChainMetadataEdgeProcessor; -import org.thingsboard.server.service.edge.rpc.processor.settings.AdminSettingsEdgeProcessor; import org.thingsboard.server.service.edge.rpc.processor.telemetry.TelemetryEdgeProcessor; import org.thingsboard.server.service.edge.rpc.sync.EdgeRequestsService; import org.thingsboard.server.service.executors.GrpcCallbackExecutorService; @@ -193,9 +192,6 @@ public class EdgeContextComponent { // processors - @Autowired - private AdminSettingsEdgeProcessor adminSettingsProcessor; - @Autowired private AlarmProcessor alarmProcessor; diff --git a/application/src/main/java/org/thingsboard/server/service/edge/rpc/EdgeGrpcSession.java b/application/src/main/java/org/thingsboard/server/service/edge/rpc/EdgeGrpcSession.java index e9b3a09734..ec9eedde62 100644 --- a/application/src/main/java/org/thingsboard/server/service/edge/rpc/EdgeGrpcSession.java +++ b/application/src/main/java/org/thingsboard/server/service/edge/rpc/EdgeGrpcSession.java @@ -78,7 +78,6 @@ import org.thingsboard.server.service.edge.EdgeContextComponent; import org.thingsboard.server.service.edge.EdgeMsgConstructorUtils; import org.thingsboard.server.service.edge.rpc.fetch.EdgeEventFetcher; import org.thingsboard.server.service.edge.rpc.fetch.GeneralEdgeEventFetcher; -import org.thingsboard.server.service.edge.rpc.utils.AdminSettingsCleanupUtils; import org.thingsboard.server.service.edge.rpc.utils.EdgeVersionUtils; import java.io.Closeable; @@ -240,9 +239,7 @@ public abstract class EdgeGrpcSession implements Closeable { log.info("[{}][{}][{}] Staring edge sync process", tenantId, edge.getId(), sessionId); syncInProgress = true; interruptGeneralProcessingOnSync(); - AdminSettingsCleanupUtils.sendOneTimeAdminSettingsCleanupIfNeeded(ctx, edge, edgeVersion, - EdgeVersion.V_4_2_2_4, this::sendDownlinkMsgsPack, - () -> doSync(new EdgeSyncCursor(ctx, edge, fullSync))); + doSync(new EdgeSyncCursor(ctx, edge, fullSync)); } else { log.info("[{}][{}][{}] Sync is already started, skipping starting it now", tenantId, edge.getId(), sessionId); } diff --git a/application/src/main/java/org/thingsboard/server/service/edge/rpc/processor/settings/AdminSettingsEdgeProcessor.java b/application/src/main/java/org/thingsboard/server/service/edge/rpc/processor/settings/AdminSettingsEdgeProcessor.java index 7e80be5b1c..a43808d2da 100644 --- a/application/src/main/java/org/thingsboard/server/service/edge/rpc/processor/settings/AdminSettingsEdgeProcessor.java +++ b/application/src/main/java/org/thingsboard/server/service/edge/rpc/processor/settings/AdminSettingsEdgeProcessor.java @@ -2,35 +2,21 @@ // SPDX-License-Identifier: Apache-2.0 package org.thingsboard.server.service.edge.rpc.processor.settings; -import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.node.ObjectNode; import lombok.extern.slf4j.Slf4j; -import org.apache.commons.lang3.RandomStringUtils; -import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; import org.thingsboard.common.util.JacksonUtil; import org.thingsboard.server.common.data.AdminSettings; import org.thingsboard.server.common.data.EdgeUtils; -import org.thingsboard.server.common.data.edge.Edge; import org.thingsboard.server.common.data.edge.EdgeEvent; import org.thingsboard.server.common.data.edge.EdgeEventType; import org.thingsboard.server.common.data.id.AdminSettingsId; 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.common.data.security.model.JwtSettings; import org.thingsboard.server.gen.edge.v1.AdminSettingsUpdateMsg; import org.thingsboard.server.gen.edge.v1.DownlinkMsg; import org.thingsboard.server.gen.edge.v1.EdgeVersion; import org.thingsboard.server.queue.util.TbCoreComponent; import org.thingsboard.server.service.edge.rpc.processor.BaseEdgeProcessor; -import org.thingsboard.server.service.security.auth.jwt.settings.JwtSettingsService; -import java.nio.charset.StandardCharsets; -import java.util.ArrayList; -import java.util.Base64; -import java.util.HashSet; -import java.util.List; import java.util.Set; @Slf4j @@ -40,15 +26,6 @@ public class AdminSettingsEdgeProcessor extends BaseEdgeProcessor { private static final Set EDGE_SYNCED_SETTINGS_KEYS = Set.of("general", "connectivity"); - private static final int DEFAULT_PAGE_SIZE = 1000; - - @Value("${security.jwt.tokenExpirationTime:9000}") - private Integer tokenExpirationTime; - @Value("${security.jwt.refreshTokenExpTime:604800}") - private Integer refreshTokenExpTime; - @Value("${security.jwt.tokenIssuer:thingsboard.io}") - private String tokenIssuer; - @Override public DownlinkMsg convertEdgeEventToDownlink(EdgeEvent edgeEvent, EdgeVersion edgeVersion) { AdminSettings adminSettings = null; @@ -75,61 +52,6 @@ public class AdminSettingsEdgeProcessor extends BaseEdgeProcessor { .build(); } - public List convertAdminSettingsCleanupToDownlinks(Edge edge) { - List result = new ArrayList<>(); - Set cleanedKeys = new HashSet<>(); - - Set tenantScopes = Set.of(TenantId.SYS_TENANT_ID, edge.getTenantId()); - for (TenantId scope : tenantScopes) { - PageLink pageLink = new PageLink(DEFAULT_PAGE_SIZE); - PageData page; - do { - page = edgeCtx.getAdminSettingsService().findAllByTenantId(scope, pageLink); - for (AdminSettings adminSettings : page.getData()) { - String key = adminSettings.getKey(); - if (EDGE_SYNCED_SETTINGS_KEYS.contains(key) || !cleanedKeys.add(key)) { - continue; - } - result.add(buildAdminSettingsCleanupDownlink(key)); - } - pageLink = pageLink.nextPageLink(); - } while (page.hasNext()); - } - log.info("[{}][{}] Prepared {} one-time admin settings cleanup message(s): {}", - edge.getTenantId(), edge.getId(), result.size(), cleanedKeys); - return result; - } - - private DownlinkMsg buildAdminSettingsCleanupDownlink(String key) { - AdminSettings adminSettings = new AdminSettings(); - adminSettings.setTenantId(TenantId.SYS_TENANT_ID); - adminSettings.setKey(key); - adminSettings.setJsonValue(buildAdminSettingsCleanupValue(key)); - AdminSettingsUpdateMsg msg = AdminSettingsUpdateMsg.newBuilder().setEntity(JacksonUtil.toString(adminSettings)).build(); - return DownlinkMsg.newBuilder() - .setDownlinkMsgId(EdgeUtils.nextPositiveInt()) - .addAdminSettingsUpdateMsg(msg) - .build(); - } - - private JsonNode buildAdminSettingsCleanupValue(String key) { - if (JwtSettingsService.ADMIN_SETTINGS_JWT_KEY.equals(key)) { - return JacksonUtil.valueToTree(generateRandomJwtSettings()); - } - ObjectNode value = JacksonUtil.newObjectNode(); - if ("mail".equals(key)) { - value.put("password", ""); - value.put("refreshToken", ""); - } - return value; - } - - private JwtSettings generateRandomJwtSettings() { - String randomSigningKey = Base64.getEncoder().encodeToString( - RandomStringUtils.secure().nextAlphanumeric(64).getBytes(StandardCharsets.UTF_8)); - return new JwtSettings(tokenExpirationTime, refreshTokenExpTime, tokenIssuer, randomSigningKey); - } - @Override public EdgeEventType getEdgeEventType() { return EdgeEventType.ADMIN_SETTINGS; diff --git a/application/src/main/java/org/thingsboard/server/service/edge/rpc/utils/AdminSettingsCleanupUtils.java b/application/src/main/java/org/thingsboard/server/service/edge/rpc/utils/AdminSettingsCleanupUtils.java deleted file mode 100644 index cd0fd2ec35..0000000000 --- a/application/src/main/java/org/thingsboard/server/service/edge/rpc/utils/AdminSettingsCleanupUtils.java +++ /dev/null @@ -1,94 +0,0 @@ -// SPDX-FileCopyrightText: Copyright The Thingsboard Authors -// SPDX-License-Identifier: Apache-2.0 -package org.thingsboard.server.service.edge.rpc.utils; - -import com.google.common.util.concurrent.FutureCallback; -import com.google.common.util.concurrent.Futures; -import com.google.common.util.concurrent.ListenableFuture; -import lombok.extern.slf4j.Slf4j; -import org.checkerframework.checker.nullness.qual.Nullable; -import org.thingsboard.server.common.data.AttributeScope; -import org.thingsboard.server.common.data.edge.Edge; -import org.thingsboard.server.common.data.id.TenantId; -import org.thingsboard.server.common.data.kv.AttributeKvEntry; -import org.thingsboard.server.common.data.kv.BaseAttributeKvEntry; -import org.thingsboard.server.common.data.kv.BooleanDataEntry; -import org.thingsboard.server.gen.edge.v1.DownlinkMsg; -import org.thingsboard.server.gen.edge.v1.EdgeVersion; -import org.thingsboard.server.service.edge.EdgeContextComponent; - -import java.util.List; -import java.util.Optional; -import java.util.function.Function; - -@Slf4j -public final class AdminSettingsCleanupUtils { - - private static final String ADMIN_SETTINGS_CLEANUP_COMPLETED_ATTR_KEY = "adminSettingsCleanupCompleted"; - - /** - * Sends the one-time admin settings cleanup pack to edges that were provisioned before admin settings sync was - * removed, then runs {@code continuation}. Edges on {@code cleanupUpToVersion} or newer never received the - * settings, so they are skipped. The completion flag is stored as a server attribute on the edge, so the cleanup - * is sent once; if the pack is interrupted the flag is not set and the cleanup is retried on the next sync. - * - * @param downlinkMsgsPackSender sends a downlink pack, returning whether the send was interrupted - * @param continuation always invoked, whether or not the cleanup ran or failed - */ - public static void sendOneTimeAdminSettingsCleanupIfNeeded(EdgeContextComponent ctx, Edge edge, EdgeVersion edgeVersion, - EdgeVersion cleanupUpToVersion, - Function, ListenableFuture> downlinkMsgsPackSender, - Runnable continuation) { - if (!EdgeVersionUtils.isEdgeVersionOlderThan(edgeVersion, cleanupUpToVersion)) { - continuation.run(); - return; - } - TenantId tenantId = edge.getTenantId(); - try { - ListenableFuture> isCleanupCompletedAttrFuture = ctx.getAttributesService() - .find(tenantId, edge.getId(), AttributeScope.SERVER_SCOPE, ADMIN_SETTINGS_CLEANUP_COMPLETED_ATTR_KEY); - - ListenableFuture cleanupFuture = Futures.transformAsync( - isCleanupCompletedAttrFuture, - attr -> { - boolean alreadyCompleted = attr.isPresent() && attr.flatMap(AttributeKvEntry::getBooleanValue).orElse(false); - if (alreadyCompleted) { - return Futures.immediateFuture(false); - } - List cleanupMsgs = ctx.getAdminSettingsProcessor().convertAdminSettingsCleanupToDownlinks(edge); - if (cleanupMsgs.isEmpty()) { - return Futures.immediateFuture(true); - } - // send the cleanup pack; mark completed only if it was not interrupted, so it retries on next sync otherwise - return Futures.transform(downlinkMsgsPackSender.apply(cleanupMsgs), - isInterrupted -> !Boolean.TRUE.equals(isInterrupted), ctx.getGrpcCallbackExecutorService()); - }, ctx.getGrpcCallbackExecutorService()); - - Futures.addCallback(cleanupFuture, new FutureCallback<>() { - @Override - public void onSuccess(@Nullable Boolean markCompleted) { - if (Boolean.TRUE.equals(markCompleted)) { - markAdminSettingsCleanupCompleted(ctx, edge); - } - continuation.run(); - } - - @Override - public void onFailure(Throwable t) { - log.error("[{}][{}] Failed to run one-time admin settings cleanup for edge", tenantId, edge.getId(), t); - continuation.run(); - } - }, ctx.getGrpcCallbackExecutorService()); - } catch (Exception e) { - log.error("[{}][{}] Failed to start admin settings cleanup", tenantId, edge.getId(), e); - continuation.run(); - } - } - - private static void markAdminSettingsCleanupCompleted(EdgeContextComponent ctx, Edge edge) { - AttributeKvEntry attributeKvEntry = new BaseAttributeKvEntry( - new BooleanDataEntry(ADMIN_SETTINGS_CLEANUP_COMPLETED_ATTR_KEY, true), System.currentTimeMillis()); - ctx.getAttributesService().save(edge.getTenantId(), edge.getId(), AttributeScope.SERVER_SCOPE, attributeKvEntry); - } - -} diff --git a/application/src/test/java/org/thingsboard/server/service/edge/rpc/processor/settings/AdminSettingsEdgeProcessorTest.java b/application/src/test/java/org/thingsboard/server/service/edge/rpc/processor/settings/AdminSettingsEdgeProcessorTest.java index 9a9d0a9ca8..70598f6c67 100644 --- a/application/src/test/java/org/thingsboard/server/service/edge/rpc/processor/settings/AdminSettingsEdgeProcessorTest.java +++ b/application/src/test/java/org/thingsboard/server/service/edge/rpc/processor/settings/AdminSettingsEdgeProcessorTest.java @@ -2,7 +2,6 @@ // SPDX-License-Identifier: Apache-2.0 package org.thingsboard.server.service.edge.rpc.processor.settings; -import com.fasterxml.jackson.databind.JsonNode; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -12,25 +11,18 @@ import org.mockito.junit.jupiter.MockitoExtension; import org.springframework.test.util.ReflectionTestUtils; import org.thingsboard.common.util.JacksonUtil; import org.thingsboard.server.common.data.AdminSettings; -import org.thingsboard.server.common.data.edge.Edge; import org.thingsboard.server.common.data.edge.EdgeEvent; import org.thingsboard.server.common.data.id.AdminSettingsId; import org.thingsboard.server.common.data.id.EdgeId; import org.thingsboard.server.common.data.id.TenantId; -import org.thingsboard.server.common.data.page.PageData; import org.thingsboard.server.dao.settings.AdminSettingsService; import org.thingsboard.server.gen.edge.v1.DownlinkMsg; import org.thingsboard.server.gen.edge.v1.EdgeVersion; import org.thingsboard.server.service.edge.EdgeContextComponent; -import java.util.List; -import java.util.Map; -import java.util.Set; import java.util.UUID; -import java.util.stream.Collectors; import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.lenient; import static org.mockito.Mockito.when; @@ -49,9 +41,6 @@ public class AdminSettingsEdgeProcessorTest { public void setUp() { processor = new AdminSettingsEdgeProcessor(); ReflectionTestUtils.setField(processor, "edgeCtx", edgeCtx); - ReflectionTestUtils.setField(processor, "tokenExpirationTime", 9000); - ReflectionTestUtils.setField(processor, "refreshTokenExpTime", 604800); - ReflectionTestUtils.setField(processor, "tokenIssuer", "thingsboard.io"); lenient().when(edgeCtx.getAdminSettingsService()).thenReturn(adminSettingsService); } @@ -89,42 +78,6 @@ public class AdminSettingsEdgeProcessorTest { Assertions.assertNull(downlink); } - @Test - public void testCleanupClearsSecretsAndSkipsAllowListedKeys() { - Edge edge = new Edge(); - edge.setId(new EdgeId(UUID.randomUUID())); - edge.setTenantId(tenantId); - - when(adminSettingsService.findAllByTenantId(eq(TenantId.SYS_TENANT_ID), any())) - .thenReturn(page(adminSettings(TenantId.SYS_TENANT_ID, "mail"), - adminSettings(TenantId.SYS_TENANT_ID, "jwt"), - adminSettings(TenantId.SYS_TENANT_ID, "general"))); - when(adminSettingsService.findAllByTenantId(eq(tenantId), any())) - .thenReturn(page(adminSettings(tenantId, "sms"), - adminSettings(tenantId, "connectivity"))); - - List downlinks = processor.convertAdminSettingsCleanupToDownlinks(edge); - - Map cleanupByKey = downlinks.stream() - .map(d -> JacksonUtil.fromString(d.getAdminSettingsUpdateMsg(0).getEntity(), AdminSettings.class, true)) - .collect(Collectors.toMap(AdminSettings::getKey, s -> s)); - - // Allow-listed keys (general/connectivity) are never wiped; every other key is. - Assertions.assertEquals(Set.of("mail", "jwt", "sms"), cleanupByKey.keySet()); - - // Mail secrets are blanked. - JsonNode mailValue = cleanupByKey.get("mail").getJsonValue(); - Assertions.assertEquals("", mailValue.get("password").asText()); - Assertions.assertEquals("", mailValue.get("refreshToken").asText()); - - // JWT signing key is re-randomized to a non-empty value. - JsonNode jwtValue = cleanupByKey.get("jwt").getJsonValue(); - Assertions.assertFalse(jwtValue.get("tokenSigningKey").asText().isEmpty()); - - // Other non-allow-listed keys are wiped to an empty object. - Assertions.assertTrue(cleanupByKey.get("sms").getJsonValue().isEmpty()); - } - private EdgeEvent edgeEvent(TenantId eventTenantId) { EdgeEvent edgeEvent = new EdgeEvent(); edgeEvent.setTenantId(eventTenantId); @@ -142,9 +95,4 @@ public class AdminSettingsEdgeProcessorTest { return adminSettings; } - private PageData page(AdminSettings... settings) { - List data = List.of(settings); - return new PageData<>(data, 1, data.size(), false); - } - } From a4ff69fe9e5e2ae0cf71e00392bd65c827684efa Mon Sep 17 00:00:00 2001 From: Nikita Mazurenko Date: Fri, 11 Sep 2026 18:23:10 +0300 Subject: [PATCH 11/16] Remove cloud-side admin settings cleanup in favor of edge-side migration --- .../service/edge/EdgeContextComponent.java | 4 - .../service/edge/rpc/EdgeGrpcSession.java | 5 +- .../settings/AdminSettingsEdgeProcessor.java | 78 --------------- .../rpc/utils/AdminSettingsCleanupUtils.java | 94 ------------------- .../AdminSettingsEdgeProcessorTest.java | 52 ---------- 5 files changed, 1 insertion(+), 232 deletions(-) delete mode 100644 application/src/main/java/org/thingsboard/server/service/edge/rpc/utils/AdminSettingsCleanupUtils.java diff --git a/application/src/main/java/org/thingsboard/server/service/edge/EdgeContextComponent.java b/application/src/main/java/org/thingsboard/server/service/edge/EdgeContextComponent.java index ac75570f82..1564ad8e7b 100644 --- a/application/src/main/java/org/thingsboard/server/service/edge/EdgeContextComponent.java +++ b/application/src/main/java/org/thingsboard/server/service/edge/EdgeContextComponent.java @@ -63,7 +63,6 @@ import org.thingsboard.server.service.edge.rpc.processor.relation.RelationEdgePr import org.thingsboard.server.service.edge.rpc.processor.resource.ResourceEdgeProcessor; import org.thingsboard.server.service.edge.rpc.processor.rule.RuleChainEdgeProcessor; import org.thingsboard.server.service.edge.rpc.processor.rule.RuleChainMetadataEdgeProcessor; -import org.thingsboard.server.service.edge.rpc.processor.settings.AdminSettingsEdgeProcessor; import org.thingsboard.server.service.edge.rpc.processor.telemetry.TelemetryEdgeProcessor; import org.thingsboard.server.service.edge.rpc.processor.user.UserProcessor; import org.thingsboard.server.service.edge.rpc.sync.EdgeRequestsService; @@ -201,9 +200,6 @@ public class EdgeContextComponent { private Optional statsCounterService; // processors - @Autowired - private AdminSettingsEdgeProcessor adminSettingsProcessor; - @Autowired private AlarmProcessor alarmProcessor; diff --git a/application/src/main/java/org/thingsboard/server/service/edge/rpc/EdgeGrpcSession.java b/application/src/main/java/org/thingsboard/server/service/edge/rpc/EdgeGrpcSession.java index 413de01b79..d01a53aab8 100644 --- a/application/src/main/java/org/thingsboard/server/service/edge/rpc/EdgeGrpcSession.java +++ b/application/src/main/java/org/thingsboard/server/service/edge/rpc/EdgeGrpcSession.java @@ -85,7 +85,6 @@ import org.thingsboard.server.service.edge.EdgeContextComponent; import org.thingsboard.server.service.edge.EdgeMsgConstructorUtils; import org.thingsboard.server.service.edge.rpc.fetch.EdgeEventFetcher; import org.thingsboard.server.service.edge.rpc.fetch.GeneralEdgeEventFetcher; -import org.thingsboard.server.service.edge.rpc.utils.AdminSettingsCleanupUtils; import org.thingsboard.server.service.edge.rpc.utils.EdgeVersionUtils; import java.io.Closeable; @@ -255,9 +254,7 @@ public abstract class EdgeGrpcSession implements Closeable { log.info("[{}][{}][{}] Staring edge sync process", tenantId, edge.getId(), sessionId); updateSyncInProgress(true); interruptGeneralProcessingOnSync(); - AdminSettingsCleanupUtils.sendOneTimeAdminSettingsCleanupIfNeeded(ctx, edge, edgeVersion, - EdgeVersion.V_4_3_1_4, this::sendDownlinkMsgsPack, - () -> doSync(new EdgeSyncCursor(ctx, edge, fullSync))); + doSync(new EdgeSyncCursor(ctx, edge, fullSync)); } else { log.info("[{}][{}][{}] Sync is already started, skipping starting it now", tenantId, edge.getId(), sessionId); } diff --git a/application/src/main/java/org/thingsboard/server/service/edge/rpc/processor/settings/AdminSettingsEdgeProcessor.java b/application/src/main/java/org/thingsboard/server/service/edge/rpc/processor/settings/AdminSettingsEdgeProcessor.java index 7e80be5b1c..a43808d2da 100644 --- a/application/src/main/java/org/thingsboard/server/service/edge/rpc/processor/settings/AdminSettingsEdgeProcessor.java +++ b/application/src/main/java/org/thingsboard/server/service/edge/rpc/processor/settings/AdminSettingsEdgeProcessor.java @@ -2,35 +2,21 @@ // SPDX-License-Identifier: Apache-2.0 package org.thingsboard.server.service.edge.rpc.processor.settings; -import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.node.ObjectNode; import lombok.extern.slf4j.Slf4j; -import org.apache.commons.lang3.RandomStringUtils; -import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; import org.thingsboard.common.util.JacksonUtil; import org.thingsboard.server.common.data.AdminSettings; import org.thingsboard.server.common.data.EdgeUtils; -import org.thingsboard.server.common.data.edge.Edge; import org.thingsboard.server.common.data.edge.EdgeEvent; import org.thingsboard.server.common.data.edge.EdgeEventType; import org.thingsboard.server.common.data.id.AdminSettingsId; 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.common.data.security.model.JwtSettings; import org.thingsboard.server.gen.edge.v1.AdminSettingsUpdateMsg; import org.thingsboard.server.gen.edge.v1.DownlinkMsg; import org.thingsboard.server.gen.edge.v1.EdgeVersion; import org.thingsboard.server.queue.util.TbCoreComponent; import org.thingsboard.server.service.edge.rpc.processor.BaseEdgeProcessor; -import org.thingsboard.server.service.security.auth.jwt.settings.JwtSettingsService; -import java.nio.charset.StandardCharsets; -import java.util.ArrayList; -import java.util.Base64; -import java.util.HashSet; -import java.util.List; import java.util.Set; @Slf4j @@ -40,15 +26,6 @@ public class AdminSettingsEdgeProcessor extends BaseEdgeProcessor { private static final Set EDGE_SYNCED_SETTINGS_KEYS = Set.of("general", "connectivity"); - private static final int DEFAULT_PAGE_SIZE = 1000; - - @Value("${security.jwt.tokenExpirationTime:9000}") - private Integer tokenExpirationTime; - @Value("${security.jwt.refreshTokenExpTime:604800}") - private Integer refreshTokenExpTime; - @Value("${security.jwt.tokenIssuer:thingsboard.io}") - private String tokenIssuer; - @Override public DownlinkMsg convertEdgeEventToDownlink(EdgeEvent edgeEvent, EdgeVersion edgeVersion) { AdminSettings adminSettings = null; @@ -75,61 +52,6 @@ public class AdminSettingsEdgeProcessor extends BaseEdgeProcessor { .build(); } - public List convertAdminSettingsCleanupToDownlinks(Edge edge) { - List result = new ArrayList<>(); - Set cleanedKeys = new HashSet<>(); - - Set tenantScopes = Set.of(TenantId.SYS_TENANT_ID, edge.getTenantId()); - for (TenantId scope : tenantScopes) { - PageLink pageLink = new PageLink(DEFAULT_PAGE_SIZE); - PageData page; - do { - page = edgeCtx.getAdminSettingsService().findAllByTenantId(scope, pageLink); - for (AdminSettings adminSettings : page.getData()) { - String key = adminSettings.getKey(); - if (EDGE_SYNCED_SETTINGS_KEYS.contains(key) || !cleanedKeys.add(key)) { - continue; - } - result.add(buildAdminSettingsCleanupDownlink(key)); - } - pageLink = pageLink.nextPageLink(); - } while (page.hasNext()); - } - log.info("[{}][{}] Prepared {} one-time admin settings cleanup message(s): {}", - edge.getTenantId(), edge.getId(), result.size(), cleanedKeys); - return result; - } - - private DownlinkMsg buildAdminSettingsCleanupDownlink(String key) { - AdminSettings adminSettings = new AdminSettings(); - adminSettings.setTenantId(TenantId.SYS_TENANT_ID); - adminSettings.setKey(key); - adminSettings.setJsonValue(buildAdminSettingsCleanupValue(key)); - AdminSettingsUpdateMsg msg = AdminSettingsUpdateMsg.newBuilder().setEntity(JacksonUtil.toString(adminSettings)).build(); - return DownlinkMsg.newBuilder() - .setDownlinkMsgId(EdgeUtils.nextPositiveInt()) - .addAdminSettingsUpdateMsg(msg) - .build(); - } - - private JsonNode buildAdminSettingsCleanupValue(String key) { - if (JwtSettingsService.ADMIN_SETTINGS_JWT_KEY.equals(key)) { - return JacksonUtil.valueToTree(generateRandomJwtSettings()); - } - ObjectNode value = JacksonUtil.newObjectNode(); - if ("mail".equals(key)) { - value.put("password", ""); - value.put("refreshToken", ""); - } - return value; - } - - private JwtSettings generateRandomJwtSettings() { - String randomSigningKey = Base64.getEncoder().encodeToString( - RandomStringUtils.secure().nextAlphanumeric(64).getBytes(StandardCharsets.UTF_8)); - return new JwtSettings(tokenExpirationTime, refreshTokenExpTime, tokenIssuer, randomSigningKey); - } - @Override public EdgeEventType getEdgeEventType() { return EdgeEventType.ADMIN_SETTINGS; diff --git a/application/src/main/java/org/thingsboard/server/service/edge/rpc/utils/AdminSettingsCleanupUtils.java b/application/src/main/java/org/thingsboard/server/service/edge/rpc/utils/AdminSettingsCleanupUtils.java deleted file mode 100644 index cd0fd2ec35..0000000000 --- a/application/src/main/java/org/thingsboard/server/service/edge/rpc/utils/AdminSettingsCleanupUtils.java +++ /dev/null @@ -1,94 +0,0 @@ -// SPDX-FileCopyrightText: Copyright The Thingsboard Authors -// SPDX-License-Identifier: Apache-2.0 -package org.thingsboard.server.service.edge.rpc.utils; - -import com.google.common.util.concurrent.FutureCallback; -import com.google.common.util.concurrent.Futures; -import com.google.common.util.concurrent.ListenableFuture; -import lombok.extern.slf4j.Slf4j; -import org.checkerframework.checker.nullness.qual.Nullable; -import org.thingsboard.server.common.data.AttributeScope; -import org.thingsboard.server.common.data.edge.Edge; -import org.thingsboard.server.common.data.id.TenantId; -import org.thingsboard.server.common.data.kv.AttributeKvEntry; -import org.thingsboard.server.common.data.kv.BaseAttributeKvEntry; -import org.thingsboard.server.common.data.kv.BooleanDataEntry; -import org.thingsboard.server.gen.edge.v1.DownlinkMsg; -import org.thingsboard.server.gen.edge.v1.EdgeVersion; -import org.thingsboard.server.service.edge.EdgeContextComponent; - -import java.util.List; -import java.util.Optional; -import java.util.function.Function; - -@Slf4j -public final class AdminSettingsCleanupUtils { - - private static final String ADMIN_SETTINGS_CLEANUP_COMPLETED_ATTR_KEY = "adminSettingsCleanupCompleted"; - - /** - * Sends the one-time admin settings cleanup pack to edges that were provisioned before admin settings sync was - * removed, then runs {@code continuation}. Edges on {@code cleanupUpToVersion} or newer never received the - * settings, so they are skipped. The completion flag is stored as a server attribute on the edge, so the cleanup - * is sent once; if the pack is interrupted the flag is not set and the cleanup is retried on the next sync. - * - * @param downlinkMsgsPackSender sends a downlink pack, returning whether the send was interrupted - * @param continuation always invoked, whether or not the cleanup ran or failed - */ - public static void sendOneTimeAdminSettingsCleanupIfNeeded(EdgeContextComponent ctx, Edge edge, EdgeVersion edgeVersion, - EdgeVersion cleanupUpToVersion, - Function, ListenableFuture> downlinkMsgsPackSender, - Runnable continuation) { - if (!EdgeVersionUtils.isEdgeVersionOlderThan(edgeVersion, cleanupUpToVersion)) { - continuation.run(); - return; - } - TenantId tenantId = edge.getTenantId(); - try { - ListenableFuture> isCleanupCompletedAttrFuture = ctx.getAttributesService() - .find(tenantId, edge.getId(), AttributeScope.SERVER_SCOPE, ADMIN_SETTINGS_CLEANUP_COMPLETED_ATTR_KEY); - - ListenableFuture cleanupFuture = Futures.transformAsync( - isCleanupCompletedAttrFuture, - attr -> { - boolean alreadyCompleted = attr.isPresent() && attr.flatMap(AttributeKvEntry::getBooleanValue).orElse(false); - if (alreadyCompleted) { - return Futures.immediateFuture(false); - } - List cleanupMsgs = ctx.getAdminSettingsProcessor().convertAdminSettingsCleanupToDownlinks(edge); - if (cleanupMsgs.isEmpty()) { - return Futures.immediateFuture(true); - } - // send the cleanup pack; mark completed only if it was not interrupted, so it retries on next sync otherwise - return Futures.transform(downlinkMsgsPackSender.apply(cleanupMsgs), - isInterrupted -> !Boolean.TRUE.equals(isInterrupted), ctx.getGrpcCallbackExecutorService()); - }, ctx.getGrpcCallbackExecutorService()); - - Futures.addCallback(cleanupFuture, new FutureCallback<>() { - @Override - public void onSuccess(@Nullable Boolean markCompleted) { - if (Boolean.TRUE.equals(markCompleted)) { - markAdminSettingsCleanupCompleted(ctx, edge); - } - continuation.run(); - } - - @Override - public void onFailure(Throwable t) { - log.error("[{}][{}] Failed to run one-time admin settings cleanup for edge", tenantId, edge.getId(), t); - continuation.run(); - } - }, ctx.getGrpcCallbackExecutorService()); - } catch (Exception e) { - log.error("[{}][{}] Failed to start admin settings cleanup", tenantId, edge.getId(), e); - continuation.run(); - } - } - - private static void markAdminSettingsCleanupCompleted(EdgeContextComponent ctx, Edge edge) { - AttributeKvEntry attributeKvEntry = new BaseAttributeKvEntry( - new BooleanDataEntry(ADMIN_SETTINGS_CLEANUP_COMPLETED_ATTR_KEY, true), System.currentTimeMillis()); - ctx.getAttributesService().save(edge.getTenantId(), edge.getId(), AttributeScope.SERVER_SCOPE, attributeKvEntry); - } - -} diff --git a/application/src/test/java/org/thingsboard/server/service/edge/rpc/processor/settings/AdminSettingsEdgeProcessorTest.java b/application/src/test/java/org/thingsboard/server/service/edge/rpc/processor/settings/AdminSettingsEdgeProcessorTest.java index 9a9d0a9ca8..70598f6c67 100644 --- a/application/src/test/java/org/thingsboard/server/service/edge/rpc/processor/settings/AdminSettingsEdgeProcessorTest.java +++ b/application/src/test/java/org/thingsboard/server/service/edge/rpc/processor/settings/AdminSettingsEdgeProcessorTest.java @@ -2,7 +2,6 @@ // SPDX-License-Identifier: Apache-2.0 package org.thingsboard.server.service.edge.rpc.processor.settings; -import com.fasterxml.jackson.databind.JsonNode; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -12,25 +11,18 @@ import org.mockito.junit.jupiter.MockitoExtension; import org.springframework.test.util.ReflectionTestUtils; import org.thingsboard.common.util.JacksonUtil; import org.thingsboard.server.common.data.AdminSettings; -import org.thingsboard.server.common.data.edge.Edge; import org.thingsboard.server.common.data.edge.EdgeEvent; import org.thingsboard.server.common.data.id.AdminSettingsId; import org.thingsboard.server.common.data.id.EdgeId; import org.thingsboard.server.common.data.id.TenantId; -import org.thingsboard.server.common.data.page.PageData; import org.thingsboard.server.dao.settings.AdminSettingsService; import org.thingsboard.server.gen.edge.v1.DownlinkMsg; import org.thingsboard.server.gen.edge.v1.EdgeVersion; import org.thingsboard.server.service.edge.EdgeContextComponent; -import java.util.List; -import java.util.Map; -import java.util.Set; import java.util.UUID; -import java.util.stream.Collectors; import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.lenient; import static org.mockito.Mockito.when; @@ -49,9 +41,6 @@ public class AdminSettingsEdgeProcessorTest { public void setUp() { processor = new AdminSettingsEdgeProcessor(); ReflectionTestUtils.setField(processor, "edgeCtx", edgeCtx); - ReflectionTestUtils.setField(processor, "tokenExpirationTime", 9000); - ReflectionTestUtils.setField(processor, "refreshTokenExpTime", 604800); - ReflectionTestUtils.setField(processor, "tokenIssuer", "thingsboard.io"); lenient().when(edgeCtx.getAdminSettingsService()).thenReturn(adminSettingsService); } @@ -89,42 +78,6 @@ public class AdminSettingsEdgeProcessorTest { Assertions.assertNull(downlink); } - @Test - public void testCleanupClearsSecretsAndSkipsAllowListedKeys() { - Edge edge = new Edge(); - edge.setId(new EdgeId(UUID.randomUUID())); - edge.setTenantId(tenantId); - - when(adminSettingsService.findAllByTenantId(eq(TenantId.SYS_TENANT_ID), any())) - .thenReturn(page(adminSettings(TenantId.SYS_TENANT_ID, "mail"), - adminSettings(TenantId.SYS_TENANT_ID, "jwt"), - adminSettings(TenantId.SYS_TENANT_ID, "general"))); - when(adminSettingsService.findAllByTenantId(eq(tenantId), any())) - .thenReturn(page(adminSettings(tenantId, "sms"), - adminSettings(tenantId, "connectivity"))); - - List downlinks = processor.convertAdminSettingsCleanupToDownlinks(edge); - - Map cleanupByKey = downlinks.stream() - .map(d -> JacksonUtil.fromString(d.getAdminSettingsUpdateMsg(0).getEntity(), AdminSettings.class, true)) - .collect(Collectors.toMap(AdminSettings::getKey, s -> s)); - - // Allow-listed keys (general/connectivity) are never wiped; every other key is. - Assertions.assertEquals(Set.of("mail", "jwt", "sms"), cleanupByKey.keySet()); - - // Mail secrets are blanked. - JsonNode mailValue = cleanupByKey.get("mail").getJsonValue(); - Assertions.assertEquals("", mailValue.get("password").asText()); - Assertions.assertEquals("", mailValue.get("refreshToken").asText()); - - // JWT signing key is re-randomized to a non-empty value. - JsonNode jwtValue = cleanupByKey.get("jwt").getJsonValue(); - Assertions.assertFalse(jwtValue.get("tokenSigningKey").asText().isEmpty()); - - // Other non-allow-listed keys are wiped to an empty object. - Assertions.assertTrue(cleanupByKey.get("sms").getJsonValue().isEmpty()); - } - private EdgeEvent edgeEvent(TenantId eventTenantId) { EdgeEvent edgeEvent = new EdgeEvent(); edgeEvent.setTenantId(eventTenantId); @@ -142,9 +95,4 @@ public class AdminSettingsEdgeProcessorTest { return adminSettings; } - private PageData page(AdminSettings... settings) { - List data = List.of(settings); - return new PageData<>(data, 1, data.size(), false); - } - } From 4044db40bc8e16c90f130ccbd481204d612a3d62 Mon Sep 17 00:00:00 2001 From: Nikita Mazurenko Date: Tue, 22 Sep 2026 12:14:58 +0200 Subject: [PATCH 12/16] Harden edge-delegated mail/SMS/notification send handling --- .../rpc/sync/DefaultEdgeRequestsService.java | 71 +++++++++++++++---- .../src/main/resources/thingsboard.yml | 4 ++ 2 files changed, 60 insertions(+), 15 deletions(-) diff --git a/application/src/main/java/org/thingsboard/server/service/edge/rpc/sync/DefaultEdgeRequestsService.java b/application/src/main/java/org/thingsboard/server/service/edge/rpc/sync/DefaultEdgeRequestsService.java index 7a642e5cf0..03c8d11f07 100644 --- a/application/src/main/java/org/thingsboard/server/service/edge/rpc/sync/DefaultEdgeRequestsService.java +++ b/application/src/main/java/org/thingsboard/server/service/edge/rpc/sync/DefaultEdgeRequestsService.java @@ -8,12 +8,16 @@ import com.google.common.util.concurrent.FutureCallback; import com.google.common.util.concurrent.Futures; import com.google.common.util.concurrent.ListenableFuture; import com.google.common.util.concurrent.SettableFuture; +import jakarta.annotation.PreDestroy; import lombok.extern.slf4j.Slf4j; import org.checkerframework.checker.nullness.qual.Nullable; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Lazy; import org.springframework.stereotype.Service; import org.thingsboard.common.util.JacksonUtil; +import org.thingsboard.common.util.ListeningExecutor; +import org.thingsboard.common.util.ThingsBoardExecutors; import org.thingsboard.rule.engine.api.MailService; import org.thingsboard.rule.engine.api.SmsService; import org.thingsboard.rule.engine.api.notification.FirebaseService; @@ -70,16 +74,22 @@ import org.thingsboard.server.gen.edge.v1.WidgetBundleTypesRequestMsg; import org.thingsboard.server.queue.util.TbCoreComponent; import org.thingsboard.server.service.entitiy.entityview.TbEntityViewService; import org.thingsboard.server.service.mail.EdgeMailRequest; +import org.thingsboard.server.service.mail.MailExecutorService; import org.thingsboard.server.service.notification.EdgeNotificationRequest; import org.thingsboard.server.service.sms.EdgeSmsRequest; +import org.thingsboard.server.service.sms.SmsExecutorService; import org.thingsboard.server.service.executors.DbCallbackExecutorService; +import org.thingsboard.server.service.executors.NotificationExecutorService; import org.thingsboard.server.service.state.DefaultDeviceStateService; +import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.UUID; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.TimeUnit; @Service @TbCoreComponent @@ -129,6 +139,26 @@ public class DefaultEdgeRequestsService implements EdgeRequestsService { @Autowired private NotificationSettingsService notificationSettingsService; + @Autowired + private MailExecutorService mailExecutor; + + @Autowired + private SmsExecutorService smsExecutor; + + @Autowired + private NotificationExecutorService notificationExecutor; + + @Value("${edges.rpc.delegated_send_timeout_sec:20}") + private int delegatedSendTimeoutSec; + + private final ScheduledExecutorService sendTimeoutScheduler = + ThingsBoardExecutors.newSingleThreadScheduledExecutor("edge-delegated-send-watchdog"); + + @PreDestroy + public void destroy() { + sendTimeoutScheduler.shutdownNow(); + } + @Override public ListenableFuture processRuleChainMetadataRequestMsg(TenantId tenantId, Edge edge, RuleChainMetadataRequestMsg ruleChainMetadataRequestMsg) { log.trace("[{}] processRuleChainMetadataRequestMsg [{}][{}]", tenantId, edge.getName(), ruleChainMetadataRequestMsg); @@ -452,11 +482,11 @@ public class DefaultEdgeRequestsService implements EdgeRequestsService { @Override public ListenableFuture processSendEmailMsg(TenantId tenantId, Edge edge, SendEmailUplinkMsg sendEmailUplinkMsg) { - return submitEdgeSend(tenantId, edge, "email", () -> sendEmailForEdge(tenantId, sendEmailUplinkMsg)); + return submitEdgeSend(tenantId, edge, "email", mailExecutor, () -> sendEmailForEdge(tenantId, sendEmailUplinkMsg)); } private void sendEmailForEdge(TenantId tenantId, SendEmailUplinkMsg sendEmailUplinkMsg) throws Exception { - EdgeMailRequest request = JacksonUtil.fromString(sendEmailUplinkMsg.getRequest(), EdgeMailRequest.class); + EdgeMailRequest request = parseSendRequest(sendEmailUplinkMsg.getRequest(), EdgeMailRequest.class); if (request == null || request.getMethod() == null) { log.warn("[{}] Received empty send email request from edge", tenantId); return; @@ -487,11 +517,11 @@ public class DefaultEdgeRequestsService implements EdgeRequestsService { @Override public ListenableFuture processSendSmsMsg(TenantId tenantId, Edge edge, SendSmsUplinkMsg sendSmsUplinkMsg) { - return submitEdgeSend(tenantId, edge, "sms", () -> sendSmsForEdge(tenantId, sendSmsUplinkMsg)); + return submitEdgeSend(tenantId, edge, "sms", smsExecutor, () -> sendSmsForEdge(tenantId, sendSmsUplinkMsg)); } private void sendSmsForEdge(TenantId tenantId, SendSmsUplinkMsg sendSmsUplinkMsg) throws Exception { - EdgeSmsRequest request = JacksonUtil.fromString(sendSmsUplinkMsg.getRequest(), EdgeSmsRequest.class); + EdgeSmsRequest request = parseSendRequest(sendSmsUplinkMsg.getRequest(), EdgeSmsRequest.class); if (request == null || request.getMethod() == null) { log.warn("[{}] Received empty send sms request from edge", tenantId); return; @@ -506,24 +536,31 @@ public class DefaultEdgeRequestsService implements EdgeRequestsService { @Override public ListenableFuture processSendNotificationMsg(TenantId tenantId, Edge edge, SendNotificationUplinkMsg sendNotificationUplinkMsg) { - return submitEdgeSend(tenantId, edge, "notification", () -> sendNotificationForEdge(tenantId, sendNotificationUplinkMsg)); + return submitEdgeSend(tenantId, edge, "notification", notificationExecutor, () -> sendNotificationForEdge(tenantId, sendNotificationUplinkMsg)); } - private ListenableFuture submitEdgeSend(TenantId tenantId, Edge edge, String what, EdgeSendTask task) { + private ListenableFuture submitEdgeSend(TenantId tenantId, Edge edge, String what, + ListeningExecutor executor, EdgeSendTask task) { log.trace("[{}] processing edge-delegated {} send [{}]", tenantId, what, edge.getName()); - dbCallbackExecutorService.submit(() -> { - try { - task.execute(); - } catch (Exception e) { - log.warn("[{}] Failed to send {} requested by edge [{}]", tenantId, what, edge.getName(), e); - } + ListenableFuture future = Futures.withTimeout(executor.submit(() -> { + task.execute(); return null; - }); - return Futures.immediateFuture(null); + }), delegatedSendTimeoutSec, TimeUnit.SECONDS, sendTimeoutScheduler); + Futures.addCallback(future, new FutureCallback<>() { + @Override + public void onSuccess(@Nullable Void result) { + } + + @Override + public void onFailure(Throwable t) { + log.warn("[{}] Failed to send {} requested by edge [{}]", tenantId, what, edge.getName(), t); + } + }, dbCallbackExecutorService); + return future; } private void sendNotificationForEdge(TenantId tenantId, SendNotificationUplinkMsg sendNotificationUplinkMsg) throws Exception { - EdgeNotificationRequest request = JacksonUtil.fromString(sendNotificationUplinkMsg.getRequest(), EdgeNotificationRequest.class); + EdgeNotificationRequest request = parseSendRequest(sendNotificationUplinkMsg.getRequest(), EdgeNotificationRequest.class); if (request == null || request.getMethod() == null) { log.warn("[{}] Received empty send notification request from edge", tenantId); return; @@ -574,6 +611,10 @@ public class DefaultEdgeRequestsService implements EdgeRequestsService { return config; } + private static T parseSendRequest(String request, Class clazz) throws IOException { + return request != null ? JacksonUtil.IGNORE_UNKNOWN_PROPERTIES_JSON_MAPPER.readValue(request, clazz) : null; + } + private ListenableFuture saveEdgeEvent(TenantId tenantId, EdgeId edgeId, EdgeEventType type, diff --git a/application/src/main/resources/thingsboard.yml b/application/src/main/resources/thingsboard.yml index 2de4c21c8a..a7c8c9b093 100644 --- a/application/src/main/resources/thingsboard.yml +++ b/application/src/main/resources/thingsboard.yml @@ -1618,6 +1618,10 @@ edges: max_inbound_message_size: "${EDGES_RPC_MAX_INBOUND_MESSAGE_SIZE:4194304}" # Maximum length of telemetry (time-series and attributes) message the cloud sends to the edge. By default, there is no limitation. max_telemetry_message_size: "${EDGES_RPC_MAX_TELEMETRY_MESSAGE_SIZE:0}" + # Maximum time the cloud spends on a mail/SMS/notification send delegated by the edge before failing it. + # Must stay below the edge's 'cloud.uplink_pack_timeout_sec' (60 seconds by default): if the uplink is not + # answered in time the edge resends everything still unacknowledged, which delivers the same mail or SMS twice. + delegated_send_timeout_sec: "${EDGES_RPC_DELEGATED_SEND_TIMEOUT_SEC:20}" storage: # Max records of edge event to read from DB and sent to the edge max_read_records_count: "${EDGES_STORAGE_MAX_READ_RECORDS_COUNT:50}" From 59a68d02a9d4499c3ab3ceec419903bd0e154f57 Mon Sep 17 00:00:00 2001 From: Nikita Mazurenko Date: Tue, 22 Sep 2026 12:42:38 +0200 Subject: [PATCH 13/16] Propagate transient FCM failures for edge-delegated push --- .../edge/rpc/sync/DefaultEdgeRequestsService.java | 14 +++++++++++--- 1 file changed, 11 insertions(+), 3 deletions(-) diff --git a/application/src/main/java/org/thingsboard/server/service/edge/rpc/sync/DefaultEdgeRequestsService.java b/application/src/main/java/org/thingsboard/server/service/edge/rpc/sync/DefaultEdgeRequestsService.java index 03c8d11f07..96964f59f8 100644 --- a/application/src/main/java/org/thingsboard/server/service/edge/rpc/sync/DefaultEdgeRequestsService.java +++ b/application/src/main/java/org/thingsboard/server/service/edge/rpc/sync/DefaultEdgeRequestsService.java @@ -8,6 +8,8 @@ import com.google.common.util.concurrent.FutureCallback; import com.google.common.util.concurrent.Futures; import com.google.common.util.concurrent.ListenableFuture; import com.google.common.util.concurrent.SettableFuture; +import com.google.firebase.messaging.FirebaseMessagingException; +import com.google.firebase.messaging.MessagingErrorCode; import jakarta.annotation.PreDestroy; import lombok.extern.slf4j.Slf4j; import org.checkerframework.checker.nullness.qual.Nullable; @@ -580,7 +582,7 @@ public class DefaultEdgeRequestsService implements EdgeRequestsService { slackService.sendMessage(tenantId, config.getBotToken(), request.getConversationId(), request.getMessage()); } - private void sendMobilePushForEdge(TenantId tenantId, EdgeNotificationRequest request) { + private void sendMobilePushForEdge(TenantId tenantId, EdgeNotificationRequest request) throws Exception { MobileAppNotificationDeliveryMethodConfig config = getMobileAppConfig(tenantId); if (config == null || request.getFcmTokens() == null) { log.warn("[{}] Mobile app notifications are not configured on the cloud; dropping edge-delegated push", tenantId); @@ -590,8 +592,14 @@ public class DefaultEdgeRequestsService implements EdgeRequestsService { for (String fcmToken : request.getFcmTokens()) { try { firebaseService.sendMessage(tenantId, credentials, fcmToken, request.getSubject(), request.getBody(), request.getData(), request.getBadge()); - } catch (Exception e) { - log.warn("[{}] Failed to push edge-delegated notification to FCM token", tenantId, e); + } catch (FirebaseMessagingException e) { + MessagingErrorCode errorCode = e.getMessagingErrorCode(); + if (MessagingErrorCode.UNREGISTERED == errorCode || MessagingErrorCode.INVALID_ARGUMENT == errorCode + || MessagingErrorCode.SENDER_ID_MISMATCH == errorCode) { + log.debug("[{}] Edge-delegated push rejected, FCM token is no longer valid: {}", tenantId, errorCode); + continue; + } + throw e; } } } From 24274cb50b9929cc36f6d7fa5e9284b66fec064e Mon Sep 17 00:00:00 2001 From: Nikita Mazurenko Date: Tue, 22 Sep 2026 14:06:56 +0200 Subject: [PATCH 14/16] Fix license header in EdgeGrpcServiceTest --- .../server/service/edge/rpc/EdgeGrpcServiceTest.java | 2 ++ 1 file changed, 2 insertions(+) diff --git a/application/src/test/java/org/thingsboard/server/service/edge/rpc/EdgeGrpcServiceTest.java b/application/src/test/java/org/thingsboard/server/service/edge/rpc/EdgeGrpcServiceTest.java index 7b71c65c9f..74cc3e2153 100644 --- a/application/src/test/java/org/thingsboard/server/service/edge/rpc/EdgeGrpcServiceTest.java +++ b/application/src/test/java/org/thingsboard/server/service/edge/rpc/EdgeGrpcServiceTest.java @@ -1,3 +1,5 @@ +// SPDX-FileCopyrightText: Copyright The Thingsboard Authors +// SPDX-License-Identifier: Apache-2.0 /** * Copyright © 2016-2026 The Thingsboard Authors * From ad6cc38eb4f9a53bb0fe200c5841b97d36c88358 Mon Sep 17 00:00:00 2001 From: Nikita Mazurenko Date: Tue, 22 Sep 2026 14:07:22 +0200 Subject: [PATCH 15/16] Remove stale license header in EdgeGrpcServiceTest --- .../service/edge/rpc/EdgeGrpcServiceTest.java | 15 --------------- 1 file changed, 15 deletions(-) diff --git a/application/src/test/java/org/thingsboard/server/service/edge/rpc/EdgeGrpcServiceTest.java b/application/src/test/java/org/thingsboard/server/service/edge/rpc/EdgeGrpcServiceTest.java index 74cc3e2153..80730f9f53 100644 --- a/application/src/test/java/org/thingsboard/server/service/edge/rpc/EdgeGrpcServiceTest.java +++ b/application/src/test/java/org/thingsboard/server/service/edge/rpc/EdgeGrpcServiceTest.java @@ -1,20 +1,5 @@ // SPDX-FileCopyrightText: Copyright The Thingsboard Authors // SPDX-License-Identifier: Apache-2.0 -/** - * Copyright © 2016-2026 The Thingsboard Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ package org.thingsboard.server.service.edge.rpc; import org.junit.jupiter.api.BeforeEach; From c2190d387376bd51d08af59108262db6e69d3343 Mon Sep 17 00:00:00 2001 From: Nikita Mazurenko Date: Sat, 24 Oct 2026 17:38:14 +0200 Subject: [PATCH 16/16] Keep syncing system general and connectivity settings to edge --- .../service/edge/rpc/EdgeSyncCursor.java | 5 +++-- .../settings/AdminSettingsEdgeProcessor.java | 4 +--- .../server/controller/EdgeControllerTest.java | 18 +++++++++++++++++ .../server/edge/AbstractEdgeTest.java | 8 ++++---- .../AdminSettingsEdgeProcessorTest.java | 20 ++++++++++++++++--- 5 files changed, 43 insertions(+), 12 deletions(-) diff --git a/application/src/main/java/org/thingsboard/server/service/edge/rpc/EdgeSyncCursor.java b/application/src/main/java/org/thingsboard/server/service/edge/rpc/EdgeSyncCursor.java index 0bf73d7b92..a35c88be07 100644 --- a/application/src/main/java/org/thingsboard/server/service/edge/rpc/EdgeSyncCursor.java +++ b/application/src/main/java/org/thingsboard/server/service/edge/rpc/EdgeSyncCursor.java @@ -8,6 +8,7 @@ import org.thingsboard.server.common.data.edge.Edge; import org.thingsboard.server.common.data.id.EntityId; import org.thingsboard.server.common.data.id.TenantId; import org.thingsboard.server.service.edge.EdgeContextComponent; +import org.thingsboard.server.service.edge.rpc.fetch.AdminSettingsEdgeEventFetcher; import org.thingsboard.server.service.edge.rpc.fetch.AssetProfilesEdgeEventFetcher; import org.thingsboard.server.service.edge.rpc.fetch.AssetsEdgeEventFetcher; import org.thingsboard.server.service.edge.rpc.fetch.CustomerEdgeEventFetcher; @@ -49,8 +50,8 @@ public class EdgeSyncCursor { fetchers.add(new TenantEdgeEventFetcher(ctx.getTenantService())); fetchers.add(new QueuesEdgeEventFetcher(ctx.getQueueService())); fetchers.add(new RuleChainsEdgeEventFetcher(ctx.getRuleChainService())); - // Admin settings are not synced to the edge: 'general'/'connectivity' are system-scoped and the edge - // auto-generates its own on install, while 'mail'/'sms'/'notifications' are delegated to the cloud. + fetchers.add(new AdminSettingsEdgeEventFetcher(ctx.getAdminSettingsService(), TenantId.SYS_TENANT_ID)); + fetchers.add(new AdminSettingsEdgeEventFetcher(ctx.getAdminSettingsService(), edge.getTenantId())); fetchers.add(new TenantAdminUsersEdgeEventFetcher(ctx.getUserService())); } Customer publicCustomer = ctx.getCustomerService().findPublicCustomer(edge.getTenantId()); diff --git a/application/src/main/java/org/thingsboard/server/service/edge/rpc/processor/settings/AdminSettingsEdgeProcessor.java b/application/src/main/java/org/thingsboard/server/service/edge/rpc/processor/settings/AdminSettingsEdgeProcessor.java index a43808d2da..f1e0400100 100644 --- a/application/src/main/java/org/thingsboard/server/service/edge/rpc/processor/settings/AdminSettingsEdgeProcessor.java +++ b/application/src/main/java/org/thingsboard/server/service/edge/rpc/processor/settings/AdminSettingsEdgeProcessor.java @@ -10,7 +10,6 @@ import org.thingsboard.server.common.data.EdgeUtils; import org.thingsboard.server.common.data.edge.EdgeEvent; import org.thingsboard.server.common.data.edge.EdgeEventType; import org.thingsboard.server.common.data.id.AdminSettingsId; -import org.thingsboard.server.common.data.id.TenantId; import org.thingsboard.server.gen.edge.v1.AdminSettingsUpdateMsg; import org.thingsboard.server.gen.edge.v1.DownlinkMsg; import org.thingsboard.server.gen.edge.v1.EdgeVersion; @@ -39,8 +38,7 @@ public class AdminSettingsEdgeProcessor extends BaseEdgeProcessor { if (adminSettings == null) { return null; } - if (TenantId.SYS_TENANT_ID.equals(adminSettings.getTenantId()) - || !EDGE_SYNCED_SETTINGS_KEYS.contains(adminSettings.getKey())) { + if (!EDGE_SYNCED_SETTINGS_KEYS.contains(adminSettings.getKey())) { log.trace("Skipping admin settings [{}] sync to edge [{}] - not in the edge allow-list", adminSettings.getKey(), edgeEvent.getEdgeId()); return null; diff --git a/application/src/test/java/org/thingsboard/server/controller/EdgeControllerTest.java b/application/src/test/java/org/thingsboard/server/controller/EdgeControllerTest.java index 379d038577..080d5ecf63 100644 --- a/application/src/test/java/org/thingsboard/server/controller/EdgeControllerTest.java +++ b/application/src/test/java/org/thingsboard/server/controller/EdgeControllerTest.java @@ -29,6 +29,7 @@ import org.springframework.test.context.TestPropertySource; import org.springframework.test.util.TestSocketUtils; import org.thingsboard.common.util.JacksonUtil; import org.thingsboard.common.util.ThingsBoardExecutors; +import org.thingsboard.server.common.data.AdminSettings; import org.thingsboard.server.common.data.AttributeScope; import org.thingsboard.server.common.data.Customer; import org.thingsboard.server.common.data.Device; @@ -65,6 +66,7 @@ import org.thingsboard.server.dao.exception.DataValidationException; import org.thingsboard.server.dao.model.ModelConstants; import org.thingsboard.server.dao.service.DaoSqlTest; import org.thingsboard.server.edge.imitator.EdgeImitator; +import org.thingsboard.server.gen.edge.v1.AdminSettingsUpdateMsg; import org.thingsboard.server.gen.edge.v1.AssetProfileUpdateMsg; import org.thingsboard.server.gen.edge.v1.AssetUpdateMsg; import org.thingsboard.server.gen.edge.v1.CustomerUpdateMsg; @@ -997,6 +999,8 @@ public class EdgeControllerTest extends AbstractControllerTest { Assert.assertTrue(popQueueMsg(edgeImitator.getDownlinkMsgsDeque(), UpdateMsgType.ENTITY_CREATED_RPC_MESSAGE, "Main")); Assert.assertTrue(popRuleChainMsg(edgeImitator.getDownlinkMsgsDeque(), UpdateMsgType.ENTITY_CREATED_RPC_MESSAGE, "Edge Root Rule Chain")); Assert.assertTrue(popRuleChainMetadataMsg(edgeImitator.getDownlinkMsgsDeque(), UpdateMsgType.ENTITY_CREATED_RPC_MESSAGE, getEdgeRootRuleChainId(edgeImitator))); + Assert.assertTrue(popAdminSettingsMsg(edgeImitator.getDownlinkMsgsDeque(), "general")); + Assert.assertTrue(popAdminSettingsMsg(edgeImitator.getDownlinkMsgsDeque(), "connectivity")); Assert.assertTrue(popDeviceProfileMsg(edgeImitator.getDownlinkMsgsDeque(), UpdateMsgType.ENTITY_CREATED_RPC_MESSAGE, "default")); Assert.assertTrue(popDeviceProfileMsg(edgeImitator.getDownlinkMsgsDeque(), UpdateMsgType.ENTITY_CREATED_RPC_MESSAGE, "default")); Assert.assertTrue(popAssetProfileMsg(edgeImitator.getDownlinkMsgsDeque(), UpdateMsgType.ENTITY_CREATED_RPC_MESSAGE, "default")); @@ -1060,6 +1064,20 @@ public class EdgeControllerTest extends AbstractControllerTest { return false; } + private boolean popAdminSettingsMsg(Deque messages, String key) { + for (AbstractMessage message : messages) { + if (message instanceof AdminSettingsUpdateMsg adminSettingsUpdateMsg) { + AdminSettings adminSettings = JacksonUtil.fromString(adminSettingsUpdateMsg.getEntity(), AdminSettings.class, true); + Assert.assertNotNull(adminSettings); + if (key.equals(adminSettings.getKey())) { + messages.remove(message); + return true; + } + } + } + return false; + } + private boolean popDeviceProfileMsg(Deque messages, UpdateMsgType msgType, String name) { for (AbstractMessage message : messages) { if (message instanceof DeviceProfileUpdateMsg deviceProfileUpdateMsg) { diff --git a/application/src/test/java/org/thingsboard/server/edge/AbstractEdgeTest.java b/application/src/test/java/org/thingsboard/server/edge/AbstractEdgeTest.java index d6dfa1a953..8066eadde3 100644 --- a/application/src/test/java/org/thingsboard/server/edge/AbstractEdgeTest.java +++ b/application/src/test/java/org/thingsboard/server/edge/AbstractEdgeTest.java @@ -118,7 +118,7 @@ abstract public class AbstractEdgeTest extends AbstractControllerTest { registry.add("edges.rpc.port", () -> EDGE_PORT); } - public static final Integer CONNECT_MESSAGE_COUNT = 13; + public static final Integer CONNECT_MESSAGE_COUNT = 15; public static final Integer INSTALLATION_MESSAGE_COUNT = 8; public static final Integer SYNC_MESSAGE_COUNT = CONNECT_MESSAGE_COUNT + INSTALLATION_MESSAGE_COUNT; private static final String THERMOSTAT_DEVICE_PROFILE_NAME = "Thermostat"; @@ -279,9 +279,9 @@ abstract public class AbstractEdgeTest extends AbstractControllerTest { validateMsgsCnt(RuleChainMetadataUpdateMsg.class, 1); validateRuleChainMetadataUpdates(ruleChainUUID); - // No admin settings are synced to the edge: 'general'/'connectivity' are system-scoped and the edge - // auto-generates its own, while 'mail'/'sms'/'notifications' are delegated to the cloud. - validateMsgsCnt(AdminSettingsUpdateMsg.class, 0); + // 2 messages ('general', 'connectivity') + validateMsgsCnt(AdminSettingsUpdateMsg.class, 2); + validateAdminSettings(2); // 4 messages // - 1 from default profile fetcher diff --git a/application/src/test/java/org/thingsboard/server/service/edge/rpc/processor/settings/AdminSettingsEdgeProcessorTest.java b/application/src/test/java/org/thingsboard/server/service/edge/rpc/processor/settings/AdminSettingsEdgeProcessorTest.java index 70598f6c67..308bc83696 100644 --- a/application/src/test/java/org/thingsboard/server/service/edge/rpc/processor/settings/AdminSettingsEdgeProcessorTest.java +++ b/application/src/test/java/org/thingsboard/server/service/edge/rpc/processor/settings/AdminSettingsEdgeProcessorTest.java @@ -6,6 +6,8 @@ import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; import org.springframework.test.util.ReflectionTestUtils; @@ -69,9 +71,21 @@ public class AdminSettingsEdgeProcessorTest { } @Test - public void testSystemScopedAllowListedKeyIsNotSyncedToEdge() { - AdminSettings general = adminSettings(TenantId.SYS_TENANT_ID, "general"); - when(adminSettingsService.findAdminSettingsById(any(), any())).thenReturn(general); + public void testSystemScopedAllowListedKeyIsSyncedToEdge() { + AdminSettings connectivity = adminSettings(TenantId.SYS_TENANT_ID, "connectivity"); + when(adminSettingsService.findAdminSettingsById(any(), any())).thenReturn(connectivity); + + DownlinkMsg downlink = processor.convertEdgeEventToDownlink(edgeEvent(TenantId.SYS_TENANT_ID), EdgeVersion.V_4_2_2_4); + + Assertions.assertNotNull(downlink); + Assertions.assertEquals(1, downlink.getAdminSettingsUpdateMsgCount()); + } + + @ParameterizedTest + @ValueSource(strings = {"mail", "jwt", "sms", "notifications"}) + public void testSystemScopedNonAllowListedKeyIsNotSyncedToEdge(String key) { + AdminSettings settings = adminSettings(TenantId.SYS_TENANT_ID, key); + when(adminSettingsService.findAdminSettingsById(any(), any())).thenReturn(settings); DownlinkMsg downlink = processor.convertEdgeEventToDownlink(edgeEvent(TenantId.SYS_TENANT_ID), EdgeVersion.V_4_2_2_4);