Skip to content

armgit / core

Public Imported from GitHub
0

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

Merge commit from fork

Eric Bariaux3384960b7949
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 e89d1dccb..4d0e55ffd 100644
--- a/manager/src/main/java/org/openremote/manager/alarm/AlarmResourceImpl.java
+++ b/manager/src/main/java/org/openremote/manager/alarm/AlarmResourceImpl.java
@@ -136,6 +136,10 @@ public class AlarmResourceImpl extends ManagerWebResource implements AlarmResour
throw new ForbiddenException("Realm '" + alarm.getRealm() + "' is nonexistent, inactive or inaccessible");
}
return alarmService.sendAlarm(alarm, assetIds);
+ } catch (EntityNotFoundException e) {
+ throw new WebApplicationException(Response.Status.NOT_FOUND);
+ } catch (AlarmService.AlarmAssetLinkRealmMismatchException e) {
+ throw new WebApplicationException(Response.Status.BAD_REQUEST);
} catch (NullPointerException e) {
throw new WebApplicationException(Response.Status.BAD_REQUEST);
} catch (ForbiddenException e) {
@@ -179,18 +183,37 @@ public class AlarmResourceImpl extends ManagerWebResource implements AlarmResour
throw new IllegalArgumentException("No AlarmAssetLink objects were provided.");
}
Set<String> realms = links.stream().map(link -> link.getId().getRealm()).collect(Collectors.toSet());
+ Set<Long> alarmIds = links.stream().map(link -> link.getId().getAlarmId()).collect(Collectors.toSet());
- if (!isRealmActiveAndAccessible(realms.stream().findFirst().orElse(null))) {
- throw new ForbiddenException("Realm '" + realms.stream().findFirst() + "' is nonexistent, inactive or inaccessible");
+ if (alarmIds.size() > 1) {
+ throw new IllegalArgumentException("AlarmAssetLink objects must all have the same alarm ID");
+ }
+
+ if (realms.size() > 1) {
+ throw new IllegalArgumentException("AlarmAssetLink objects must all have the same realm");
+ }
+ for (String realm : realms) {
+ if (TextUtil.isNullOrEmpty(realm)) {
+ throw new IllegalArgumentException("Missing realm");
+ }
+ if (!isRealmActiveAndAccessible(realm)) {
+ throw new ForbiddenException("Realm '" + realm + "' is nonexistent, inactive or inaccessible");
+ }
}
- alarmService.linkAssets(links);
+
+ Long alarmId = alarmIds.iterator().next();
+ String realm = realms.iterator().next();
+ List<String> assetIds = links.stream().map(link -> link.getId().getAssetId()).toList();
+
+ alarmService.linkAssets(assetIds, realm, alarmId);
} catch (EntityNotFoundException e) {
throw new WebApplicationException(Response.Status.NOT_FOUND);
} catch (ForbiddenException e) {
throw new WebApplicationException(Response.Status.FORBIDDEN);
+ } catch (AlarmService.AlarmAssetLinkRealmMismatchException e) {
+ throw new WebApplicationException(Response.Status.BAD_REQUEST);
} 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 be6222eb4..53436eda5 100644
--- a/manager/src/main/java/org/openremote/manager/alarm/AlarmService.java
+++ b/manager/src/main/java/org/openremote/manager/alarm/AlarmService.java
@@ -24,6 +24,7 @@ import jakarta.persistence.PersistenceException;
import jakarta.persistence.TypedQuery;
import org.apache.camel.builder.RouteBuilder;
import org.hibernate.Session;
+import org.openremote.manager.asset.AssetStorageService;
import org.openremote.manager.notification.NotificationService;
import org.openremote.manager.security.ManagerIdentityProvider;
import org.openremote.model.Constants;
@@ -68,8 +69,15 @@ public class AlarmService extends RouteBuilder implements ContainerService {
public static final Logger LOG = Logger.getLogger(AlarmService.class.getName());
+ public static class AlarmAssetLinkRealmMismatchException extends IllegalArgumentException {
+ public AlarmAssetLinkRealmMismatchException(String message) {
+ super(message);
+ }
+ }
+
private Container container;
private ClientEventService clientEventService;
+ private AssetStorageService assetStorageService;
private ManagerIdentityService identityService;
private NotificationService notificationService;
private PersistenceService persistenceService;
@@ -84,6 +92,7 @@ public class AlarmService extends RouteBuilder implements ContainerService {
public void init(Container container) throws Exception {
this.container = container;
this.clientEventService = container.getService(ClientEventService.class);
+ this.assetStorageService = container.getService(AssetStorageService.class);
this.identityService = container.getService(ManagerIdentityService.class);
this.notificationService = container.getService(NotificationService.class);
this.persistenceService = container.getService(PersistenceService.class);
@@ -166,6 +175,26 @@ public class AlarmService extends RouteBuilder implements ContainerService {
});
}
+ /**
+ * Throws an {@link EntityNotFoundException} if any asset does not exist, or an
+ * {@link AlarmAssetLinkRealmMismatchException} if any asset does not belong to {@code realm}.
+ */
+ protected void validateAssetsInRealm(String realm, Collection<String> assetIds) {
+ validateAssetIds(assetIds);
+ Set<String> uniqueAssetIds = new HashSet<>(assetIds);
+ Map<String, String> assetRealms = assetStorageService.getAssetRealms(uniqueAssetIds);
+
+ if (assetRealms.size() != uniqueAssetIds.size()) {
+ throw new EntityNotFoundException("One or more assets do not exist");
+ }
+
+ for (String assetId : uniqueAssetIds) {
+ if (!Objects.equals(realm, assetRealms.get(assetId))) {
+ throw new AlarmAssetLinkRealmMismatchException("Asset '" + assetId + "' is not in realm '" + realm + "'");
+ }
+ }
+ }
+
/**
* Sends an alarm. Callers are responsible for enforcing realm authorization.
*/
@@ -177,6 +206,10 @@ public class AlarmService extends RouteBuilder implements ContainerService {
Objects.requireNonNull(alarm.getSource(), "Source cannot be null");
Objects.requireNonNull(alarm.getSourceId(), "Source ID cannot be null");
+ if (assetIds != null && !assetIds.isEmpty()) {
+ validateAssetsInRealm(alarm.getRealm(), assetIds);
+ }
+
Instant timestamp = Instant.ofEpochMilli(timerService.getCurrentTimeMillis());
SentAlarm sentAlarm = persistenceService.doReturningTransaction(entityManager -> entityManager.merge(new SentAlarm()
.setAssigneeId(alarm.getAssigneeId())
@@ -331,31 +364,30 @@ public class AlarmService extends RouteBuilder implements ContainerService {
}
/**
- * Links multiple assets to an existing alarm.
+ * Links multiple assets to an existing alarm. Callers are responsible for enforcing realm authorization.
*/
public void linkAssets(List<String> assetIds, String realm, Long alarmId) {
- linkAssets(assetIds.stream().map(assetId -> new AlarmAssetLink(realm, alarmId, assetId)).toList());
- }
-
- /**
- * Links multiple assets to existing alarms. Callers are responsible for enforcing realm authorization.
- */
- 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());
+ validateAlarmId(alarmId);
validateAssetIds(assetIds);
+ if (TextUtil.isNullOrEmpty(realm)) {
+ throw new IllegalArgumentException("Missing realm");
+ }
+
+ SentAlarm alarm = getAlarm(alarmId);
+ if (!Objects.equals(realm, alarm.getRealm())) {
+ throw new AlarmAssetLinkRealmMismatchException("Alarm '" + alarmId + "' is not in realm '" + realm + "'");
+ }
+ validateAssetsInRealm(realm, assetIds);
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 (?, ?, ?, ?)
on conflict (sentalarm_id, realm, asset_id) do nothing
""");
- for (AlarmAssetLink link : links) {
- st.setLong(1, link.getId().getAlarmId());
- st.setString(2, link.getId().getRealm());
- st.setString(3, link.getId().getAssetId());
+ for (String assetId : assetIds) {
+ st.setLong(1, alarmId);
+ st.setString(2, realm);
+ st.setString(3, assetId);
st.setTimestamp(4, new Timestamp(timerService.getCurrentTimeMillis()));
st.addBatch();
}
diff --git a/manager/src/main/java/org/openremote/manager/asset/AssetStorageService.java b/manager/src/main/java/org/openremote/manager/asset/AssetStorageService.java
index 23b35899b..6c4c4e907 100644
--- a/manager/src/main/java/org/openremote/manager/asset/AssetStorageService.java
+++ b/manager/src/main/java/org/openremote/manager/asset/AssetStorageService.java
@@ -1000,6 +1000,26 @@ public class AssetStorageService extends RouteBuilder implements ContainerServic
});
}
+ /**
+ * Returns the realm for each asset ID that exists.
+ */
+ public Map<String, String> getAssetRealms(Collection<String> assetIds) {
+ if (assetIds == null || assetIds.isEmpty()) {
+ return Map.of();
+ }
+ return persistenceService.doReturningTransaction(entityManager -> {
+ List<Object[]> result = entityManager.createQuery("""
+ select a.id, a.realm from Asset a
+ where a.id in :assetIds
+ """, Object[].class)
+ .setParameter("assetIds", assetIds)
+ .getResultList();
+ Map<String, String> realms = new HashMap<>();
+ result.forEach(row -> realms.put((String) row[0], (String) row[1]));
+ return realms;
+ });
+ }
+
public boolean isDescendantAsset(String parentAssetId, String assetId) {
return isDescendantAssets(parentAssetId, Collections.singletonList(assetId));
}
diff --git a/model/src/main/java/org/openremote/model/alarm/AlarmResource.java b/model/src/main/java/org/openremote/model/alarm/AlarmResource.java
index 925faf86c..e1297850e 100644
--- a/model/src/main/java/org/openremote/model/alarm/AlarmResource.java
+++ b/model/src/main/java/org/openremote/model/alarm/AlarmResource.java
@@ -20,7 +20,12 @@
package org.openremote.model.alarm;
import io.swagger.v3.oas.annotations.Operation;
+import io.swagger.v3.oas.annotations.media.ArraySchema;
+import io.swagger.v3.oas.annotations.media.Content;
+import io.swagger.v3.oas.annotations.media.ExampleObject;
+import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.parameters.RequestBody;
+import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.openremote.model.Constants;
import org.openremote.model.http.RequestParams;
@@ -90,6 +95,96 @@ public interface AlarmResource {
@Path("assets")
@Consumes(APPLICATION_JSON)
@RolesAllowed({Constants.WRITE_ALARMS_ROLE})
- @Operation(operationId = "setAssetLinks", summary = "Set the asset links of an alarm")
- void setAssetLinks(@BeanParam RequestParams requestParams, @RequestBody List<AlarmAssetLink> links);
+ @Operation(
+ operationId = "setAssetLinks",
+ summary = "Add asset links to a single alarm",
+ description = """
+ Adds links between assets and one existing alarm.
+
+ The request body is a list for backward compatibility, but this operation now has single-alarm semantics:
+ every item must contain the same `id.realm` and the same `id.alarmId`. The alarm must exist in that realm,
+ every asset must exist in the same realm, and the authenticated user must have access to that realm.
+
+ Existing links are left unchanged; duplicate links in the request or links that already exist are ignored.
+ This operation does not remove existing links from the alarm.
+ """,
+ responses = {
+ @ApiResponse(responseCode = "204", description = "Asset links were added, or already existed"),
+ @ApiResponse(responseCode = "400", description = "Invalid request body, multiple alarm IDs or realms were provided, or the alarm/assets are not all in the same realm"),
+ @ApiResponse(responseCode = "401", description = "Authentication is required"),
+ @ApiResponse(responseCode = "403", description = "The authenticated user is not allowed to write alarms in the requested realm"),
+ @ApiResponse(responseCode = "404", description = "The alarm or one or more assets do not exist")
+ }
+ )
+ void setAssetLinks(
+ @BeanParam RequestParams requestParams,
+ @RequestBody(
+ required = true,
+ description = "Alarm asset links to add. All items must use the same `id.realm` and `id.alarmId`.",
+ content = @Content(
+ mediaType = APPLICATION_JSON,
+ array = @ArraySchema(schema = @Schema(implementation = AlarmAssetLink.class)),
+ examples = {
+ @ExampleObject(
+ name = "Single asset link",
+ summary = "Link one asset to one alarm",
+ value = """
+ [
+ {
+ "id": {
+ "realm": "building",
+ "alarmId": 1234,
+ "assetId": "7A6p4AnLTkKxJUCQAAABAA"
+ }
+ }
+ ]
+ """
+ ),
+ @ExampleObject(
+ name = "Multiple asset links",
+ summary = "Link multiple assets to the same alarm",
+ value = """
+ [
+ {
+ "id": {
+ "realm": "building",
+ "alarmId": 1234,
+ "assetId": "7A6p4AnLTkKxJUCQAAABAA"
+ }
+ },
+ {
+ "id": {
+ "realm": "building",
+ "alarmId": 1234,
+ "assetId": "2Qjr4AnLTkKxJUCQAAACAA"
+ }
+ }
+ ]
+ """
+ ),
+ @ExampleObject(
+ name = "Invalid multiple alarms",
+ summary = "Rejected because the request targets more than one alarm",
+ value = """
+ [
+ {
+ "id": {
+ "realm": "building",
+ "alarmId": 1234,
+ "assetId": "7A6p4AnLTkKxJUCQAAABAA"
+ }
+ },
+ {
+ "id": {
+ "realm": "building",
+ "alarmId": 5678,
+ "assetId": "2Qjr4AnLTkKxJUCQAAACAA"
+ }
+ }
+ ]
+ """
+ )
+ }
+ )
+ ) List<AlarmAssetLink> links);
}
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 73b409bf6..e771be6e7 100644
--- a/test/src/test/groovy/org/openremote/test/alarm/AlarmResourceTest.groovy
+++ b/test/src/test/groovy/org/openremote/test/alarm/AlarmResourceTest.groovy
@@ -647,10 +647,8 @@ class AlarmResourceTest extends Specification implements ManagerContainerTrait {
def alarm2 = adminResource.createAlarm(null, new Alarm().setTitle('alarm 2').setContent('content').setStatus(Alarm.Status.OPEN).setSeverity(Severity.LOW).setRealm(MASTER_REALM), null)
then: "both can be linked to an asset"
- adminResource.setAssetLinks(null, [
- new AlarmAssetLink(MASTER_REALM, alarm1.id, managerTestSetup.smartOfficeId),
- new AlarmAssetLink(MASTER_REALM, alarm2.id, managerTestSetup.smartOfficeId)
- ])
+ adminResource.setAssetLinks(null, [new AlarmAssetLink(MASTER_REALM, alarm1.id, managerTestSetup.smartOfficeId)])
+ adminResource.setAssetLinks(null, [new AlarmAssetLink(MASTER_REALM, alarm2.id, managerTestSetup.smartOfficeId)])
when: "the alarm asset links are retrieved"
def alarm1Links = adminResource.getAssetLinks(null, alarm1.id, MASTER_REALM)
@@ -667,10 +665,8 @@ class AlarmResourceTest extends Specification implements ManagerContainerTrait {
alarm2Links.get(0).id.realm == MASTER_REALM
when: "more alarm asset links are added"
- adminResource.setAssetLinks(null, [
- new AlarmAssetLink(MASTER_REALM, alarm1.id, managerTestSetup.lobbyId),
- new AlarmAssetLink(MASTER_REALM, alarm2.id, managerTestSetup.lobbyId)
- ])
+ adminResource.setAssetLinks(null, [new AlarmAssetLink(MASTER_REALM, alarm1.id, managerTestSetup.lobbyId)])
+ adminResource.setAssetLinks(null, [new AlarmAssetLink(MASTER_REALM, alarm2.id, managerTestSetup.lobbyId)])
alarm1Links = adminResource.getAssetLinks(null, alarm1.id, MASTER_REALM)
alarm2Links = adminResource.getAssetLinks(null, alarm2.id, MASTER_REALM)
@@ -691,6 +687,107 @@ class AlarmResourceTest extends Specification implements ManagerContainerTrait {
alarm2Links.get(1).id.realm == MASTER_REALM
}
+ def "should reject asset links for multiple alarms in one request"() {
+ given:
+ def alarm1 = adminResource.createAlarm(null, new Alarm().setTitle('alarm 1').setContent('content').setStatus(Alarm.Status.OPEN).setSeverity(Severity.LOW).setRealm(MASTER_REALM), null)
+ def alarm2 = adminResource.createAlarm(null, new Alarm().setTitle('alarm 2').setContent('content').setStatus(Alarm.Status.OPEN).setSeverity(Severity.LOW).setRealm(MASTER_REALM), null)
+
+ when:
+ adminResource.setAssetLinks(null, [
+ new AlarmAssetLink(MASTER_REALM, alarm1.id, managerTestSetup.smartOfficeId),
+ new AlarmAssetLink(MASTER_REALM, alarm2.id, managerTestSetup.smartOfficeId)
+ ])
+
+ then:
+ WebApplicationException ex = thrown()
+ ex.response.withCloseable { r ->
+ assert r.status == 400
+ return true
+ }
+
+ and:
+ adminResource.getAssetLinks(null, alarm1.id, MASTER_REALM).isEmpty()
+ adminResource.getAssetLinks(null, alarm2.id, MASTER_REALM).isEmpty()
+ }
+
+ // Linking alarms across realms
+ def "should reject asset links for multiple realms in one request"() {
+ given:
+ def buildingRealm = keycloakTestSetup.realmBuilding.name
+ def alarm = buildingUserResource.createAlarm(null, new Alarm("Building alarm", "Building content", Severity.MEDIUM, null, buildingRealm), null)
+ def links = [
+ new AlarmAssetLink(buildingRealm, alarm.id, managerTestSetup.apartment1Id),
+ new AlarmAssetLink(MASTER_REALM, alarm.id, managerTestSetup.smartOfficeId)
+ ]
+
+ when:
+ buildingUserResource.setAssetLinks(null, links)
+
+ then:
+ WebApplicationException ex = thrown()
+ ex.response.withCloseable { r ->
+ assert r.status == 400
+ return true
+ }
+
+ and:
+ buildingUserResource.getAssetLinks(null, alarm.id, buildingRealm).isEmpty()
+ superAdminResource.getAssetLinks(null, alarm.id, MASTER_REALM).isEmpty()
+ }
+
+ def "should reject asset links pointing to assets from another realm"() {
+ given:
+ def buildingRealm = keycloakTestSetup.realmBuilding.name
+ def alarm = buildingUserResource.createAlarm(null, new Alarm("Building alarm", "Building content", Severity.MEDIUM, null, buildingRealm), null)
+
+ when:
+ buildingUserResource.setAssetLinks(null, [new AlarmAssetLink(buildingRealm, alarm.id, managerTestSetup.smartOfficeId)])
+
+ then:
+ WebApplicationException ex = thrown()
+ ex.response.withCloseable { r ->
+ assert r.status == 400
+ return true
+ }
+
+ and:
+ buildingUserResource.getAssetLinks(null, alarm.id, buildingRealm).isEmpty()
+ }
+
+ def "should reject asset links pointing to alarms from another realm"() {
+ given:
+ def buildingRealm = keycloakTestSetup.realmBuilding.name
+ def masterAlarm = adminResource.createAlarm(null, new Alarm("Master alarm", "Master content", Severity.MEDIUM, null, MASTER_REALM), null)
+
+ when:
+ buildingUserResource.setAssetLinks(null, [new AlarmAssetLink(buildingRealm, masterAlarm.id, managerTestSetup.apartment1Id)])
+
+ then:
+ WebApplicationException ex = thrown()
+ ex.response.withCloseable { r ->
+ assert r.status == 400
+ return true
+ }
+
+ and:
+ buildingUserResource.getAssetLinks(null, masterAlarm.id, buildingRealm).isEmpty()
+ }
+
+ def "should reject creating alarms with linked assets from another realm"() {
+ given:
+ def buildingRealm = keycloakTestSetup.realmBuilding.name
+
+ when:
+ buildingUserResource.createAlarm(null, new Alarm("Building alarm", "Building content", Severity.MEDIUM, null, buildingRealm), [managerTestSetup.smartOfficeId])
+
+ then:
+ WebApplicationException ex = thrown()
+ ex.response.withCloseable { r ->
+ assert r.status == 400
+ return true
+ }
+ }
+
// Linking alarms without permissions
def "should not be able to link alarms without proper permissions"() {
when:
@@ -779,4 +876,5 @@ class AlarmResourceTest extends Specification implements ManagerContainerTrait {
return true
}
}
+
}