Browse Source

Merge pull request #15941 from MazurenkoNick/fix/send-email-uplink-43

Receive mail/SMS/notification uplink requests from edge
pull/16432/head
Viacheslav Klimov 1 month ago
committed by GitHub
parent
commit
f382b6d538
No known key found for this signature in database GPG Key ID: B5690EEEBB952194
  1. 18
      application/src/main/java/org/thingsboard/server/service/edge/rpc/EdgeGrpcSession.java
  2. 9
      application/src/main/java/org/thingsboard/server/service/edge/rpc/processor/settings/AdminSettingsEdgeProcessor.java
  3. 208
      application/src/main/java/org/thingsboard/server/service/edge/rpc/sync/DefaultEdgeRequestsService.java
  4. 9
      application/src/main/java/org/thingsboard/server/service/edge/rpc/sync/EdgeRequestsService.java
  5. 67
      application/src/main/java/org/thingsboard/server/service/mail/EdgeMailRequest.java
  6. 63
      application/src/main/java/org/thingsboard/server/service/notification/EdgeNotificationRequest.java
  7. 38
      application/src/main/java/org/thingsboard/server/service/sms/EdgeSmsRequest.java
  8. 4
      application/src/main/resources/thingsboard.yml
  9. 2
      application/src/test/java/org/thingsboard/server/controller/EdgeControllerTest.java
  10. 21
      application/src/test/java/org/thingsboard/server/edge/AbstractEdgeTest.java
  11. 66
      application/src/test/java/org/thingsboard/server/edge/AdminSettingsEdgeTest.java
  12. 197
      application/src/test/java/org/thingsboard/server/edge/SendEmailEdgeTest.java
  13. 112
      application/src/test/java/org/thingsboard/server/edge/SendNotificationEdgeTest.java
  14. 71
      application/src/test/java/org/thingsboard/server/edge/SendSmsEdgeTest.java
  15. 112
      application/src/test/java/org/thingsboard/server/service/edge/rpc/processor/settings/AdminSettingsEdgeProcessorTest.java
  16. 25
      common/edge-api/src/main/proto/edge.proto

18
application/src/main/java/org/thingsboard/server/service/edge/rpc/EdgeGrpcSession.java

@ -69,6 +69,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;
@ -943,6 +946,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));

9
application/src/main/java/org/thingsboard/server/service/edge/rpc/processor/settings/AdminSettingsEdgeProcessor.java

@ -16,11 +16,15 @@ 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 java.util.Set;
@Slf4j
@Component
@TbCoreComponent
public class AdminSettingsEdgeProcessor extends BaseEdgeProcessor {
private static final Set<String> EDGE_SYNCED_SETTINGS_KEYS = Set.of("general", "connectivity");
@Override
public DownlinkMsg convertEdgeEventToDownlink(EdgeEvent edgeEvent, EdgeVersion edgeVersion) {
AdminSettings adminSettings = null;
@ -34,6 +38,11 @@ public class AdminSettingsEdgeProcessor extends BaseEdgeProcessor {
if (adminSettings == null) {
return null;
}
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;
}
AdminSettingsUpdateMsg msg = AdminSettingsUpdateMsg.newBuilder().setEntity(JacksonUtil.toString(adminSettings)).build();
return DownlinkMsg.newBuilder()
.setDownlinkMsgId(EdgeUtils.nextPositiveInt())

208
application/src/main/java/org/thingsboard/server/service/edge/rpc/sync/DefaultEdgeRequestsService.java

@ -8,12 +8,22 @@ 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;
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;
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;
@ -33,6 +43,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;
@ -43,6 +57,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;
@ -53,18 +68,30 @@ 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.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
@ -99,6 +126,41 @@ 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;
@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<Void> processRuleChainMetadataRequestMsg(TenantId tenantId, Edge edge, RuleChainMetadataRequestMsg ruleChainMetadataRequestMsg) {
log.trace("[{}] processRuleChainMetadataRequestMsg [{}][{}]", tenantId, edge.getName(), ruleChainMetadataRequestMsg);
@ -420,6 +482,147 @@ public class DefaultEdgeRequestsService implements EdgeRequestsService {
return futureToSet;
}
@Override
public ListenableFuture<Void> processSendEmailMsg(TenantId tenantId, Edge edge, SendEmailUplinkMsg sendEmailUplinkMsg) {
return submitEdgeSend(tenantId, edge, "email", mailExecutor, () -> sendEmailForEdge(tenantId, sendEmailUplinkMsg));
}
private void sendEmailForEdge(TenantId tenantId, SendEmailUplinkMsg sendEmailUplinkMsg) throws Exception {
EdgeMailRequest request = parseSendRequest(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<Void> processSendSmsMsg(TenantId tenantId, Edge edge, SendSmsUplinkMsg sendSmsUplinkMsg) {
return submitEdgeSend(tenantId, edge, "sms", smsExecutor, () -> sendSmsForEdge(tenantId, sendSmsUplinkMsg));
}
private void sendSmsForEdge(TenantId tenantId, SendSmsUplinkMsg sendSmsUplinkMsg) throws Exception {
EdgeSmsRequest request = parseSendRequest(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<Void> processSendNotificationMsg(TenantId tenantId, Edge edge, SendNotificationUplinkMsg sendNotificationUplinkMsg) {
return submitEdgeSend(tenantId, edge, "notification", notificationExecutor, () -> sendNotificationForEdge(tenantId, sendNotificationUplinkMsg));
}
private ListenableFuture<Void> submitEdgeSend(TenantId tenantId, Edge edge, String what,
ListeningExecutor executor, EdgeSendTask task) {
log.trace("[{}] processing edge-delegated {} send [{}]", tenantId, what, edge.getName());
ListenableFuture<Void> future = Futures.withTimeout(executor.submit(() -> {
task.execute();
return 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 = parseSendRequest(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) 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);
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 (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;
}
}
}
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 static <T> T parseSendRequest(String request, Class<T> clazz) throws IOException {
return request != null ? JacksonUtil.IGNORE_UNKNOWN_PROPERTIES_JSON_MAPPER.readValue(request, clazz) : null;
}
private ListenableFuture<Void> saveEdgeEvent(TenantId tenantId,
EdgeId edgeId,
EdgeEventType type,
@ -433,4 +636,9 @@ public class DefaultEdgeRequestsService implements EdgeRequestsService {
return edgeEventService.saveAsync(edgeEvent);
}
@FunctionalInterface
private interface EdgeSendTask {
void execute() throws Exception;
}
}

9
application/src/main/java/org/thingsboard/server/service/edge/rpc/sync/EdgeRequestsService.java

@ -11,6 +11,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;
@ -37,4 +40,10 @@ public interface EdgeRequestsService {
@Deprecated(since = "3.9.1", forRemoval = true)
ListenableFuture<Void> processEntityViewsRequestMsg(TenantId tenantId, Edge edge, EntityViewsRequestMsg entityViewsRequestMsg);
ListenableFuture<Void> processSendEmailMsg(TenantId tenantId, Edge edge, SendEmailUplinkMsg sendEmailUplinkMsg);
ListenableFuture<Void> processSendSmsMsg(TenantId tenantId, Edge edge, SendSmsUplinkMsg sendSmsUplinkMsg);
ListenableFuture<Void> processSendNotificationMsg(TenantId tenantId, Edge edge, SendNotificationUplinkMsg sendNotificationUplinkMsg);
}

67
application/src/main/java/org/thingsboard/server/service/mail/EdgeMailRequest.java

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

63
application/src/main/java/org/thingsboard/server/service/notification/EdgeNotificationRequest.java

@ -0,0 +1,63 @@
// SPDX-FileCopyrightText: Copyright The Thingsboard Authors
// SPDX-License-Identifier: Apache-2.0
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:
* <ul>
* <li>{@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.</li>
* <li>{@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}.</li>
* </ul>
*/
@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<SlackFileData> files;
// SEND_MOBILE_PUSH
private Set<String> fcmTokens;
private String subject;
private String body;
private Map<String, String> data;
private Integer badge;
@Data
@NoArgsConstructor
@AllArgsConstructor
public static class SlackFileData {
private String name;
private String type;
private byte[] data;
}
}

38
application/src/main/java/org/thingsboard/server/service/sms/EdgeSmsRequest.java

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

4
application/src/main/resources/thingsboard.yml

@ -1639,6 +1639,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}"

2
application/src/test/java/org/thingsboard/server/controller/EdgeControllerTest.java

@ -1000,9 +1000,7 @@ public class EdgeControllerTest extends AbstractControllerTest {
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"));

21
application/src/test/java/org/thingsboard/server/edge/AbstractEdgeTest.java

@ -24,6 +24,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.HasVersion;
@ -88,6 +89,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;
@ -99,6 +101,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;
@ -118,7 +121,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 = 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";
@ -131,6 +134,16 @@ abstract public class AbstractEdgeTest extends AbstractControllerTest {
@Autowired
protected EdgeEventService edgeEventService;
protected void sendUplinkMsgAndWaitForResponse(Consumer<UplinkMsg.Builder> 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();
@ -276,9 +289,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);
// 2 messages ('general', 'connectivity')
validateMsgsCnt(AdminSettingsUpdateMsg.class, 2);
validateAdminSettings(2);
// 4 messages
// - 1 from default profile fetcher

66
application/src/test/java/org/thingsboard/server/edge/AdminSettingsEdgeTest.java

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

197
application/src/test/java/org/thingsboard/server/edge/SendEmailEdgeTest.java

@ -0,0 +1,197 @@
// SPDX-FileCopyrightText: Copyright The Thingsboard Authors
// SPDX-License-Identifier: Apache-2.0
package org.thingsboard.server.edge;
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.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.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("<b>Edge test body</b>")
.build();
sendEmailUplink(request);
verify(mailService, timeout(30000))
.sendEmail(eq(tenantId), eq("recipient@thingsboard.io"), eq("Edge test subject"), eq("<b>Edge test body</b>"));
}
@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));
}
@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();
sendUplinkMsgAndWaitForResponse(builder -> builder.addSendEmailUplinkMsg(sendEmailUplinkMsg));
}
}

112
application/src/test/java/org/thingsboard/server/edge/SendNotificationEdgeTest.java

@ -0,0 +1,112 @@
// SPDX-FileCopyrightText: Copyright The Thingsboard Authors
// SPDX-License-Identifier: Apache-2.0
package org.thingsboard.server.edge;
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.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.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<NotificationDeliveryMethod, NotificationDeliveryMethodConfig> 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<NotificationDeliveryMethod, NotificationDeliveryMethodConfig> 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();
sendUplinkMsgAndWaitForResponse(builder -> builder.addSendNotificationUplinkMsg(sendNotificationUplinkMsg));
}
}

71
application/src/test/java/org/thingsboard/server/edge/SendSmsEdgeTest.java

@ -0,0 +1,71 @@
// SPDX-FileCopyrightText: Copyright The Thingsboard Authors
// SPDX-License-Identifier: Apache-2.0
package org.thingsboard.server.edge;
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.sms.config.TestSmsRequest;
import org.thingsboard.server.dao.service.DaoSqlTest;
import org.thingsboard.server.gen.edge.v1.SendSmsUplinkMsg;
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 SendSmsEdgeTest 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();
sendUplinkMsgAndWaitForResponse(builder -> builder.addSendSmsUplinkMsg(sendSmsUplinkMsg));
}
}

112
application/src/test/java/org/thingsboard/server/service/edge/rpc/processor/settings/AdminSettingsEdgeProcessorTest.java

@ -0,0 +1,112 @@
// SPDX-FileCopyrightText: Copyright The Thingsboard Authors
// SPDX-License-Identifier: Apache-2.0
package org.thingsboard.server.service.edge.rpc.processor.settings;
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;
import org.thingsboard.common.util.JacksonUtil;
import org.thingsboard.server.common.data.AdminSettings;
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.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.UUID;
import static org.mockito.ArgumentMatchers.any;
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);
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 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);
Assertions.assertNull(downlink);
}
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;
}
}

25
common/edge-api/src/main/proto/edge.proto

@ -360,6 +360,28 @@ 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;
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;
@ -465,6 +487,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 {

Loading…
Cancel
Save