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 ba6c21d7af..be37a6b2e6 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 b59c496ceb..cd8f55952b 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 @@ -44,6 +44,7 @@ import org.thingsboard.server.common.data.device.data.DeviceData; 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; @@ -910,6 +911,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); diff --git a/common/version-control/src/main/java/org/thingsboard/server/service/sync/DefaultGitSyncService.java b/common/version-control/src/main/java/org/thingsboard/server/service/sync/DefaultGitSyncService.java index b4d678fec0..731fb33d22 100644 --- a/common/version-control/src/main/java/org/thingsboard/server/service/sync/DefaultGitSyncService.java +++ b/common/version-control/src/main/java/org/thingsboard/server/service/sync/DefaultGitSyncService.java @@ -150,7 +150,7 @@ public class DefaultGitSyncService implements GitSyncService { private Path getRepoDirectory(RepositorySettings settings) { // using uri to define folder name in case repo url is changed String name = URI.create(settings.getRepositoryUri()).getPath().replaceAll("[^a-zA-Z]", ""); - return Path.of(repositoriesFolder, name); + return GitRepository.resolveDirectory(repositoriesFolder, name); } private RevCommit getLastCommit(String key) { diff --git a/common/version-control/src/main/java/org/thingsboard/server/service/sync/vc/DefaultGitRepositoryService.java b/common/version-control/src/main/java/org/thingsboard/server/service/sync/vc/DefaultGitRepositoryService.java index ffe64750a7..1b686543c2 100644 --- a/common/version-control/src/main/java/org/thingsboard/server/service/sync/vc/DefaultGitRepositoryService.java +++ b/common/version-control/src/main/java/org/thingsboard/server/service/sync/vc/DefaultGitRepositoryService.java @@ -268,7 +268,8 @@ public class DefaultGitRepositoryService implements GitRepositoryService { private GitRepository openOrCloneRepository(TenantId tenantId, RepositorySettings settings, boolean fetch) throws Exception { log.debug("[{}] Init tenant repository started.", tenantId); - Path repositoryDirectory = Path.of(repositoriesFolder, settings.isLocalOnly() ? "local_" + settings.getRepositoryUri() : tenantId.getId().toString()); + String directoryName = settings.isLocalOnly() ? "local_" + settings.getRepositoryUri() : tenantId.getId().toString(); + Path repositoryDirectory = GitRepository.resolveDirectory(repositoriesFolder, directoryName); GitRepository repository = GitRepository.openOrClone(repositoryDirectory, settings, fetch); repositories.put(tenantId, repository); log.debug("[{}] Init tenant repository completed.", tenantId); diff --git a/common/version-control/src/main/java/org/thingsboard/server/service/sync/vc/GitRepository.java b/common/version-control/src/main/java/org/thingsboard/server/service/sync/vc/GitRepository.java index 1cadf7669d..83a2dda635 100644 --- a/common/version-control/src/main/java/org/thingsboard/server/service/sync/vc/GitRepository.java +++ b/common/version-control/src/main/java/org/thingsboard/server/service/sync/vc/GitRepository.java @@ -462,6 +462,15 @@ public class GitRepository { return result; } + public static Path resolveDirectory(String repositoriesFolder, String directoryName) { + Path root = Path.of(repositoriesFolder).toAbsolutePath().normalize(); + Path directory = root.resolve(directoryName).normalize(); + if (!root.equals(directory.getParent()) || !directoryName.equals(directory.getFileName().toString())) { + throw new IllegalArgumentException("Repository directory name must be a single path segment"); + } + return directory; + } + @SneakyThrows public static boolean exists(String directory) { File gitDirectory = Path.of(directory, ".git").toFile(); diff --git a/common/version-control/src/test/java/org/thingsboard/server/service/sync/vc/DefaultGitRepositoryServiceTest.java b/common/version-control/src/test/java/org/thingsboard/server/service/sync/vc/DefaultGitRepositoryServiceTest.java new file mode 100644 index 0000000000..0ccc76b406 --- /dev/null +++ b/common/version-control/src/test/java/org/thingsboard/server/service/sync/vc/DefaultGitRepositoryServiceTest.java @@ -0,0 +1,65 @@ +// SPDX-FileCopyrightText: Copyright The Thingsboard Authors +// SPDX-License-Identifier: Apache-2.0 +package org.thingsboard.server.service.sync.vc; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import org.springframework.test.util.ReflectionTestUtils; +import org.thingsboard.server.common.data.id.TenantId; +import org.thingsboard.server.common.data.sync.vc.RepositorySettings; + +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.UUID; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +public class DefaultGitRepositoryServiceTest { + + @TempDir + Path tempDir; + + private DefaultGitRepositoryService service; + private final TenantId tenantId = TenantId.fromUUID(UUID.randomUUID()); + + @BeforeEach + public void setUp() { + service = new DefaultGitRepositoryService(); + ReflectionTestUtils.setField(service, "repositoriesFolder", tempDir.toString()); + } + + @Test + public void localRepositoryIsCreatedDirectlyUnderRepositoriesFolder() throws Exception { + RepositorySettings settings = localSettings("repo1"); + + service.initRepository(tenantId, settings, false); + + assertThat(tempDir.resolve("local_repo1").resolve(".git")).isDirectory(); + assertThat(service.getRepositorySettings(tenantId)).isEqualTo(settings); + } + + @Test + public void localRepositoryNameWithMultipleSegmentsIsRejected() throws Exception { + Path marker = tempDir.resolve("keep").resolve("marker.txt"); + Files.createDirectories(marker.getParent()); + Files.writeString(marker, "content"); + + assertThatThrownBy(() -> service.initRepository(tenantId, localSettings("repo1/main"), false)) + .isInstanceOf(IllegalArgumentException.class); + + assertThat(tempDir.resolve("local_repo1")).doesNotExist(); + assertThat(marker).exists(); + assertThat(service.getRepositorySettings(tenantId)).isNull(); + } + + private RepositorySettings localSettings(String repositoryUri) { + RepositorySettings settings = new RepositorySettings(); + settings.setRepositoryUri(repositoryUri); + settings.setDefaultBranch("main"); + settings.setLocalOnly(true); + return settings; + } + +} diff --git a/common/version-control/src/test/java/org/thingsboard/server/service/sync/vc/GitRepositoryTest.java b/common/version-control/src/test/java/org/thingsboard/server/service/sync/vc/GitRepositoryTest.java new file mode 100644 index 0000000000..3457818d21 --- /dev/null +++ b/common/version-control/src/test/java/org/thingsboard/server/service/sync/vc/GitRepositoryTest.java @@ -0,0 +1,36 @@ +// SPDX-FileCopyrightText: Copyright The Thingsboard Authors +// SPDX-License-Identifier: Apache-2.0 +package org.thingsboard.server.service.sync.vc; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; + +import java.nio.file.Path; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +public class GitRepositoryTest { + + @TempDir + Path tempDir; + + @Test + public void directoryIsResolvedDirectlyUnderRepositoriesFolder() { + assertThat(GitRepository.resolveDirectory(tempDir.toString(), "repo1")) + .isEqualTo(tempDir.toAbsolutePath().normalize().resolve("repo1")); + } + + @Test + public void emptyDirectoryNameIsRejected() { + assertThatThrownBy(() -> GitRepository.resolveDirectory(tempDir.toString(), "")) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + public void directoryNameThatIsNotNormalizedIsRejected() { + assertThatThrownBy(() -> GitRepository.resolveDirectory(tempDir.toString(), "./repo1")) + .isInstanceOf(IllegalArgumentException.class); + } + +}