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

Koena4b5a74bef4d
diff --git a/AGENTS.md b/AGENTS.md
index be83d9c25..ea13b4924 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -15,6 +15,16 @@ In sandboxed environments, add `--offline` (requires dependencies to already be
When running integration tests, part of the stack (PostgreSQL and Keycloak) must be running. Start it with `mkdir -pm 777 tmp && docker compose -f profile/dev-testing.yml -p openremote up -d --no-build`.
Running `./gradlew clean` deletes the root `tmp/` directory that is mounted into PostgreSQL (see `profile/dev-testing.yml`), so recreate it and restart the stack before running tests again.
+## REST resources
+
+### Endpoint roles
+
+Annotate every endpoint with the resource role of its domain, e.g. `read:alarms` or `write:notifications`. Use `read:admin` or `write:admin` only where the domain has no resource role, or where admin-only access is a deliberate decision. The admin roles are standalone, so holding `write:admin` does not grant `write:notifications`.
+
+### Access control
+
+Access control belongs in the resource implementation, not in the service. Extend `ManagerWebResource` and use its checks rather than reaching for the identity provider: `throwIfNotRealmActiveAndAccessible` and `throwIfRestrictedUser` reject with a 403, and `isRealmActiveAndAccessible` and `isRestrictedUser` are there for conditions that need more than a rejection. Resolve the entity first and return 404 when it is missing, then require access to its realm, and apply restricted user rules in the same place. Service methods take already authorised input and state that in their javadoc with "Callers are responsible for enforcing realm authorization." Alarms and notifications are the reference for this shape; equivalent endpoints across the two must enforce the same way. Flows that never pass through a resource, such as notifications published to the message broker, authorise inside the service instead.
+
## UI
### Generated model types
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 4d0e55ffd..467de2cdd 100644
--- a/manager/src/main/java/org/openremote/manager/alarm/AlarmResourceImpl.java
+++ b/manager/src/main/java/org/openremote/manager/alarm/AlarmResourceImpl.java
@@ -20,9 +20,6 @@
package org.openremote.manager.alarm;
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;
@@ -59,14 +56,10 @@ public class AlarmResourceImpl extends ManagerWebResource implements AlarmResour
public SentAlarm[] getAlarms(RequestParams requestParams, String realm, Alarm.Status status, String assetId, String assigneeId) {
try {
String filterRealm = TextUtil.isNullOrEmpty(realm) ? getAuthenticatedRealmName() : realm;
- if (!isRealmActiveAndAccessible(filterRealm)) {
- throw new ForbiddenException("Realm '" + filterRealm + "' is nonexistent, inactive or inaccessible");
- }
+ throwIfNotRealmActiveAndAccessible(filterRealm);
return alarmService.getAlarms(filterRealm, status, assetId, assigneeId).toArray(new SentAlarm[0]);
} catch (IllegalArgumentException | NullPointerException e) {
throw new WebApplicationException(Response.Status.BAD_REQUEST);
- } catch (ForbiddenException e) {
- throw new WebApplicationException(Response.Status.FORBIDDEN);
}
}
@@ -75,15 +68,11 @@ public class AlarmResourceImpl extends ManagerWebResource implements AlarmResour
try {
List<SentAlarm> alarms = alarmService.getAlarms(alarmIds);
for (SentAlarm alarm : alarms) {
- if (!isRealmActiveAndAccessible(alarm.getRealm())) {
- throw new ForbiddenException("Realm '" + alarm.getRealm() + "' is nonexistent, inactive or inaccessible");
- }
+ throwIfNotRealmActiveAndAccessible(alarm.getRealm());
}
alarmService.removeAlarms(alarms, alarmIds);
} 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);
}
@@ -93,14 +82,10 @@ public class AlarmResourceImpl extends ManagerWebResource implements AlarmResour
public SentAlarm getAlarm(RequestParams requestParams, Long alarmId) {
try {
SentAlarm alarm = alarmService.getAlarm(alarmId);
- if (!isRealmActiveAndAccessible(alarm.getRealm())) {
- throw new ForbiddenException("Realm '" + alarm.getRealm() + "' is nonexistent, inactive or inaccessible");
- }
+ throwIfNotRealmActiveAndAccessible(alarm.getRealm());
return alarmService.getAlarm(alarmId);
} catch (EntityNotFoundException e) {
throw new WebApplicationException(Response.Status.NOT_FOUND);
- } catch (ForbiddenException e) {
- throw new WebApplicationException(Response.Status.FORBIDDEN);
}
}
@@ -108,14 +93,10 @@ public class AlarmResourceImpl extends ManagerWebResource implements AlarmResour
public void removeAlarm(RequestParams requestParams, Long alarmId) {
try {
SentAlarm alarm = alarmService.getAlarm(alarmId);
- if (!isRealmActiveAndAccessible(alarm.getRealm())) {
- throw new ForbiddenException("Realm '" + alarm.getRealm() + "' is nonexistent, inactive or inaccessible");
- }
+ throwIfNotRealmActiveAndAccessible(alarm.getRealm());
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);
}
@@ -132,9 +113,7 @@ public class AlarmResourceImpl extends ManagerWebResource implements AlarmResour
alarm.setSourceId(getClientId());
}
- if (!isRealmActiveAndAccessible(alarm.getRealm())) {
- throw new ForbiddenException("Realm '" + alarm.getRealm() + "' is nonexistent, inactive or inaccessible");
- }
+ throwIfNotRealmActiveAndAccessible(alarm.getRealm());
return alarmService.sendAlarm(alarm, assetIds);
} catch (EntityNotFoundException e) {
throw new WebApplicationException(Response.Status.NOT_FOUND);
@@ -142,8 +121,6 @@ public class AlarmResourceImpl extends ManagerWebResource implements AlarmResour
throw new WebApplicationException(Response.Status.BAD_REQUEST);
} catch (NullPointerException e) {
throw new WebApplicationException(Response.Status.BAD_REQUEST);
- } catch (ForbiddenException e) {
- throw new WebApplicationException(Response.Status.FORBIDDEN);
}
}
@@ -151,28 +128,20 @@ public class AlarmResourceImpl extends ManagerWebResource implements AlarmResour
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");
- }
+ throwIfNotRealmActiveAndAccessible(oldAlarm.getRealm());
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) {
try {
- if (!isRealmActiveAndAccessible(realm)) {
- throw new ForbiddenException("Realm '" + realm + "' is nonexistent, inactive or inaccessible");
- }
+ throwIfNotRealmActiveAndAccessible(realm);
return alarmService.getAssetLinks(alarmId, realm);
} catch (EntityNotFoundException e) {
throw new WebApplicationException(Response.Status.NOT_FOUND);
- } catch (ForbiddenException e) {
- throw new WebApplicationException(Response.Status.FORBIDDEN);
}
}
@@ -196,9 +165,7 @@ public class AlarmResourceImpl extends ManagerWebResource implements AlarmResour
if (TextUtil.isNullOrEmpty(realm)) {
throw new IllegalArgumentException("Missing realm");
}
- if (!isRealmActiveAndAccessible(realm)) {
- throw new ForbiddenException("Realm '" + realm + "' is nonexistent, inactive or inaccessible");
- }
+ throwIfNotRealmActiveAndAccessible(realm);
}
Long alarmId = alarmIds.iterator().next();
@@ -208,8 +175,6 @@ public class AlarmResourceImpl extends ManagerWebResource implements AlarmResour
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) {
diff --git a/manager/src/main/java/org/openremote/manager/notification/NotificationResourceImpl.java b/manager/src/main/java/org/openremote/manager/notification/NotificationResourceImpl.java
index d545275b3..59f66ab45 100644
--- a/manager/src/main/java/org/openremote/manager/notification/NotificationResourceImpl.java
+++ b/manager/src/main/java/org/openremote/manager/notification/NotificationResourceImpl.java
@@ -23,9 +23,10 @@ import com.fasterxml.jackson.databind.JsonNode;
import org.openremote.container.message.MessageBrokerService;
import org.openremote.container.security.AuthContext;
-import org.openremote.container.web.WebResource;
+import org.openremote.container.timer.TimerService;
import org.openremote.manager.asset.AssetStorageService;
import org.openremote.manager.security.ManagerIdentityService;
+import org.openremote.manager.web.ManagerWebResource;
import org.openremote.model.Constants;
import org.openremote.model.asset.Asset;
import org.openremote.model.http.RequestParams;
@@ -36,6 +37,7 @@ import org.openremote.model.notification.NotificationResource;
import org.openremote.model.notification.PushNotificationMessage;
import org.openremote.model.notification.SentNotification;
import org.openremote.model.query.AssetQuery;
+import org.openremote.model.security.User;
import org.openremote.model.util.ValueUtil;
import jakarta.ws.rs.WebApplicationException;
@@ -50,23 +52,26 @@ import java.util.logging.Logger;
import static jakarta.ws.rs.core.Response.Status.*;
import static org.openremote.model.notification.Notification.Source.CLIENT;
-public class NotificationResourceImpl extends WebResource implements NotificationResource {
+public class NotificationResourceImpl extends ManagerWebResource implements NotificationResource {
private static final Logger LOG = Logger.getLogger(NotificationResourceImpl.class.getName());
+ /** Restricted users can only read the notifications that involve them, so they may never delete any. */
+ protected static final String RESTRICTED_DELETE_DENIED = "Restricted users cannot delete notifications";
+
final protected NotificationService notificationService;
final protected MessageBrokerService messageBrokerService;
final protected AssetStorageService assetStorageService;
- final protected ManagerIdentityService managerIdentityService;
- public NotificationResourceImpl(NotificationService notificationService,
+ public NotificationResourceImpl(TimerService timerService,
+ ManagerIdentityService identityService,
+ NotificationService notificationService,
MessageBrokerService messageBrokerService,
- AssetStorageService assetStorageService,
- ManagerIdentityService managerIdentityService) {
+ AssetStorageService assetStorageService) {
+ super(timerService, identityService);
this.notificationService = notificationService;
this.messageBrokerService = messageBrokerService;
this.assetStorageService = assetStorageService;
- this.managerIdentityService = managerIdentityService;
}
@Override
@@ -83,8 +88,7 @@ public class NotificationResourceImpl extends WebResource implements Notificatio
realmId != null ? Collections.singletonList(realmId) : null,
userId != null ? Collections.singletonList(userId) : null,
assetId != null ? Collections.singletonList(assetId) : null,
- source, sort, descending != null && descending, offset, limit, authContext,
- managerIdentityService.getIdentityProvider().isRestrictedUser(authContext)
+ source, sort, descending != null && descending, offset, limit, authContext
);
sanitiseNotifications(notifications, authContext);
return notifications.toArray(new SentNotification[0]);
@@ -95,15 +99,36 @@ public class NotificationResourceImpl extends WebResource implements Notificatio
@Override
public void removeNotifications(RequestParams requestParams, Long id, String type, Long from, Long to, String realmId, String userId, String assetId) {
+ throwIfRestrictedUser(RESTRICTED_DELETE_DENIED);
+ String realm = resolveAndAuthoriseRealm(getAuthContext(), realmId);
+
+ if (id != null) {
+ throwIfNotRealmActiveAndAccessible(getNotification(id).getRealm());
+ }
+ if (userId != null) {
+ User user = identityService.getIdentityProvider().getUser(userId);
+ if (user == null) {
+ throw new WebApplicationException("User not found", NOT_FOUND);
+ }
+ throwIfNotRealmActiveAndAccessible(user.getRealm());
+ }
+ if (assetId != null) {
+ Asset<?> asset = assetStorageService.find(assetId, false);
+ if (asset == null) {
+ throw new WebApplicationException("Asset not found", NOT_FOUND);
+ }
+ throwIfNotRealmActiveAndAccessible(asset.getRealm());
+ }
+
try {
notificationService.removeNotifications(
- id != null ? Collections.singletonList(id) : null,
- type != null ? Collections.singletonList(type) : null,
+ id,
+ type,
from != null ? Instant.ofEpochMilli(from) : null,
to != null ? Instant.ofEpochMilli(to) : null,
- realmId != null ? Collections.singletonList(realmId) : null,
- userId != null ? Collections.singletonList(userId) : null,
- assetId != null ? Collections.singletonList(assetId) : null);
+ realm,
+ userId,
+ assetId);
} catch (IllegalArgumentException e) {
throw new WebApplicationException("Invalid criteria set", BAD_REQUEST);
}
@@ -115,9 +140,20 @@ public class NotificationResourceImpl extends WebResource implements Notificatio
throw new WebApplicationException("Missing notification ID", BAD_REQUEST);
}
+ throwIfRestrictedUser(RESTRICTED_DELETE_DENIED);
+ throwIfNotRealmActiveAndAccessible(getNotification(notificationId).getRealm());
+
notificationService.removeNotification(notificationId);
}
+ protected SentNotification getNotification(Long notificationId) {
+ SentNotification sentNotification = notificationService.getSentNotification(notificationId);
+ if (sentNotification == null) {
+ throw new WebApplicationException("Notification not found", NOT_FOUND);
+ }
+ return sentNotification;
+ }
+
@Override
public void sendNotification(RequestParams requestParams, Notification notification) {
@@ -199,7 +235,7 @@ public class NotificationResourceImpl extends WebResource implements Notificatio
} else {
// Regular users can only update notifications sent to them or assets in their realm
// Restricted users can only update notifications sent to them or assets linked to them
- boolean isRestrictedUser = managerIdentityService.getIdentityProvider().isRestrictedUser(getAuthContext());
+ boolean isRestrictedUser = isRestrictedUser();
switch (sentNotification.getTarget()) {
case REALM:
@@ -247,8 +283,7 @@ public class NotificationResourceImpl extends WebResource implements Notificatio
realmId != null ? Collections.singletonList(realmId) : null,
userId != null ? Collections.singletonList(userId) : null,
assetId != null ? Collections.singletonList(assetId) : null,
- source, authContext,
- managerIdentityService.getIdentityProvider().isRestrictedUser(authContext)
+ source, authContext
);
} catch (IllegalArgumentException e) {
throw new WebApplicationException("Invalid criteria set", BAD_REQUEST);
@@ -256,9 +291,10 @@ public class NotificationResourceImpl extends WebResource implements Notificatio
}
/**
- * Resolves the realm to query and verifies the caller may access it. Superusers may query any realm (or all
- * realms when {@code realmId} is null); other callers default to their own realm and may not query a realm they
- * cannot access (which would otherwise let them read another realm's notifications by passing its ID).
+ * Resolves the realm a request applies to and verifies the caller may access it. Superusers may target any realm
+ * (or all realms when {@code realmId} is null); other callers are confined to their own realm and may not target
+ * a realm they cannot access (which would otherwise let them read or delete another realm's notifications by
+ * passing its ID).
*/
protected String resolveAndAuthoriseRealm(AuthContext authContext, String realmId) {
if (authContext == null || authContext.isSuperUser()) {
@@ -267,9 +303,7 @@ public class NotificationResourceImpl extends WebResource implements Notificatio
if (realmId == null) {
return authContext.getAuthenticatedRealmName();
}
- if (!managerIdentityService.getIdentityProvider().isRealmActiveAndAccessible(authContext, realmId)) {
- throw new WebApplicationException("Realm '" + realmId + "' is nonexistent, inactive or inaccessible", FORBIDDEN);
- }
+ throwIfNotRealmActiveAndAccessible(realmId);
return realmId;
}
diff --git a/manager/src/main/java/org/openremote/manager/notification/NotificationService.java b/manager/src/main/java/org/openremote/manager/notification/NotificationService.java
index abd6f4667..72becd6d7 100644
--- a/manager/src/main/java/org/openremote/manager/notification/NotificationService.java
+++ b/manager/src/main/java/org/openremote/manager/notification/NotificationService.java
@@ -97,10 +97,11 @@ public class NotificationService extends RouteBuilder implements ContainerServic
notificationHandlerMap.put(notificationHandler.getTypeName(), notificationHandler));
container.getService(ManagerWebService.class).addApiSingleton(
- new NotificationResourceImpl(this,
+ new NotificationResourceImpl(timerService,
+ container.getService(ManagerIdentityService.class),
+ this,
container.getService(MessageBrokerService.class),
- container.getService(AssetStorageService.class),
- container.getService(ManagerIdentityService.class))
+ container.getService(AssetStorageService.class))
);
clientEventService.addSubscriptionAuthorizer((realm, authContext, eventSubscription) -> {
if (!eventSubscription.isEventType(NotificationEvent.class) || authContext == null) {
@@ -352,6 +353,9 @@ public class NotificationService extends RouteBuilder implements ContainerServic
return messageBrokerService.getFluentProducerTemplate().withBody(notification).withHeaders(headers).to(NotificationService.NOTIFICATION_QUEUE).request(Boolean.class);
}
+ /**
+ * Marks a sent notification as delivered. Callers are responsible for enforcing realm authorization.
+ */
public void setNotificationDelivered(long id) {
setNotificationDelivered(id, timerService.getCurrentTimeMillis());
}
@@ -365,6 +369,9 @@ public class NotificationService extends RouteBuilder implements ContainerServic
});
}
+ /**
+ * Marks a sent notification as acknowledged. Callers are responsible for enforcing realm authorization.
+ */
public void setNotificationAcknowledged(long id, String acknowledgement) {
setNotificationAcknowledged(id, acknowledgement, timerService.getCurrentTimeMillis());
}
@@ -379,14 +386,22 @@ public class NotificationService extends RouteBuilder implements ContainerServic
});
}
+ /**
+ * Retrieves the details of an existing sent notification. Callers are responsible for enforcing realm
+ * authorization.
+ */
public SentNotification getSentNotification(Long notificationId) {
return persistenceService.doReturningTransaction(em -> em.find(SentNotification.class, notificationId));
}
- public List<SentNotification> getNotifications(List<Long> ids, List<String> types, Instant from, Instant to, List<String> realmIds, List<String> userIds, List<String> assetIds, Notification.Source source, SentNotification.SortField sort, boolean descending, Integer offset, Integer limit, AuthContext authContext, boolean restricted) throws IllegalArgumentException {
+ /**
+ * Retrieves sent notifications matching the criteria. Callers are responsible for enforcing realm authorization;
+ * the auth context only narrows the results to what a restricted caller may see.
+ */
+ public List<SentNotification> getNotifications(List<Long> ids, List<String> types, Instant from, Instant to, List<String> realmIds, List<String> userIds, List<String> assetIds, Notification.Source source, SentNotification.SortField sort, boolean descending, Integer offset, Integer limit, AuthContext authContext) throws IllegalArgumentException {
StringBuilder builder = new StringBuilder("select n from SentNotification n where 1=1");
List<Object> parameters = new ArrayList<>();
- buildNotificationCriteria(builder, parameters, ids, types, from, to, realmIds, userIds, assetIds, source, authContext, restricted);
+ buildNotificationCriteria(builder, parameters, ids, types, from, to, realmIds, userIds, assetIds, source, authContext);
builder.append(buildOrderBy(sort, descending));
return persistenceService.doReturningTransaction(entityManager -> {
@@ -403,10 +418,14 @@ public class NotificationService extends RouteBuilder implements ContainerServic
});
}
- public long getNotificationsCount(List<String> types, Instant from, Instant to, List<String> realmIds, List<String> userIds, List<String> assetIds, Notification.Source source, AuthContext authContext, boolean restricted) throws IllegalArgumentException {
+ /**
+ * Counts sent notifications matching the criteria. Callers are responsible for enforcing realm authorization;
+ * the auth context only narrows the count to what a restricted caller may see.
+ */
+ public long getNotificationsCount(List<String> types, Instant from, Instant to, List<String> realmIds, List<String> userIds, List<String> assetIds, Notification.Source source, AuthContext authContext) throws IllegalArgumentException {
StringBuilder builder = new StringBuilder("select count(n) from SentNotification n where 1=1");
List<Object> parameters = new ArrayList<>();
- buildNotificationCriteria(builder, parameters, null, types, from, to, realmIds, userIds, assetIds, source, authContext, restricted);
+ buildNotificationCriteria(builder, parameters, null, types, from, to, realmIds, userIds, assetIds, source, authContext);
return persistenceService.doReturningTransaction(entityManager -> {
TypedQuery<Long> query = entityManager.createQuery(builder.toString(), Long.class);
@@ -441,7 +460,7 @@ public class NotificationService extends RouteBuilder implements ContainerServic
* Restricted callers are additionally limited to notifications they sent, that target them, or that target
* their realm; any other caller with access sees all notifications matching the criteria.
*/
- protected void buildNotificationCriteria(StringBuilder builder, List<Object> parameters, List<Long> ids, List<String> types, Instant from, Instant to, List<String> realmIds, List<String> userIds, List<String> assetIds, Notification.Source source, AuthContext authContext, boolean restricted) {
+ protected void buildNotificationCriteria(StringBuilder builder, List<Object> parameters, List<Long> ids, List<String> types, Instant from, Instant to, List<String> realmIds, List<String> userIds, List<String> assetIds, Notification.Source source, AuthContext authContext) {
int idx = 1;
if (ids != null && !ids.isEmpty()) {
@@ -479,9 +498,8 @@ public class NotificationService extends RouteBuilder implements ContainerServic
}
// Only restricted users are limited to notifications they sent, that target them, or that target their realm;
- // any other caller with access (read:notifications / read:admin / superuser) sees all of them. Whether the
- // caller is restricted is decided by the caller (resource layer) so authorization logic stays in one place.
- if (restricted && authContext != null) {
+ // any other caller with access (read:notifications / superuser) sees all of them.
+ if (authContext != null && identityService.getIdentityProvider().isRestrictedUser(authContext)) {
builder.append(" AND (n.sourceId = ?").append(idx++)
.append(" OR (n.target = ?").append(idx++).append(" AND n.targetId = ?").append(idx++).append(")")
.append(" OR (n.target = ?").append(idx++).append(" AND n.targetId = ?").append(idx++).append("))");
@@ -493,6 +511,9 @@ public class NotificationService extends RouteBuilder implements ContainerServic
}
}
+ /**
+ * Removes an existing sent notification. Callers are responsible for enforcing realm authorization.
+ */
public void removeNotification(Long id) {
persistenceService.doTransaction(entityManager -> entityManager
.createQuery("delete SentNotification where id = :id")
@@ -501,104 +522,59 @@ public class NotificationService extends RouteBuilder implements ContainerServic
);
}
- public void removeNotifications(List<Long> ids, List<String> types, Instant from, Instant to, List<String> realmIds, List<String> userIds, List<String> assetIds) throws IllegalArgumentException {
-
- StringBuilder builder = new StringBuilder();
- builder.append("delete from SentNotification n where 1=1");
- List<Object> parameters = new ArrayList<>();
- processCriteria(builder, parameters, ids, types, from, to, realmIds, userIds, assetIds, true);
-
- persistenceService.doTransaction(entityManager -> {
- Query query = entityManager.createQuery(builder.toString());
- IntStream.rangeClosed(1, parameters.size())
- .forEach(i -> query.setParameter(i, parameters.get(i-1)));
- query.executeUpdate();
- });
- }
-
- protected void processCriteria(StringBuilder builder, List<Object> parameters, List<Long> ids, List<String> types, Instant from, Instant to, List<String> realmIds, List<String> userIds, List<String> assetIds, boolean isRemove) {
- boolean hasIds = ids != null && !ids.isEmpty();
- boolean hasTypes = types != null && !types.isEmpty();
- boolean hasRealms = realmIds != null && !realmIds.isEmpty();
- boolean hasUsers = userIds != null && !userIds.isEmpty();
- boolean hasAssets = assetIds != null && !assetIds.isEmpty();
- int counter = 0;
-
- if (hasIds) {
- counter++;
- }
- if (hasTypes) {
- counter++;
- }
- if (hasRealms) {
- counter++;
- }
- if (hasUsers) {
- counter++;
- }
- if (hasAssets) {
- counter++;
- }
+ /**
+ * Removes existing sent notifications matching the criteria; a non null realm confines the delete to that realm
+ * and at least one other criterion is required. Callers are responsible for enforcing realm authorization,
+ * including that the notification, user and asset are accessible to the requester.
+ */
+ public void removeNotifications(Long id, String type, Instant from, Instant to, String realm, String userId, String assetId) throws IllegalArgumentException {
- if (isRemove && from == null && to == null && counter == 0) {
+ if (id == null && type == null && from == null && to == null && userId == null && assetId == null) {
LOG.fine("No filters set for remove notifications request so not allowed");
throw new IllegalArgumentException("No criteria specified");
}
- if (hasIds) {
- builder.append(" AND n.id IN ?")
- .append(parameters.size() + 1);
- parameters.add(ids);
- return;
- }
+ StringBuilder builder = new StringBuilder("delete from SentNotification n where 1=1");
+ List<Object> parameters = new ArrayList<>();
- if (hasTypes) {
- builder.append(" AND n.type IN ?")
- .append(parameters.size() + 1);
- parameters.add(types);
+ if (id != null) {
+ builder.append(" AND n.id = ?").append(parameters.size() + 1);
+ parameters.add(id);
+ }
+ if (type != null) {
+ builder.append(" AND n.type = ?").append(parameters.size() + 1);
+ parameters.add(type);
}
-
if (from != null) {
- builder.append(" AND n.sentOn >= ?")
- .append(parameters.size() + 1);
-
+ builder.append(" AND n.sentOn >= ?").append(parameters.size() + 1);
parameters.add(from);
}
-
if (to != null) {
- builder.append(" AND n.sentOn <= ?")
- .append(parameters.size() + 1);
-
+ builder.append(" AND n.sentOn <= ?").append(parameters.size() + 1);
parameters.add(to);
}
-
- if (hasAssets) {
- builder.append(" AND n.target = ?")
- .append(parameters.size() + 1)
- .append(" AND n.targetId IN ?")
- .append(parameters.size() + 2);
-
+ if (realm != null) {
+ builder.append(" AND n.realm = ?").append(parameters.size() + 1);
+ parameters.add(realm);
+ }
+ if (assetId != null) {
+ builder.append(" AND n.target = ?").append(parameters.size() + 1)
+ .append(" AND n.targetId = ?").append(parameters.size() + 2);
parameters.add(Notification.TargetType.ASSET);
- parameters.add(assetIds);
-
- } else if (hasUsers) {
- builder.append(" AND n.target = ?")
- .append(parameters.size() + 1)
- .append(" AND n.targetId IN ?")
- .append(parameters.size() + 2);
-
+ parameters.add(assetId);
+ } else if (userId != null) {
+ builder.append(" AND n.target = ?").append(parameters.size() + 1)
+ .append(" AND n.targetId = ?").append(parameters.size() + 2);
parameters.add(Notification.TargetType.USER);
- parameters.add(userIds);
-
- } else if (hasRealms) {
- builder.append(" AND n.target = ?")
- .append(parameters.size() + 1)
- .append(" AND n.targetId IN ?")
- .append(parameters.size() + 2);
-
- parameters.add(Notification.TargetType.REALM);
- parameters.add(realmIds);
+ parameters.add(userId);
}
+
+ persistenceService.doTransaction(entityManager -> {
+ Query query = entityManager.createQuery(builder.toString());
+ IntStream.rangeClosed(1, parameters.size())
+ .forEach(i -> query.setParameter(i, parameters.get(i-1)));
+ query.executeUpdate();
+ });
}
diff --git a/manager/src/main/java/org/openremote/manager/services/ExternalServiceResourceImpl.java b/manager/src/main/java/org/openremote/manager/services/ExternalServiceResourceImpl.java
index 4ebf3dd3e..56216acef 100644
--- a/manager/src/main/java/org/openremote/manager/services/ExternalServiceResourceImpl.java
+++ b/manager/src/main/java/org/openremote/manager/services/ExternalServiceResourceImpl.java
@@ -113,10 +113,7 @@ public class ExternalServiceResourceImpl extends ManagerWebResource implements E
@Override
public ExternalService[] getServices(RequestParams requestParams, String realm) {
- if (!isRealmActiveAndAccessible(realm)) {
- throw new WebApplicationException("Realm '" + realm + "' is nonexistent, inactive or inaccessible",
- Response.Status.FORBIDDEN);
- }
+ throwIfNotRealmActiveAndAccessible(realm);
return externalServiceRegistry.getServices(realm);
}
@@ -130,11 +127,7 @@ public class ExternalServiceResourceImpl extends ManagerWebResource implements E
Response.Status.NOT_FOUND);
}
- if (!isRealmActiveAndAccessible(service.getRealm())) {
- throw new WebApplicationException(
- "Realm '" + service.getRealm() + "' is nonexistent, inactive or inaccessible",
- Response.Status.FORBIDDEN);
- }
+ throwIfNotRealmActiveAndAccessible(service.getRealm());
return service;
}
@@ -159,11 +152,7 @@ public class ExternalServiceResourceImpl extends ManagerWebResource implements E
Response.Status.NOT_FOUND);
}
- if (!isRealmActiveAndAccessible(service.getRealm())) {
- throw new WebApplicationException(
- "Realm '" + service.getRealm() + "' is nonexistent, inactive or inaccessible",
- Response.Status.FORBIDDEN);
- }
+ throwIfNotRealmActiveAndAccessible(service.getRealm());
// Restrict heartbeats to the user who registered the service
if (!isServiceRegistrarCurrentUser(service)) {
@@ -196,11 +185,7 @@ public class ExternalServiceResourceImpl extends ManagerWebResource implements E
Response.Status.NOT_FOUND);
}
- if (!isRealmActiveAndAccessible(service.getRealm())) {
- throw new WebApplicationException(
- "Realm '" + service.getRealm() + "' is nonexistent, inactive or inaccessible",
- Response.Status.FORBIDDEN);
- }
+ throwIfNotRealmActiveAndAccessible(service.getRealm());
// Restrict de-registering a service to the user who registered the service
if (!isServiceRegistrarCurrentUser(service)) {
diff --git a/manager/src/main/java/org/openremote/manager/web/ManagerWebResource.java b/manager/src/main/java/org/openremote/manager/web/ManagerWebResource.java
index 429f652c5..08e7b0979 100644
--- a/manager/src/main/java/org/openremote/manager/web/ManagerWebResource.java
+++ b/manager/src/main/java/org/openremote/manager/web/ManagerWebResource.java
@@ -24,6 +24,10 @@ import org.openremote.container.web.WebResource;
import org.openremote.manager.security.ManagerIdentityService;
import org.openremote.model.security.Realm;
+import jakarta.ws.rs.WebApplicationException;
+
+import static jakarta.ws.rs.core.Response.Status.FORBIDDEN;
+
public class ManagerWebResource extends WebResource {
final protected TimerService timerService;
@@ -54,4 +58,22 @@ public class ManagerWebResource extends WebResource {
return identityService.getIdentityProvider().isRealmActiveAndAccessible(getAuthContext(), realm);
}
+ /**
+ * Rejects the request with a 403 when the caller cannot access the realm.
+ */
+ public void throwIfNotRealmActiveAndAccessible(String realm) {
+ if (!isRealmActiveAndAccessible(realm)) {
+ throw new WebApplicationException("Realm '" + realm + "' is nonexistent, inactive or inaccessible", FORBIDDEN);
+ }
+ }
+
+ /**
+ * Rejects the request with a 403 when the caller is a restricted user.
+ */
+ public void throwIfRestrictedUser(String message) {
+ if (isRestrictedUser()) {
+ throw new WebApplicationException(message, FORBIDDEN);
+ }
+ }
+
}
diff --git a/model/src/main/java/org/openremote/model/notification/NotificationResource.java b/model/src/main/java/org/openremote/model/notification/NotificationResource.java
index 08ffe2e5e..6210c664c 100644
--- a/model/src/main/java/org/openremote/model/notification/NotificationResource.java
+++ b/model/src/main/java/org/openremote/model/notification/NotificationResource.java
@@ -37,11 +37,11 @@ public interface NotificationResource {
* Gets sent notifications matching the supplied criteria; optionally limiting the scope by {@link
* AbstractNotificationMessage} type, sent datetime, realm, target user/asset, {@link Notification.Source} and/or
* pagination (offset/limit). Restricted users only ever see notifications they sent or that target them or their
- * realm; non-superusers are limited to a realm they can access (their own when none is specified).
+ * realm.
*/
@GET
@Produces(APPLICATION_JSON)
- @RolesAllowed({Constants.READ_ADMIN_ROLE, Constants.READ_NOTIFICATIONS_ROLE})
+ @RolesAllowed({Constants.READ_NOTIFICATIONS_ROLE})
@Operation(operationId = "getNotifications", summary = "Retrieve sent notifications matching the supplied criteria")
SentNotification[] getNotifications(@BeanParam RequestParams requestParams,
@QueryParam("id") Long id,
@@ -62,11 +62,9 @@ public interface NotificationResource {
* request by {@link AbstractNotificationMessage} type and/or sent datetime. If type(s) or timestamp are not set
* then it is assumed no type or time constraint is required. Can also provide a list of notification IDs to delete
* specific notifications.
- * <p>
- * Only the superuser can call this operation.
*/
@DELETE
- @RolesAllowed({Constants.WRITE_ADMIN_ROLE})
+ @RolesAllowed({Constants.WRITE_NOTIFICATIONS_ROLE})
@Operation(operationId = "removeNotifications", summary = "Delete all sent notifications by targets")
void removeNotifications(@BeanParam RequestParams requestParams,
@QueryParam("id") Long id,
@@ -79,12 +77,10 @@ public interface NotificationResource {
/**
* Remove a specific sent notification by ID.
- * <p>
- * Only the superuser can call this operation.
*/
@DELETE
@Path("{notificationId}")
- @RolesAllowed({Constants.WRITE_ADMIN_ROLE})
+ @RolesAllowed({Constants.WRITE_NOTIFICATIONS_ROLE})
@Operation(operationId = "removeNotification", summary = "Delete a sent notification")
void removeNotification(@BeanParam RequestParams requestParams,
@PathParam("notificationId") Long notificationId);
@@ -97,7 +93,7 @@ public interface NotificationResource {
@POST
@Path("alert")
@Consumes(APPLICATION_JSON)
- @RolesAllowed({Constants.WRITE_ADMIN_ROLE, Constants.WRITE_NOTIFICATIONS_ROLE})
+ @RolesAllowed({Constants.WRITE_NOTIFICATIONS_ROLE})
@Operation(operationId = "sendNotification", summary = "Send a notification to one or more targets")
void sendNotification(@BeanParam RequestParams requestParams,
Notification notification);
@@ -137,7 +133,7 @@ public interface NotificationResource {
@GET
@Path("count")
@Produces(APPLICATION_JSON)
- @RolesAllowed({Constants.READ_ADMIN_ROLE, Constants.READ_NOTIFICATIONS_ROLE})
+ @RolesAllowed({Constants.READ_NOTIFICATIONS_ROLE})
@Operation(operationId = "getNotificationsCount", summary = "Count sent notifications matching the supplied criteria")
long getNotificationsCount(@BeanParam RequestParams requestParams,
@QueryParam("type") String type,
diff --git a/test/src/test/groovy/org/openremote/test/notification/NotificationTest.groovy b/test/src/test/groovy/org/openremote/test/notification/NotificationTest.groovy
index 68f2f20a2..36712045c 100644
--- a/test/src/test/groovy/org/openremote/test/notification/NotificationTest.groovy
+++ b/test/src/test/groovy/org/openremote/test/notification/NotificationTest.groovy
@@ -477,15 +477,12 @@ class NotificationTest extends Specification implements ManagerContainerTrait {
assert adminNotificationResource.getNotifications(null, null, null, null, null, null, null, anonymousConsole.id, null, null, null, null, null).count {it.deliveredOn != null} == 1
}
- when: "a regular user tries to remove notifications"
+ when: "a regular user removes notifications of their own realm"
testuser1NotificationResource.removeNotifications(null, null, PushNotificationMessage.TYPE, null, null, MASTER_REALM, null, null)
- then: "access should be forbidden"
- ex = thrown()
- ex.response.withCloseable { r ->
- assert r.status == 403
- return true
- }
+ then: "write:notifications grants the delete and the other realm's notifications are untouched"
+ noExceptionThrown()
+ adminNotificationResource.getNotifications(null, null, PushNotificationMessage.TYPE, null, null, null, null, null, null, null, null, null, null).length > 0
when: "a restricted user tries to remove notifications"
testuser3NotificationResource.removeNotifications(null, null, PushNotificationMessage.TYPE, null, null, realm, null, null)
@@ -1071,7 +1068,7 @@ class NotificationTest extends Specification implements ManagerContainerTrait {
((LocalizedNotificationMessage) invalidNotification.getMessage()).setMessage("nl", new PushNotificationMessage())*/
}
- def "Check get notifications by realm access control"() {
+ def "Check notification realm access control"() {
List<Message> sentEmails = new CopyOnWriteArrayList<>()
@@ -1113,11 +1110,22 @@ class NotificationTest extends Specification implements ManagerContainerTrait {
identityProvider.updateUserClientRoles(buildingRealm, notifUser.id, KEYCLOAK_CLIENT_ID, READ_NOTIFICATIONS_ROLE)
def notifUserId = notifUser.id
+ and: "a transient master realm user with an email address, so a master realm notification gets persisted"
+ def masterUserInput = new User()
+ masterUserInput.username = "masternotifuser"
+ masterUserInput.firstName = "Master"
+ masterUserInput.lastName = "User"
+ masterUserInput.email = "[email protected]"
+ masterUserInput.enabled = true
+ identityProvider.createUpdateUser(MASTER_REALM, masterUserInput, "masternotifuser", true)
+
and: "authenticated users with differing permissions"
def adminAccessToken = authenticate(container, MASTER_REALM, KEYCLOAK_CLIENT_ID, MASTER_REALM_ADMIN_USER, getString(container.getConfig(), OR_ADMIN_PASSWORD, OR_ADMIN_PASSWORD_DEFAULT))
def testuser2AccessToken = authenticate(container, buildingRealm, KEYCLOAK_CLIENT_ID, "testuser2", "testuser2")
def buildingUserAccessToken = authenticate(container, buildingRealm, KEYCLOAK_CLIENT_ID, "building", "building")
def notifUserAccessToken = authenticate(container, buildingRealm, KEYCLOAK_CLIENT_ID, "notifuser", "notifuser")
+ // testuser4 is a building realm admin (write:admin), i.e. it may delete but only within its own realm
+ def testuser4AccessToken = authenticate(container, buildingRealm, KEYCLOAK_CLIENT_ID, "testuser4", "testuser4")
and: "a helper that requests notifications for a realm over REST as the given user"
// realm is selected via the realmId query param (the consolidated endpoint has no realm path segment)
@@ -1127,6 +1135,26 @@ class NotificationTest extends Specification implements ManagerContainerTrait {
.request().get()
}
+ and: "a helper that reads the notifications of a realm with a given name as the superuser"
+ def notificationsNamed = { String realmId, String name ->
+ def response = requestNotificationsByRealm(MASTER_REALM, adminAccessToken, realmId)
+ def sent = response.readEntity(SentNotification[].class).findAll { it.name == name }
+ response.close()
+ return sent
+ }
+
+ and: "helpers that delete notifications over REST as the given user"
+ def deleteNotifications = { String authRealm, String token, Map<String, Object> queryParams ->
+ def target = getClientApiTarget(serverUri(serverPort), authRealm, token).path("notification")
+ queryParams.each { name, value -> target = target.queryParam(name, value) }
+ target.request().delete()
+ }
+ def deleteNotificationById = { String authRealm, String token, Long notificationId ->
+ getClientApiTarget(serverUri(serverPort), authRealm, token)
+ .path("notification").path(notificationId.toString())
+ .request().delete()
+ }
+
when: "an email notification is sent to the entire building realm"
def notification = new Notification(
"RealmAccessTest",
@@ -1225,6 +1253,60 @@ class NotificationTest extends Specification implements ManagerContainerTrait {
noRealmSent[0].targetId == buildingUserId
noRealmResponse.close()
+ when: "an email notification is sent to the entire master realm"
+ def masterNotification = new Notification(
+ "MasterRealmAccessTest",
+ new EmailNotificationMessage().setSubject("Master realm test").setText("Hello master"),
+ Collections.singletonList(new Notification.Target(Notification.TargetType.REALM, MASTER_REALM)), null, null)
+ notificationService.sendNotification(masterNotification, Notification.Source.REALM_RULESET, MASTER_REALM)
+
+ then: "it is persisted against the master realm"
+ conditions.eventually {
+ assert notificationsNamed(MASTER_REALM, "MasterRealmAccessTest").size() > 0
+ }
+
+ when: "a realm admin of the building realm tries to delete the master realm's notifications"
+ def masterCount = notificationsNamed(MASTER_REALM, "MasterRealmAccessTest").size()
+ def crossRealmDelete = deleteNotifications(buildingRealm, testuser4AccessToken, [realmId: MASTER_REALM, type: EmailNotificationMessage.TYPE])
+
+ then: "the request is forbidden and the master realm's notifications are untouched"
+ crossRealmDelete.status == 403
+ crossRealmDelete.close()
+ notificationsNamed(MASTER_REALM, "MasterRealmAccessTest").size() == masterCount
+
+ when: "a realm admin of the building realm tries to delete a single master realm notification by id"
+ def masterNotificationId = notificationsNamed(MASTER_REALM, "MasterRealmAccessTest")[0].id
+ def byIdDelete = deleteNotificationById(buildingRealm, testuser4AccessToken, masterNotificationId)
+
+ then: "the request is forbidden and the notification remains"
+ byIdDelete.status == 403
+ byIdDelete.close()
+ notificationsNamed(MASTER_REALM, "MasterRealmAccessTest").any { it.id == masterNotificationId }
+
+ when: "the superuser deletes a notification that doesn't exist"
+ def missingDelete = deleteNotificationById(MASTER_REALM, adminAccessToken, Long.MAX_VALUE)
+
+ then: "the notification is reported as not found"
+ missingDelete.status == 404
+ missingDelete.close()
+
+ when: "a realm admin of the building realm deletes notifications by type without specifying a realm"
+ def ownRealmDelete = deleteNotifications(buildingRealm, testuser4AccessToken, [type: EmailNotificationMessage.TYPE])
+
+ then: "only their own realm's notifications are deleted"
+ ownRealmDelete.status == 204
+ ownRealmDelete.close()
+ notificationsNamed(buildingRealm, "RealmAccessTest").isEmpty()
+ notificationsNamed(MASTER_REALM, "MasterRealmAccessTest").size() == masterCount
+
+ when: "the superuser deletes notifications by type"
+ def superUserDelete = deleteNotifications(MASTER_REALM, adminAccessToken, [type: EmailNotificationMessage.TYPE])
+
+ then: "the delete is not confined to a realm"
+ superUserDelete.status == 204
+ superUserDelete.close()
+ notificationsNamed(MASTER_REALM, "MasterRealmAccessTest").isEmpty()
+
cleanup: "the mock is removed"
notificationService.notificationHandlerMap.put(emailNotificationHandler.getTypeName(), emailNotificationHandler)
}
diff --git a/ui/app/manager/src/headers.ts b/ui/app/manager/src/headers.ts
index 85b1c452c..3a86a936c 100644
--- a/ui/app/manager/src/headers.ts
+++ b/ui/app/manager/src/headers.ts
@@ -129,7 +129,7 @@ export function headerItemNotifications<S extends AppStateKeyed, A extends AnyAc
value: "notifications",
href: getNotificationsRoute(),
text: "notification_other",
- roles: ["read:admin", "read:notifications"]
+ roles: ["read:notifications"]
}
}
diff --git a/ui/app/manager/src/pages/page-notifications.ts b/ui/app/manager/src/pages/page-notifications.ts
index a7f466a28..ce0198eeb 100644
--- a/ui/app/manager/src/pages/page-notifications.ts
+++ b/ui/app/manager/src/pages/page-notifications.ts
@@ -443,7 +443,7 @@ export class PageNotifications extends Page<AppStateKeyed> {
}
protected render() {
- const writeNotifications = manager.hasRole("write:admin") || manager.hasRole("write:notifications");
+ const writeNotifications = manager.hasRole("write:notifications");
const hasRecipientType = manager.hasRole("read:admin")
|| manager.hasRole("read:assets")
|| manager.hasRole("read:users");