Browse Source

Merge remote-tracking branch 'internal/hotfix-4.4' into internal-lts-4.4

pull/16844/head
Viacheslav Klimov 3 weeks ago
parent
commit
2a261b70ec
Failed to extract signature
  1. 14
      application/src/main/java/org/thingsboard/server/controller/NotificationRuleController.java
  2. 9
      application/src/main/java/org/thingsboard/server/service/notification/DefaultNotificationCenter.java
  3. 36
      application/src/test/java/org/thingsboard/server/service/notification/NotificationApiTest.java
  4. 131
      application/src/test/java/org/thingsboard/server/service/notification/NotificationRuleApiTest.java
  5. 5
      common/version-control/src/main/java/org/thingsboard/server/service/sync/DefaultGitSyncService.java
  6. 3
      common/version-control/src/main/java/org/thingsboard/server/service/sync/vc/DefaultGitRepositoryService.java
  7. 9
      common/version-control/src/main/java/org/thingsboard/server/service/sync/vc/GitRepository.java
  8. 65
      common/version-control/src/test/java/org/thingsboard/server/service/sync/vc/DefaultGitRepositoryServiceTest.java
  9. 36
      common/version-control/src/test/java/org/thingsboard/server/service/sync/vc/GitRepositoryTest.java

14
application/src/main/java/org/thingsboard/server/controller/NotificationRuleController.java

@ -20,17 +20,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.common.data.permission.Operation;
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 java.util.List;
import java.util.UUID;
import static org.thingsboard.server.common.data.permission.Resource.NOTIFICATION;
@ -52,6 +56,7 @@ import static org.thingsboard.server.controller.ControllerConstants.SYSTEM_OR_TE
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 +
@ -111,6 +116,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<UUID> targets : notificationRule.getRecipientsConfig().getTargetsTable().values()) {
for (UUID targetId : targets) {
checkNotificationTargetId(new NotificationTargetId(targetId), Operation.READ);
}
}
return doSaveAndLog(EntityType.NOTIFICATION_RULE, notificationRule, notificationRuleService::saveNotificationRule);
}

9
application/src/main/java/org/thingsboard/server/service/notification/DefaultNotificationCenter.java

@ -114,6 +114,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();
}
@ -126,7 +129,7 @@ public class DefaultNotificationCenter extends AbstractSubscriptionService imple
List<NotificationTarget> 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);
@ -516,6 +519,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<NotificationChannel> channels, NotificationCenter webNotificationChannel) {
this.channels = channels.stream().collect(Collectors.toMap(NotificationChannel::getDeliveryMethod, c -> c));

36
application/src/test/java/org/thingsboard/server/service/notification/NotificationApiTest.java

@ -1123,6 +1123,42 @@ public class NotificationApiTest extends AbstractNotificationApiTest {
assertThat(getAvailableDeliveryMethods()).doesNotContain(NotificationDeliveryMethod.MOBILE_APP);
}
@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<NotificationRequestStats> future = SettableFuture.create();
notificationCenter.processNotificationRequest(notificationRequest.getTenantId(), notificationRequest, new FutureCallback<>() {

131
application/src/test/java/org/thingsboard/server/service/notification/NotificationRuleApiTest.java

@ -45,6 +45,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;
@ -914,6 +915,136 @@ 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.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<UUID> 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 = DefaultNotificationRuleRecipientsConfig.forTriggerType(NotificationRuleTriggerType.ENTITY_ACTION);
recipientsConfig.setTargets(targets);
rule.setRecipientsConfig(recipientsConfig);
return rule;
}
private <R> R checkNotificationAfter(Callable<R> action, BiConsumer<Notification, R> check) throws Exception {
if (getWsClient().getLastDataUpdate() == null) {
getWsClient().subscribeForUnreadNotifications(10).waitForReply(true);

5
common/version-control/src/main/java/org/thingsboard/server/service/sync/DefaultGitSyncService.java

@ -1,5 +1,6 @@
// SPDX-FileCopyrightText: Copyright The ThingsBoard Authors
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: Modifications Copyright ThingsBoard, Inc.
// SPDX-License-Identifier: Apache-2.0 AND BUSL-1.1
package org.thingsboard.server.service.sync;
import jakarta.annotation.PreDestroy;
@ -150,7 +151,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) {

3
common/version-control/src/main/java/org/thingsboard/server/service/sync/vc/DefaultGitRepositoryService.java

@ -358,7 +358,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);

9
common/version-control/src/main/java/org/thingsboard/server/service/sync/vc/GitRepository.java

@ -476,6 +476,15 @@ public class GitRepository {
return git.getRepository().resolve(rev);
}
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();

65
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;
}
}

36
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);
}
}
Loading…
Cancel
Save