Skip to content

armgit / core

Public Imported from GitHub
0

100% open-source IoT Platform - Integrate your devices, add intelligence, build custom apps

Super admin can't open or delete alarms in other realms (#1838)

Dennis Kuijs1ce1ebb07450
diff --git a/manager/src/main/java/org/openremote/manager/alarm/AlarmResourceImpl.java b/manager/src/main/java/org/openremote/manager/alarm/AlarmResourceImpl.java
index b923b03fa..1d6dc26ba 100644
--- a/manager/src/main/java/org/openremote/manager/alarm/AlarmResourceImpl.java
+++ b/manager/src/main/java/org/openremote/manager/alarm/AlarmResourceImpl.java
@@ -23,6 +23,8 @@ import jakarta.persistence.EntityNotFoundException;
import jakarta.ws.rs.BadRequestException;
import jakarta.ws.rs.ForbiddenException;
import jakarta.ws.rs.NotFoundException;
+import jakarta.ws.rs.WebApplicationException;
+import jakarta.ws.rs.core.Response;
import org.openremote.container.timer.TimerService;
import org.openremote.manager.security.ManagerIdentityService;
import org.openremote.manager.web.ManagerWebResource;
@@ -35,7 +37,9 @@ import org.openremote.model.http.RequestParams;
import org.openremote.model.util.TextUtil;
import java.util.List;
+import java.util.Set;
import java.util.function.Supplier;
+import java.util.stream.Collectors;
import static org.openremote.model.alarm.Alarm.Source.CLIENT;
import static org.openremote.model.alarm.Alarm.Source.MANUAL;
@@ -51,79 +55,140 @@ public class AlarmResourceImpl extends ManagerWebResource implements AlarmResour
this.alarmService = alarmService;
}
- private <T> T mapExceptions(Supplier<T> supplier) {
+ @Override
+ public SentAlarm[] getAlarms(RequestParams requestParams, String realm, Alarm.Status status, String assetId, String assigneeId) {
try {
- return supplier.get();
+ String filterRealm = TextUtil.isNullOrEmpty(realm) ? getAuthenticatedRealmName() : realm;
+ if (!isRealmActiveAndAccessible(filterRealm)) {
+ throw new ForbiddenException("Realm '" + filterRealm + "' is nonexistent, inactive or inaccessible");
+ }
+ return alarmService.getAlarms(filterRealm, status, assetId, assigneeId).toArray(new SentAlarm[0]);
} catch (IllegalArgumentException | NullPointerException e) {
- throw new BadRequestException(e.getMessage(), e);
- } catch (EntityNotFoundException e) {
- throw new NotFoundException(e.getMessage(), e);
- } catch (SecurityException e) {
- throw new ForbiddenException(e.getMessage(), e);
+ throw new WebApplicationException(Response.Status.BAD_REQUEST);
+ } catch (ForbiddenException e) {
+ throw new WebApplicationException(Response.Status.FORBIDDEN);
}
}
- private void mapExceptions(Runnable runnable) {
+ @Override
+ public void removeAlarms(RequestParams requestParams, List<Long> alarmIds) {
try {
- runnable.run();
- } catch (IllegalArgumentException | NullPointerException e) {
- throw new BadRequestException(e.getMessage(), e);
+ if (!isRealmActiveAndAccessible(getAuthenticatedRealmName())) {
+ throw new ForbiddenException("Realm '" + getAuthenticatedRealmName() + "' is nonexistent, inactive or inaccessible");
+ }
+ List<SentAlarm> alarms = alarmService.getAlarms(alarmIds);;
+ alarmService.removeAlarms(alarms, alarmIds);
} catch (EntityNotFoundException e) {
- throw new NotFoundException(e.getMessage(), e);
- } catch (SecurityException e) {
- throw new ForbiddenException(e.getMessage(), e);
- }
- }
-
- @Override
- public SentAlarm[] getAlarms(RequestParams requestParams, String realm, Alarm.Status status, String assetId, String assigneeId) {
- String filterRealm = TextUtil.isNullOrEmpty(realm) ? getAuthenticatedRealm().getName() : realm;
- if (!isRealmActiveAndAccessible(filterRealm)) {
- throw new ForbiddenException("Realm '" + filterRealm + "' is not active or inaccessible");
+ throw new WebApplicationException(Response.Status.NOT_FOUND);
+ } catch (ForbiddenException e) {
+ throw new WebApplicationException(Response.Status.FORBIDDEN);
+ } catch (IllegalArgumentException e) {
+ throw new WebApplicationException(Response.Status.BAD_REQUEST);
}
- return mapExceptions(() -> alarmService.getAlarms(filterRealm, status, assetId, assigneeId).toArray(new SentAlarm[0]));
- }
-
- @Override
- public void removeAlarms(RequestParams requestParams, List<Long> alarmIds) {
- mapExceptions(() -> alarmService.removeAlarms(alarmIds, getUserId()));
}
@Override
public SentAlarm getAlarm(RequestParams requestParams, Long alarmId) {
- return mapExceptions(() -> alarmService.getAlarm(alarmId, getUserId()));
+ try {
+ SentAlarm alarm = alarmService.getAlarm(alarmId);
+ if (!isRealmActiveAndAccessible(alarm.getRealm())) {
+ throw new ForbiddenException("Realm '" + alarm.getRealm() + "' is nonexistent, inactive or inaccessible");
+ }
+ return alarmService.getAlarm(alarmId);
+ } catch (EntityNotFoundException e) {
+ throw new WebApplicationException(Response.Status.NOT_FOUND);
+ } catch (ForbiddenException e) {
+ throw new WebApplicationException(Response.Status.FORBIDDEN);
+ }
}
@Override
public void removeAlarm(RequestParams requestParams, Long alarmId) {
- mapExceptions(() -> alarmService.removeAlarm(alarmId, getUserId()));
+ try {
+ SentAlarm alarm = alarmService.getAlarm(alarmId);
+ if (!isRealmActiveAndAccessible(alarm.getRealm())) {
+ throw new ForbiddenException("Realm '" + alarm.getRealm() + "' is nonexistent, inactive or inaccessible");
+ }
+ alarmService.removeAlarm(alarm);
+ } catch (EntityNotFoundException e) {
+ throw new WebApplicationException(Response.Status.NOT_FOUND);
+ } catch (ForbiddenException e) {
+ throw new WebApplicationException(Response.Status.FORBIDDEN);
+ } catch (IllegalArgumentException e) {
+ throw new WebApplicationException(Response.Status.BAD_REQUEST);
+ }
}
@Override
public SentAlarm createAlarm(RequestParams requestParams, Alarm alarm, List<String> assetIds) {
- if (getUserId() != null) {
- alarm.setSource(MANUAL);
- alarm.setSourceId(getUserId());
- } else if (getClientId() != null) {
- alarm.setSource(CLIENT);
- alarm.setSourceId(getClientId());
+ try {
+ if (getUserId() != null) {
+ alarm.setSource(MANUAL);
+ alarm.setSourceId(getUserId());
+ } else if (getClientId() != null) {
+ alarm.setSource(CLIENT);
+ alarm.setSourceId(getClientId());
+ }
+
+ if (!isRealmActiveAndAccessible(alarm.getRealm())) {
+ throw new ForbiddenException("Realm '" + alarm.getRealm() + "' is nonexistent, inactive or inaccessible");
+ }
+ return alarmService.sendAlarm(alarm, assetIds);
+ } catch (NullPointerException e) {
+ throw new WebApplicationException(Response.Status.BAD_REQUEST);
+ } catch (ForbiddenException e) {
+ throw new WebApplicationException(Response.Status.FORBIDDEN);
}
- return mapExceptions(() -> alarmService.sendAlarm(alarm, assetIds, getUserId()));
}
@Override
- public void updateAlarm(RequestParams requestParams, Long alarmId, SentAlarm alarm) {
- mapExceptions(() -> alarmService.updateAlarm(alarmId, getUserId(), alarm));
+ public void updateAlarm(RequestParams requestParams, Long alarmId, SentAlarm newAlarm) {
+ try {
+ SentAlarm oldAlarm = alarmService.getAlarm(alarmId);
+ if (!isRealmActiveAndAccessible(oldAlarm.getRealm())) {
+ throw new ForbiddenException("Realm '" + oldAlarm.getRealm() + "' is nonexistent, inactive or inaccessible");
+ }
+ alarmService.updateAlarm(oldAlarm, newAlarm);
+ } catch (EntityNotFoundException e) {
+ throw new WebApplicationException(Response.Status.NOT_FOUND);
+ } catch (ForbiddenException e) {
+ throw new WebApplicationException(Response.Status.FORBIDDEN);
+ }
}
@Override
public List<AlarmAssetLink> getAssetLinks(RequestParams requestParams, Long alarmId, String realm) {
- return mapExceptions(() -> alarmService.getAssetLinks(alarmId, getUserId(), realm));
+ try {
+ if (!isRealmActiveAndAccessible(realm)) {
+ throw new ForbiddenException("Realm '" + realm + "' is nonexistent, inactive or inaccessible");
+ }
+ return alarmService.getAssetLinks(alarmId, realm);
+ } catch (EntityNotFoundException e) {
+ throw new WebApplicationException(Response.Status.NOT_FOUND);
+ } catch (ForbiddenException e) {
+ throw new WebApplicationException(Response.Status.FORBIDDEN);
+ }
}
@Override
public void setAssetLinks(RequestParams requestParams, List<AlarmAssetLink> links) {
- mapExceptions(() -> alarmService.linkAssets(links, getUserId()));
+ try {
+ if (links == null || links.isEmpty()) {
+ throw new IllegalArgumentException("No AlarmAssetLink objects were provided.");
+ }
+ Set<String> realms = links.stream().map(link -> link.getId().getRealm()).collect(Collectors.toSet());
+
+ if (!isRealmActiveAndAccessible(realms.stream().findFirst().orElse(null))) {
+ throw new ForbiddenException("Realm '" + realms.stream().findFirst() + "' is nonexistent, inactive or inaccessible");
+ }
+ alarmService.linkAssets(links);
+ } catch (EntityNotFoundException e) {
+ throw new WebApplicationException(Response.Status.NOT_FOUND);
+ } catch (ForbiddenException e) {
+ throw new WebApplicationException(Response.Status.FORBIDDEN);
+ } catch (NullPointerException | IllegalArgumentException e) {
+ throw new WebApplicationException(Response.Status.BAD_REQUEST);
+ }
}
}
diff --git a/manager/src/main/java/org/openremote/manager/alarm/AlarmService.java b/manager/src/main/java/org/openremote/manager/alarm/AlarmService.java
index f147a9322..94bd65cbc 100644
--- a/manager/src/main/java/org/openremote/manager/alarm/AlarmService.java
+++ b/manager/src/main/java/org/openremote/manager/alarm/AlarmService.java
@@ -151,26 +151,6 @@ public class AlarmService extends RouteBuilder implements ContainerService {
alarmIds.forEach(this::validateAlarmId);
}
- /**
- * Validates if the {@code alarm} is non-null and the user can access to the alarm realm.
- */
- protected void validateAlarmExistsAndAccessible(SentAlarm alarm, String userId) {
- if (alarm == null) {
- throw new EntityNotFoundException("Alarm does not exist");
- }
- validateRealmAccessibleToUser(userId, alarm.getRealm());
- }
-
- /**
- * Validates if the {@code alarms} are non-null, match the alarmIds length and the user has access to all alarm realms.
- */
- protected void validateAlarmsExistAndAccessible(List<Long> alarmIds, List<SentAlarm> alarms, String userId) {
- if (alarms == null || alarmIds.size() != alarms.size()) {
- throw new EntityNotFoundException("One or more alarms do not exist");
- }
- validateRealmsAccessibleToUser(userId, getAlarmRealms(alarms));
- }
-
/**
* Throws an {@link IllegalArgumentException} if the given {@code assetIds} are null or empty.
*/
@@ -185,36 +165,10 @@ public class AlarmService extends RouteBuilder implements ContainerService {
});
}
- /**
- * Validates if the user has access to the given realm.
- */
- protected void validateRealmAccessibleToUser(String userId, String realm) {
- validateRealmsAccessibleToUser(userId, Set.of(realm));
- }
-
- /**
- * Validates if the user has access to all given realms.
- */
- protected void validateRealmsAccessibleToUser(String userId, Set<String> realms) {
- if (userId == null) {
- return;
- }
- ManagerIdentityProvider identityProvider = identityService.getIdentityProvider();
- User user = identityProvider.getUser(userId);
- if (user == null) {
- throw new IllegalStateException("User does not exist");
- }
-
- if (!identityProvider.isMasterRealmAdmin(userId) &&
- (realms.size() > 1 || !identityProvider.isUserInRealm(userId, realms.stream().findFirst().orElse(null)))) {
- throw new SecurityException("Realm is not active or inaccessible");
- }
- }
-
/**
* Sends an alarm if the given user has access to the alarm realm.
*/
- public SentAlarm sendAlarm(Alarm alarm, List<String> assetIds, String userId) {
+ public SentAlarm sendAlarm(Alarm alarm, List<String> assetIds) {
Objects.requireNonNull(alarm, "Alarm cannot be null");
Objects.requireNonNull(alarm.getRealm(), "Alarm realm cannot be null");
Objects.requireNonNull(alarm.getTitle(), "Alarm title cannot be null");
@@ -222,8 +176,6 @@ public class AlarmService extends RouteBuilder implements ContainerService {
Objects.requireNonNull(alarm.getSource(), "Source cannot be null");
Objects.requireNonNull(alarm.getSourceId(), "Source ID cannot be null");
- validateRealmAccessibleToUser(userId, alarm.getRealm());
-
Date timestamp = new Date(timerService.getCurrentTimeMillis());
SentAlarm sentAlarm = persistenceService.doReturningTransaction(entityManager -> entityManager.merge(new SentAlarm()
.setAssigneeId(alarm.getAssigneeId())
@@ -324,7 +276,7 @@ public class AlarmService extends RouteBuilder implements ContainerService {
result.put("Severity", alarm.getSeverity().name());
result.put("Status", alarm.getStatus().name());
- List<String> assetLinks = getAssetLinks(alarm.getId(), null, alarm.getRealm()).stream().map(AlarmAssetLink::getAssetName).toList();
+ List<String> assetLinks = getAssetLinks(alarm.getId(), alarm.getRealm()).stream().map(AlarmAssetLink::getAssetName).toList();
result.put("Linked assets", assetLinks.isEmpty() ? "None" : String.join(", ", assetLinks));
result.put("Assignee", TextUtil.isNullOrEmpty(alarm.getAssigneeUsername()) ? "None" : alarm.getAssigneeUsername());
@@ -352,69 +304,48 @@ public class AlarmService extends RouteBuilder implements ContainerService {
/**
* Updates an existing alarm if the given user has access to the alarm realm.
*/
- public void updateAlarm(Long alarmId, String userId, SentAlarm alarm) {
- SentAlarm oldAlarm = getAlarm(alarmId, userId);
+ public void updateAlarm(SentAlarm oldAlarm, SentAlarm newAlarm) {
String oldAssigneeId = oldAlarm.getAssigneeId();
- String newAssigneeId = alarm.getAssigneeId();
-
- if (newAssigneeId != null) {
- validateRealmAccessibleToUser(newAssigneeId, alarm.getRealm());
- }
+ String newAssigneeId = newAlarm.getAssigneeId();
persistenceService.doTransaction(entityManager -> entityManager.createQuery("""
update SentAlarm set title=:title, content=:content, severity=:severity, status=:status, lastModified=:lastModified, assigneeId=:assigneeId
where id =:id
""")
- .setParameter("id", alarmId)
- .setParameter("title", alarm.getTitle())
- .setParameter("content", alarm.getContent())
- .setParameter("severity", alarm.getSeverity())
- .setParameter("status", alarm.getStatus())
+ .setParameter("id", oldAlarm.getId())
+ .setParameter("title", newAlarm.getTitle())
+ .setParameter("content", newAlarm.getContent())
+ .setParameter("severity", newAlarm.getSeverity())
+ .setParameter("status", newAlarm.getStatus())
.setParameter("lastModified", new Timestamp(timerService.getCurrentTimeMillis()))
.setParameter("assigneeId", newAssigneeId)
.executeUpdate());
- clientEventService.publishEvent(new AlarmEvent(alarm.getRealm(), PersistenceEvent.Cause.UPDATE));
+ clientEventService.publishEvent(new AlarmEvent(newAlarm.getRealm(), PersistenceEvent.Cause.UPDATE));
- if (alarm.getSeverity() == Alarm.Severity.HIGH) {
- Set<String> excludeUserIds = Stream.of(userId, oldAssigneeId).filter(Objects::nonNull).collect(Collectors.toSet());
- sendAssigneeNotification(getAlarm(alarmId, userId), excludeUserIds);
+ if (newAlarm.getSeverity() == Alarm.Severity.HIGH) {
+ Set<String> excludeUserIds = Stream.of(oldAssigneeId).filter(Objects::nonNull).collect(Collectors.toSet());
+ sendAssigneeNotification(getAlarm(oldAlarm.getId()), excludeUserIds);
}
}
- /**
- * Links one asset to an existing alarm.
- */
- public void linkAsset(String assetId, String realm, Long alarmId) {
- linkAssets(List.of(assetId), realm, alarmId);
- }
-
/**
* Links multiple assets to an existing alarm.
*/
public void linkAssets(List<String> assetIds, String realm, Long alarmId) {
- linkAssets(assetIds.stream().map(assetId -> new AlarmAssetLink(realm, alarmId, assetId)).toList(), null);
+ linkAssets(assetIds.stream().map(assetId -> new AlarmAssetLink(realm, alarmId, assetId)).toList());
}
/**
* Links multiple assets to existing alarms if the given user has access to the alarm realms.
*/
- public void linkAssets(List<AlarmAssetLink> links, String userId) {
- if (links == null || links.isEmpty()) {
- throw new IllegalArgumentException("Missing links");
- }
-
+ public void linkAssets(List<AlarmAssetLink> links) {
Set<Long> alarmIds = links.stream().map(link -> link.getId().getAlarmId()).collect(Collectors.toSet());
validateAlarmIds(alarmIds);
Set<String> assetIds = links.stream().map(link -> link.getId().getAssetId()).collect(Collectors.toSet());
validateAssetIds(assetIds);
- if (userId != null) {
- Set<String> realms = links.stream().map(link -> link.getId().getRealm()).collect(Collectors.toSet());
- validateRealmsAccessibleToUser(userId, realms);
- }
-
persistenceService.doTransaction(entityManager -> entityManager.unwrap(Session.class).doWork(connection -> {
PreparedStatement st = connection.prepareStatement("""
insert into ALARM_ASSET_LINK (sentalarm_id, realm, asset_id, created_on) values (?, ?, ?, ?)
@@ -434,8 +365,7 @@ public class AlarmService extends RouteBuilder implements ContainerService {
/**
* Returns the assets linked to an alarm if the given user has access to the alarm realm.
*/
- public List<AlarmAssetLink> getAssetLinks(Long alarmId, String userId, String realm) throws IllegalArgumentException {
- getAlarm(alarmId, userId);
+ public List<AlarmAssetLink> getAssetLinks(Long alarmId, String realm) throws IllegalArgumentException {
return persistenceService.doReturningTransaction(entityManager ->
entityManager.createQuery("""
select aal from AlarmAssetLink aal
@@ -451,7 +381,7 @@ public class AlarmService extends RouteBuilder implements ContainerService {
/**
* Retrieves the details of an existing alarm if the given user has access to the alarm realm.
*/
- public SentAlarm getAlarm(Long alarmId, String userId) throws IllegalArgumentException {
+ public SentAlarm getAlarm(Long alarmId) throws IllegalArgumentException {
validateAlarmId(alarmId);
SentAlarm alarm;
try {
@@ -461,14 +391,18 @@ public class AlarmService extends RouteBuilder implements ContainerService {
} catch (PersistenceException e) {
alarm = null;
}
- validateAlarmExistsAndAccessible(alarm, userId);
+
+ if (alarm == null) {
+ throw new EntityNotFoundException("Alarm does not exist");
+ }
+
return alarm;
}
/**
* Retrieves the details of existing alarms if the given user has access to the alarm realms.
*/
- public List<SentAlarm> getAlarms(List<Long> alarmIds, String userId) throws IllegalArgumentException {
+ public List<SentAlarm> getAlarms(List<Long> alarmIds) throws IllegalArgumentException {
validateAlarmIds(alarmIds);
List<SentAlarm> alarms;
try {
@@ -480,7 +414,11 @@ public class AlarmService extends RouteBuilder implements ContainerService {
} catch (PersistenceException e) {
alarms = null;
}
- validateAlarmsExistAndAccessible(alarmIds, alarms, userId);
+
+ if (alarms == null || alarmIds.size() != alarms.size()) {
+ throw new EntityNotFoundException("One or more alarms do not exist");
+ }
+
return alarms;
}
@@ -520,11 +458,10 @@ public class AlarmService extends RouteBuilder implements ContainerService {
/**
* Removes an existing alarm if the given user has access to the alarm realm.
*/
- public void removeAlarm(Long alarmId, String userId) {
- SentAlarm alarm = getAlarm(alarmId, userId);
+ public void removeAlarm(SentAlarm alarm) {
persistenceService.doTransaction(entityManager -> entityManager
.createQuery("delete SentAlarm where id = :id")
- .setParameter("id", alarmId)
+ .setParameter("id", alarm.getId())
.executeUpdate()
);
clientEventService.publishEvent(new AlarmEvent(alarm.getRealm(), PersistenceEvent.Cause.DELETE));
@@ -533,8 +470,7 @@ public class AlarmService extends RouteBuilder implements ContainerService {
/**
* Removes existing alarms if the given user has access to the alarm realms.
*/
- public void removeAlarms(List<Long> alarmIds, String userId) throws IllegalArgumentException {
- List<SentAlarm> alarms = getAlarms(alarmIds, userId);
+ public void removeAlarms(List<SentAlarm> alarms, List<Long> alarmIds) throws IllegalArgumentException {
persistenceService.doTransaction(entityManager ->
entityManager.createQuery("delete from SentAlarm sa where sa.id in :ids")
.setParameter("ids", alarmIds)
diff --git a/manager/src/main/java/org/openremote/manager/rules/facade/AlarmFacade.java b/manager/src/main/java/org/openremote/manager/rules/facade/AlarmFacade.java
index 6e544f5dc..42aaafae8 100644
--- a/manager/src/main/java/org/openremote/manager/rules/facade/AlarmFacade.java
+++ b/manager/src/main/java/org/openremote/manager/rules/facade/AlarmFacade.java
@@ -53,7 +53,7 @@ public class AlarmFacade<T extends Ruleset> extends Alarms {
alarm.setRealm(rulesEngineId.getRealm().orElseThrow());
alarm.setSource(source);
- return alarmService.sendAlarm(alarm, assetIds, null).getId();
+ return alarmService.sendAlarm(alarm, assetIds).getId();
}
public void linkAssets(List<String> assetIds, Long alarmId) {
diff --git a/test/src/test/groovy/org/openremote/test/alarm/AlarmResourceTest.groovy b/test/src/test/groovy/org/openremote/test/alarm/AlarmResourceTest.groovy
index adf101e5d..01be13fcd 100644
--- a/test/src/test/groovy/org/openremote/test/alarm/AlarmResourceTest.groovy
+++ b/test/src/test/groovy/org/openremote/test/alarm/AlarmResourceTest.groovy
@@ -31,6 +31,7 @@ import org.openremote.manager.setup.SetupService
import org.openremote.model.notification.AbstractNotificationMessage
import org.openremote.model.notification.Notification
import org.openremote.model.notification.NotificationSendResult
+import org.openremote.model.security.ClientRole
import org.openremote.model.security.User
import org.openremote.setup.integration.KeycloakTestSetup
import org.openremote.setup.integration.ManagerTestSetup
@@ -48,10 +49,15 @@ import static org.openremote.model.Constants.MASTER_REALM
import static org.openremote.model.Constants.MASTER_REALM_ADMIN_USER
import jakarta.ws.rs.WebApplicationException
+import static org.openremote.model.Constants.SUPER_USER_REALM_ROLE
+
class AlarmResourceTest extends Specification implements ManagerContainerTrait {
@Shared
static AlarmResource adminResource
+ @Shared
+ static AlarmResource superAdminResource
+
@Shared
static AlarmResource regularUserResource
@@ -64,6 +70,9 @@ class AlarmResourceTest extends Specification implements ManagerContainerTrait {
@Shared
static String alarmsReadWriteUserId
+ @Shared
+ static String testuser4Id
+
@Shared
static NotificationService notificationService
@@ -88,7 +97,22 @@ class AlarmResourceTest extends Specification implements ManagerContainerTrait {
adminResource = getClientApiTarget(serverUri(serverPort), MASTER_REALM, adminAccessToken).proxy(AlarmResource.class)
User alarmsReadWriteUser = keycloakTestSetup.createUser(MASTER_REALM, "alarmsrwuser1", "alarmsrwuser1", "Alarms R/W", "User", "[email protected]", true, KeycloakTestSetup.REGULAR_USER_ROLES)
- alarmsReadWriteUserId = alarmsReadWriteUser.getId()
+ alarmsReadWriteUserId = alarmsReadWriteUser.getId();
+
+ User superUser = keycloakTestSetup.createUser(MASTER_REALM, "testuser4", "testuser4", "Demo4", "Demo4", null, true, new ClientRole[] {ClientRole.WRITE, ClientRole.READ});
+ testuser4Id = superUser.getId();
+ keycloakTestSetup.keycloakProvider.updateUserClientRoles(MASTER_REALM, testuser4Id, "account");
+ keycloakTestSetup.keycloakProvider.updateUserRealmRoles(MASTER_REALM, testuser4Id, keycloakTestSetup.keycloakProvider.addUserRealmRoles(MASTER_REALM, testuser4Id, SUPER_USER_REALM_ROLE));
+
+ def superAdminAccessToken = authenticate(
+ container,
+ MASTER_REALM,
+ KEYCLOAK_CLIENT_ID,
+ "testuser4",
+ "testuser4",
+ ).token
+
+ superAdminResource = getClientApiTarget(serverUri(serverPort), MASTER_REALM, superAdminAccessToken).proxy(AlarmResource.class)
def emailNotificationHandler = container.getService(EmailNotificationHandler.class)
def throwPushHandlerException = false
@@ -120,6 +144,40 @@ class AlarmResourceTest extends Specification implements ManagerContainerTrait {
notificationMessages.clear()
}
+ // Create alarm as new super user in other realm
+ @Unroll
+ def "should create an alarm with title '#title', content '#content', severity '#severity', assigneeId '#assigneeId' and '#emailNotifications' emailNotifications as new super user in other realm"() {
+ when: "an alarm is created"
+ def input = new Alarm(title, content, severity, assigneeId, keycloakTestSetup.realmBuilding.name)
+ def alarm = superAdminResource.createAlarm(null, input, null)
+
+ then:
+ alarm != null
+ alarm.title == title
+ alarm.content == content
+ alarm.severity == severity
+ alarm.assigneeId == assigneeId
+ alarm.status == Alarm.Status.OPEN
+
+ and:
+ def conditions = new PollingConditions(timeout: 10, initialDelay: 1, delay: 0.2)
+ conditions.eventually {
+ assert notificationMessages.size() == emailNotifications
+ }
+
+ where:
+ title | content | severity | assigneeId | emailNotifications
+ "Low Alarm" | "Test Description" | Severity.LOW | null | 0
+ "Low Assigned 1 Alarm" | "Test Description" | Severity.LOW | keycloakTestSetup.testuser1Id | 0
+ "Low Assigned 2 Alarm" | "Test Description" | Severity.LOW | alarmsReadWriteUserId | 0
+ "Medium Unassigned Alarm" | "Another Description" | Severity.MEDIUM | null | 0
+ "Medium Assigned 1 Alarm" | "Assigned Description" | Severity.MEDIUM | keycloakTestSetup.testuser1Id | 0
+ "Medium Assigned 2 Alarm" | "Assigned Description" | Severity.MEDIUM | alarmsReadWriteUserId | 0
+ "High Unassigned Alarm" | "Critical Description" | Severity.HIGH | null | 1
+ "High Assigned 1 Alarm" | "Critical Description" | Severity.HIGH | keycloakTestSetup.testuser1Id | 0
+ "High Assigned 2 Alarm" | "Critical Description" | Severity.HIGH | alarmsReadWriteUserId | 1
+ }
+
// Create alarm as admin
@Unroll
def "should create an alarm with title '#title', content '#content', severity '#severity', assigneeId '#assigneeId' and '#emailNotifications' emailNotifications"() {
@@ -259,6 +317,28 @@ class AlarmResourceTest extends Specification implements ManagerContainerTrait {
"Another Alarm" | "Updated Description" | Severity.MEDIUM | Alarm.Status.CLOSED | keycloakTestSetup.testuser1Id
}
+ // Update alarm as an new super user in other realm
+ @Unroll
+ def "should update an alarm with title '#title', content '#content', severity '#severity', status '#status' and assigneeId '#assigneeId' as an new super user in other realm"() {
+ when:
+ def alarm = superAdminResource.createAlarm(null, new Alarm().setTitle('Updatable alarm').setContent('Updatable content').setStatus(Alarm.Status.CLOSED).setSeverity(Severity.LOW).setRealm(keycloakTestSetup.realmBuilding.name), null)
+ superAdminResource.updateAlarm(null, alarm.id, new SentAlarm().setTitle(title).setContent(content).setRealm(keycloakTestSetup.realmBuilding.name).setSeverity(severity).setStatus(status).setAssigneeId(assigneeId))
+ def updated = superAdminResource.getAlarms(null, keycloakTestSetup.realmBuilding.name, null, null, null)[0]
+
+ then:
+ updated != null
+ updated.title == title
+ updated.content == content
+ updated.severity == severity
+ updated.status == status
+ updated.assigneeId == assigneeId
+
+ where:
+ title | content | severity | status | assigneeId
+ "Updated Alarm" | "Test Description" | Severity.HIGH | Alarm.Status.OPEN | null
+ "Another Alarm" | "Updated Description" | Severity.MEDIUM | Alarm.Status.CLOSED | keycloakTestSetup.testuser1Id
+ }
+
@Unroll
def "should not update an alarm with id 'null'"() {
when:
@@ -382,6 +462,21 @@ class AlarmResourceTest extends Specification implements ManagerContainerTrait {
alarms.length > 0
}
+ // Delete one alarm as an super user in other realm
+ def "should delete one alarm as new super user in other realm"() {
+ when:
+ for (int i = 0; i < 2; i++) {
+ superAdminResource.createAlarm(null, new Alarm("Alarm " + i, "Content " + i, Severity.MEDIUM, null, keycloakTestSetup.realmBuilding.name), null)
+ }
+ def delete = superAdminResource.getAlarms(null, keycloakTestSetup.realmBuilding.name, null, null, null)[0]
+ superAdminResource.removeAlarm(null, delete.id)
+
+ then: "returns some alarms but not the deleted alarm"
+ def alarms = superAdminResource.getAlarms(null, keycloakTestSetup.realmBuilding.name, null, null, null)
+ alarms.find { it.id == delete.id } == null
+ alarms.length > 0
+ }
+
// Delete multiple alarms as admin
def "should delete multiple alarms as admin"() {
when:
@@ -395,6 +490,19 @@ class AlarmResourceTest extends Specification implements ManagerContainerTrait {
adminResource.getAlarms(null, MASTER_REALM, null, null, null).length == 0
}
+ // Delete multiple alarms as super user in other realm
+ def "should delete multiple alarms as super user in other realm"() {
+ when:
+ for (int i = 0; i < 2; i++) {
+ superAdminResource.createAlarm(null, new Alarm("Alarm " + i, "Content " + i, Severity.MEDIUM, null, keycloakTestSetup.realmBuilding.name), null)
+ }
+ def alarms = superAdminResource.getAlarms(null, keycloakTestSetup.realmBuilding.name, null, null, null)
+ superAdminResource.removeAlarms(null, (List<Long>) alarms.collect { it.id })
+
+ then: "returns no alarms"
+ superAdminResource.getAlarms(null, keycloakTestSetup.realmBuilding.name, null, null, null).length == 0
+ }
+
// Get open alarms
def "should get open alarms"() {
when: "two open and one closed alarms are added"
diff --git a/test/src/test/groovy/org/openremote/test/rules/AlarmRuleTest.groovy b/test/src/test/groovy/org/openremote/test/rules/AlarmRuleTest.groovy
index ebb9dcb3b..103b74384 100644
--- a/test/src/test/groovy/org/openremote/test/rules/AlarmRuleTest.groovy
+++ b/test/src/test/groovy/org/openremote/test/rules/AlarmRuleTest.groovy
@@ -101,7 +101,7 @@ class AlarmRuleTest extends Specification implements ManagerContainerTrait {
// Remove all alarms
def alarms = alarmService.getAlarms(managerTestSetup.realmBuildingName, null, null, null)
if (alarms.size() > 0) {
- alarmService.removeAlarms((List<Long>) alarms.collect { it.id }, null)
+ alarmService.removeAlarms(alarms, (List<Long>) alarms.collect { it.id })
}
// Remove all rulesets
@@ -178,7 +178,7 @@ Value: 6000
alarm.assigneeId == assigneeId
and: "the asset is linked to the alarm"
- def assetLinks = alarmService.getAssetLinks(alarm.id, null, managerTestSetup.realmBuildingName)
+ def assetLinks = alarmService.getAssetLinks(alarm.id, managerTestSetup.realmBuildingName)
assetLinks.size() == 1
def assetLink = assetLinks.get(0)
assetLink.id.alarmId == alarm.id