From a6dcad4d79ecc125d7b2a327f0d1c32b25c2a6d8 Mon Sep 17 00:00:00 2001 From: Viacheslav Klimov Date: Thu, 12 Nov 2026 01:00:25 +0200 Subject: [PATCH] Use only notification templates and recipient groups of the rule's or request's tenant --- .../NotificationRuleController.java | 14 ++ .../DefaultNotificationCenter.java | 9 +- .../notification/NotificationApiTest.java | 36 +++++ .../notification/NotificationRuleApiTest.java | 133 ++++++++++++++++++ 4 files changed, 191 insertions(+), 1 deletion(-) diff --git a/application/src/main/java/org/thingsboard/server/controller/NotificationRuleController.java b/application/src/main/java/org/thingsboard/server/controller/NotificationRuleController.java index 62bf235899..4fdab6f437 100644 --- a/application/src/main/java/org/thingsboard/server/controller/NotificationRuleController.java +++ b/application/src/main/java/org/thingsboard/server/controller/NotificationRuleController.java @@ -19,17 +19,21 @@ import org.springframework.web.bind.annotation.RestController; import org.thingsboard.server.common.data.EntityType; import org.thingsboard.server.common.data.exception.ThingsboardException; import org.thingsboard.server.common.data.id.NotificationRuleId; +import org.thingsboard.server.common.data.id.NotificationTargetId; import org.thingsboard.server.common.data.notification.rule.NotificationRule; import org.thingsboard.server.common.data.notification.rule.NotificationRuleInfo; import org.thingsboard.server.common.data.notification.rule.trigger.config.NotificationRuleTriggerType; +import org.thingsboard.server.common.data.notification.template.NotificationTemplate; import org.thingsboard.server.common.data.page.PageData; import org.thingsboard.server.common.data.page.PageLink; import org.thingsboard.server.config.annotations.ApiOperation; import org.thingsboard.server.dao.notification.NotificationRuleService; +import org.thingsboard.server.dao.notification.NotificationTemplateService; import org.thingsboard.server.queue.util.TbCoreComponent; import org.thingsboard.server.service.security.model.SecurityUser; import org.thingsboard.server.service.security.permission.Operation; +import java.util.List; import java.util.UUID; import static org.thingsboard.server.controller.ControllerConstants.MARKDOWN_CODE_BLOCK_END; @@ -51,6 +55,7 @@ import static org.thingsboard.server.service.security.permission.Resource.NOTIFI public class NotificationRuleController extends BaseController { private final NotificationRuleService notificationRuleService; + private final NotificationTemplateService notificationTemplateService; @ApiOperation(value = "Save notification rule (saveNotificationRule)", notes = "Creates or updates notification rule. " + NEW_LINE + @@ -110,6 +115,15 @@ public class NotificationRuleController extends BaseController { if ((user.isTenantAdmin() && !triggerType.isTenantLevel()) || (user.isSystemAdmin() && triggerType.isTenantLevel())) { throw new IllegalArgumentException("Trigger type " + triggerType + " is not available"); } + NotificationTemplate template = notificationTemplateService.findNotificationTemplateById(user.getTenantId(), notificationRule.getTemplateId()); + if (template == null || !(template.getTenantId().equals(user.getTenantId()) || template.getTenantId().isSysTenantId())) { + throw new IllegalArgumentException("Notification template not found"); + } + for (List targets : notificationRule.getRecipientsConfig().getTargetsTable().values()) { + for (UUID targetId : targets) { + checkNotificationTargetId(new NotificationTargetId(targetId), Operation.READ); + } + } return doSaveAndLog(EntityType.NOTIFICATION_RULE, notificationRule, notificationRuleService::saveNotificationRule); } diff --git a/application/src/main/java/org/thingsboard/server/service/notification/DefaultNotificationCenter.java b/application/src/main/java/org/thingsboard/server/service/notification/DefaultNotificationCenter.java index ced351585a..f69bbba146 100644 --- a/application/src/main/java/org/thingsboard/server/service/notification/DefaultNotificationCenter.java +++ b/application/src/main/java/org/thingsboard/server/service/notification/DefaultNotificationCenter.java @@ -103,6 +103,9 @@ public class DefaultNotificationCenter extends AbstractSubscriptionService imple NotificationTemplate notificationTemplate; if (request.getTemplateId() != null) { notificationTemplate = notificationTemplateService.findNotificationTemplateById(tenantId, request.getTemplateId()); + if (notificationTemplate != null && !isTenantOrSystem(tenantId, notificationTemplate.getTenantId())) { + notificationTemplate = null; + } } else { notificationTemplate = request.getTemplate(); } @@ -115,7 +118,7 @@ public class DefaultNotificationCenter extends AbstractSubscriptionService imple List targets = new ArrayList<>(); for (UUID targetId : request.getTargets()) { NotificationTarget target = notificationTargetService.findNotificationTargetById(tenantId, new NotificationTargetId(targetId)); - if (target != null) { + if (target != null && tenantId.equals(target.getTenantId())) { targets.add(target); } else { log.debug("Unknown notification target {} in request {}", targetId, request); @@ -480,6 +483,10 @@ public class DefaultNotificationCenter extends AbstractSubscriptionService imple return "notification"; } + private static boolean isTenantOrSystem(TenantId tenantId, TenantId ownerId) { + return tenantId.equals(ownerId) || ownerId.isSysTenantId(); + } + @Autowired public void setChannels(List channels, NotificationCenter webNotificationChannel) { this.channels = channels.stream().collect(Collectors.toMap(NotificationChannel::getDeliveryMethod, c -> c)); diff --git a/application/src/test/java/org/thingsboard/server/service/notification/NotificationApiTest.java b/application/src/test/java/org/thingsboard/server/service/notification/NotificationApiTest.java index 76576c5650..a29fbd88b1 100644 --- a/application/src/test/java/org/thingsboard/server/service/notification/NotificationApiTest.java +++ b/application/src/test/java/org/thingsboard/server/service/notification/NotificationApiTest.java @@ -1014,6 +1014,42 @@ public class NotificationApiTest extends AbstractNotificationApiTest { assertThat(getErrorMessage(result)).contains("can only be configured by system administrator"); } + @Test + public void testNotificationRequest_templateOfOtherTenant_returnsBadRequest() throws Exception { + loginDifferentTenant(); + NotificationTemplate otherTemplate = createNotificationTemplate(NotificationType.GENERAL, "Subject", "Text", NotificationDeliveryMethod.WEB); + loginTenantAdmin(); + NotificationTarget target = createNotificationTarget(tenantAdminUserId); + long requestsCount = findNotificationRequests().getTotalElements(); + + NotificationRequest notificationRequest = NotificationRequest.builder() + .targets(List.of(target.getUuidId())) + .templateId(otherTemplate.getId()) + .additionalConfig(new NotificationRequestConfig()) + .build(); + doPost("/api/notification/request", notificationRequest).andExpect(status().isBadRequest()); + + assertThat(findNotificationRequests().getTotalElements()).isEqualTo(requestsCount); + } + + @Test + public void testNotificationRequest_systemTemplate_isDelivered() throws Exception { + loginSysAdmin(); + NotificationTemplate systemTemplate = createNotificationTemplate(NotificationType.GENERAL, "Subject", "Text", NotificationDeliveryMethod.WEB); + loginTenantAdmin(); + NotificationTarget target = createNotificationTarget(tenantAdminUserId); + + NotificationRequest notificationRequest = NotificationRequest.builder() + .tenantId(tenantId) + .templateId(systemTemplate.getId()) + .originatorEntityId(tenantAdminUserId) + .targets(List.of(target.getUuidId())) + .build(); + NotificationRequestStats stats = submitNotificationRequestAndWait(notificationRequest); + assertThat(stats.getErrors()).isEmpty(); + assertThat(stats.getSent().get(NotificationDeliveryMethod.WEB).get()).isOne(); + } + private NotificationRequestStats submitNotificationRequestAndWait(NotificationRequest notificationRequest) throws Exception { SettableFuture future = SettableFuture.create(); notificationCenter.processNotificationRequest(notificationRequest.getTenantId(), notificationRequest, new FutureCallback<>() { diff --git a/application/src/test/java/org/thingsboard/server/service/notification/NotificationRuleApiTest.java b/application/src/test/java/org/thingsboard/server/service/notification/NotificationRuleApiTest.java index 1190518ad6..de36e1cf73 100644 --- a/application/src/test/java/org/thingsboard/server/service/notification/NotificationRuleApiTest.java +++ b/application/src/test/java/org/thingsboard/server/service/notification/NotificationRuleApiTest.java @@ -40,6 +40,7 @@ import org.thingsboard.server.common.data.device.profile.SimpleAlarmConditionSpe import org.thingsboard.server.common.data.edge.Edge; import org.thingsboard.server.common.data.id.AlarmId; import org.thingsboard.server.common.data.id.DeviceId; +import org.thingsboard.server.common.data.id.NotificationTemplateId; import org.thingsboard.server.common.data.id.TenantId; import org.thingsboard.server.common.data.limit.LimitedApi; import org.thingsboard.server.common.data.notification.Notification; @@ -900,6 +901,138 @@ public class NotificationRuleApiTest extends AbstractNotificationApiTest { }); } + @Test + public void testSaveNotificationRule_templateOfOtherTenant_returnsBadRequest() throws Exception { + loginDifferentTenant(); + NotificationTemplate otherTemplate = createNotificationTemplate(NotificationType.ENTITY_ACTION, "Created", "Created", NotificationDeliveryMethod.WEB); + loginTenantAdmin(); + NotificationTarget target = createNotificationTarget(tenantAdminUserId); + + NotificationRule rule = newDeviceCreatedRule(otherTemplate.getId(), List.of(target.getUuidId())); + doPost("/api/notification/rule", rule).andExpect(status().isBadRequest()); + + assertThat(findNotificationRules().getData()).extracting(NotificationRuleInfo::getName).doesNotContain(rule.getName()); + } + + @Test + public void testSaveNotificationRule_targetOfOtherTenant_returnsForbidden() throws Exception { + loginDifferentTenant(); + NotificationTarget otherTarget = createNotificationTarget(savedDifferentTenantUser.getId()); + loginTenantAdmin(); + NotificationTemplate template = createNotificationTemplate(NotificationType.ENTITY_ACTION, "Created", "Created", NotificationDeliveryMethod.WEB); + + NotificationRule rule = newDeviceCreatedRule(template.getId(), List.of(otherTarget.getUuidId())); + doPost("/api/notification/rule", rule).andExpect(status().isForbidden()); + + NotificationTemplate alarmTemplate = createNotificationTemplate(NotificationType.ALARM, "Alarm", "Alarm", NotificationDeliveryMethod.WEB); + NotificationTarget ownTarget = createNotificationTarget(tenantAdminUserId); + NotificationRule alarmRule = new NotificationRule(); + alarmRule.setName("Alarm rule " + UUID.randomUUID()); + alarmRule.setEnabled(true); + alarmRule.setTemplateId(alarmTemplate.getId()); + alarmRule.setTriggerType(NotificationRuleTriggerType.ALARM); + AlarmNotificationRuleTriggerConfig triggerConfig = new AlarmNotificationRuleTriggerConfig(); + triggerConfig.setNotifyOn(Set.of(AlarmAction.CREATED)); + alarmRule.setTriggerConfig(triggerConfig); + EscalatedNotificationRuleRecipientsConfig recipientsConfig = new EscalatedNotificationRuleRecipientsConfig(); + recipientsConfig.setTriggerType(NotificationRuleTriggerType.ALARM); + recipientsConfig.setEscalationTable(Map.of( + 0, List.of(ownTarget.getUuidId()), + 60, List.of(otherTarget.getUuidId()) + )); + alarmRule.setRecipientsConfig(recipientsConfig); + doPost("/api/notification/rule", alarmRule).andExpect(status().isForbidden()); + + assertThat(findNotificationRules().getData()).extracting(NotificationRuleInfo::getName) + .doesNotContain(rule.getName(), alarmRule.getName()); + } + + @Test + public void testSaveNotificationRule_systemTemplate_isSaved() throws Exception { + loginSysAdmin(); + NotificationTemplate systemTemplate = createNotificationTemplate(NotificationType.ENTITY_ACTION, "Created", "Created", NotificationDeliveryMethod.WEB); + loginTenantAdmin(); + NotificationTarget target = createNotificationTarget(tenantAdminUserId); + + NotificationRule rule = saveNotificationRule(newDeviceCreatedRule(systemTemplate.getId(), List.of(target.getUuidId()))); + + try { + assertThat(rule.getId()).isNotNull(); + assertThat(rule.getTemplateId()).isEqualTo(systemTemplate.getId()); + } finally { + // the rule references a system template, which afterEach deletes before the tenant + notificationRuleService.deleteNotificationRuleById(tenantId, rule.getId()); + } + } + + @Test + public void testSaveNotificationRule_nonExistentTarget_returnsNotFound() throws Exception { + NotificationTemplate template = createNotificationTemplate(NotificationType.ENTITY_ACTION, "Created", "Created", NotificationDeliveryMethod.WEB); + + NotificationRule rule = newDeviceCreatedRule(template.getId(), List.of(UUID.randomUUID())); + doPost("/api/notification/rule", rule).andExpect(status().isNotFound()); + + assertThat(findNotificationRules().getData()).extracting(NotificationRuleInfo::getName).doesNotContain(rule.getName()); + } + + @Test + public void testRuleProcessing_deliversOnlyToTargetsOfRuleTenant() throws Exception { + loginDifferentTenant(); + NotificationTarget otherTarget = createNotificationTarget(savedDifferentTenantUser.getId()); + loginTenantAdmin(); + NotificationTemplate template = createNotificationTemplate(NotificationType.ENTITY_ACTION, "Device created", "Device created", NotificationDeliveryMethod.WEB); + NotificationTarget ownTarget = createNotificationTarget(tenantAdminUserId); + + NotificationRule rule = newDeviceCreatedRule(template.getId(), List.of(ownTarget.getUuidId(), otherTarget.getUuidId())); + rule.setTenantId(tenantId); + notificationRuleService.saveNotificationRule(tenantId, rule); + notificationRulesCache.evict(tenantId); + + createDevice("Device 1", "default", "111"); + await().atMost(TIMEOUT, TimeUnit.SECONDS) + .untilAsserted(() -> assertThat(getMyNotifications(false, 100)).extracting(Notification::getSubject).contains("Device created")); + + loginDifferentTenant(); + await().during(3, TimeUnit.SECONDS).atMost(5, TimeUnit.SECONDS) + .untilAsserted(() -> assertThat(getMyNotifications(false, 100)).extracting(Notification::getSubject).doesNotContain("Device created")); + } + + @Test + public void testRuleProcessing_templateOfOtherTenant_deliversNothing() throws Exception { + loginDifferentTenant(); + NotificationTemplate otherTemplate = createNotificationTemplate(NotificationType.ENTITY_ACTION, "Device created", "Device created", NotificationDeliveryMethod.WEB); + loginTenantAdmin(); + NotificationTarget target = createNotificationTarget(tenantAdminUserId); + + NotificationRule rule = newDeviceCreatedRule(otherTemplate.getId(), List.of(target.getUuidId())); + rule.setTenantId(tenantId); + notificationRuleService.saveNotificationRule(tenantId, rule); + notificationRulesCache.evict(tenantId); + + createDevice("Device 1", "default", "111"); + await().during(3, TimeUnit.SECONDS).atMost(5, TimeUnit.SECONDS) + .untilAsserted(() -> assertThat(getMyNotifications(false, 100)).extracting(Notification::getSubject).doesNotContain("Device created")); + } + + private NotificationRule newDeviceCreatedRule(NotificationTemplateId templateId, List targets) { + EntityActionNotificationRuleTriggerConfig triggerConfig = new EntityActionNotificationRuleTriggerConfig(); + triggerConfig.setEntityTypes(Set.of(EntityType.DEVICE)); + triggerConfig.setCreated(true); + + NotificationRule rule = new NotificationRule(); + rule.setName("Device created " + UUID.randomUUID()); + rule.setEnabled(true); + rule.setTemplateId(templateId); + rule.setTriggerType(NotificationRuleTriggerType.ENTITY_ACTION); + rule.setTriggerConfig(triggerConfig); + + DefaultNotificationRuleRecipientsConfig recipientsConfig = new DefaultNotificationRuleRecipientsConfig(); + recipientsConfig.setTriggerType(NotificationRuleTriggerType.ENTITY_ACTION); + recipientsConfig.setTargets(targets); + rule.setRecipientsConfig(recipientsConfig); + return rule; + } + private R checkNotificationAfter(Callable action, BiConsumer check) throws Exception { if (getWsClient().getLastDataUpdate() == null) { getWsClient().subscribeForUnreadNotifications(10).waitForReply(true);