100% open-source IoT Platform - Integrate your devices, add intelligence, build custom apps
Java asset-managementbuildingdashboarddataplatformdevice-managementedge-computingenergyenergy-managementenergy-monitorfleet-managementfleet-telematicsiotiot-applicationiot-platformmodbusmqttmqtt-brokerota-updaterules-enginesmartcity
Fix WebSocket unsubscribe without event type or subscriptionId (#2774)
Wouter Born149440fb8c8c
diff --git a/manager/build.gradle b/manager/build.gradleindex 37c6b2e80..e401f37b5 100644--- a/manager/build.gradle+++ b/manager/build.gradle@@ -1,6 +1,7 @@import java.nio.file.Pathsapply plugin: "java-library"+apply plugin: "groovy"apply plugin: "application"apply plugin: "distribution"apply plugin: "maven-publish"@@ -53,6 +54,19 @@ dependencies {implementation "io.prometheus:prometheus-metrics-exporter-httpserver:$prometheusVersion"implementation "org.apache.sshd:sshd-netty:$apacheMINAVersion"++ testImplementation "org.apache.groovy:groovy-all:$groovyVersion"+ testImplementation platform("org.spockframework:spock-bom:$spockVersion")+ testImplementation "org.spockframework:spock-core"+ testImplementation "net.bytebuddy:byte-buddy:$byteBuddyVersion"+ testImplementation "net.bytebuddy:byte-buddy-agent:$byteBuddyVersion"+ testRuntimeOnly "org.objenesis:objenesis:$objenesisVersion"+}++sourceSets {+ test {+ groovy.srcDirs = ['test/src/groovy']+ }}base {diff --git a/manager/src/main/java/org/openremote/manager/event/ClientEventService.java b/manager/src/main/java/org/openremote/manager/event/ClientEventService.javaindex aa92013e0..15930128d 100644--- a/manager/src/main/java/org/openremote/manager/event/ClientEventService.java+++ b/manager/src/main/java/org/openremote/manager/event/ClientEventService.java@@ -34,7 +34,6 @@ import org.openremote.container.timer.TimerService;import org.openremote.manager.gateway.GatewayService;import org.openremote.manager.security.ManagerIdentityService;import org.openremote.manager.web.ManagerWebService;-import org.openremote.model.Constants;import org.openremote.model.Container;import org.openremote.model.ContainerService;import org.openremote.model.asset.AssetFilter;@@ -59,6 +58,7 @@ import java.util.concurrent.CopyOnWriteArraySet;import java.util.concurrent.ExecutorService;import java.util.concurrent.RejectedExecutionException;import java.util.function.Consumer;+import java.util.function.Predicate;import static jakarta.ws.rs.core.HttpHeaders.AUTHORIZATION;import static java.lang.System.Logger.Level.*;@@ -109,6 +109,7 @@ import static org.openremote.model.Constants.*;* </dl>*/public class ClientEventService extends RouteBuilder implements ContainerService {+/*** Holds state for each websocket session*/@@ -124,12 +125,24 @@ public class ClientEventService extends RouteBuilder implements ContainerServiceprotected static final System.Logger LOG = System.getLogger(ClientEventService.class.getName());protected static final String PUBLISH_QUEUE = "direct://ClientPublishQueue";- final protected Collection<EventSubscriptionAuthorizer> eventSubscriptionAuthorizers = new CopyOnWriteArraySet<>();- final protected Collection<EventAuthorizer> eventAuthorizers = new CopyOnWriteArraySet<>();- final protected Set<Pair<EventSubscription<? extends Event>, Consumer<? extends Event>>> eventSubscriptions = new CopyOnWriteArraySet<>();- final protected Map<String, WebSocketChannel> sessionChannels = new ConcurrentHashMap<>();- final protected Map<String, Map<String, Consumer<? extends Event>>> websocketSessionSubscriptionConsumers = new ConcurrentHashMap<>();- final protected Map<String, SessionDispatchState> sessionStates = new ConcurrentHashMap<>();+ /**+ * Delimiter used when composing the internal subscription key from {@code eventType} and {@code subscriptionId}.+ *+ * <p>The key format is: {@code <eventType>::<subscriptionId>}+ *+ * <p>This allows unsubscribe requests to match subscriptions even when the+ * client only provides one part of the original key, which is required for+ * websocket clients that unsubscribe using only the subscription id or only the event type.+ */+ protected static final String SUBSCRIPTION_KEY_DELIMITER = "::";++ protected final Collection<EventSubscriptionAuthorizer> eventSubscriptionAuthorizers = new CopyOnWriteArraySet<>();+ protected final Collection<EventAuthorizer> eventAuthorizers = new CopyOnWriteArraySet<>();+ protected final Set<Pair<EventSubscription<? extends Event>, Consumer<? extends Event>>> eventSubscriptions = new CopyOnWriteArraySet<>();+ protected final Map<String, WebSocketChannel> sessionChannels = new ConcurrentHashMap<>();+ protected final Map<String, Map<String, Consumer<? extends Event>>> websocketSessionSubscriptionConsumers = new ConcurrentHashMap<>();+ protected final Map<String, SessionDispatchState> sessionStates = new ConcurrentHashMap<>();+protected TimerService timerService;protected ExecutorService executorService;protected MessageBrokerService messageBrokerService;@@ -428,11 +441,20 @@ public class ClientEventService extends RouteBuilder implements ContainerService@SuppressWarnings({"unchecked", "rawtypes"})void procesInboundEvent(Exchange exchange) {WebSocketChannel webSocketChannel = exchange.getIn().getHeader(UndertowConstants.CHANNEL, WebSocketChannel.class);- AuthContext authContext = (AuthContext) webSocketChannel.getAttribute(AUTH_CONTEXT);- String realm = (String) webSocketChannel.getAttribute(REALM_PARAM_NAME);+ AuthContext authContext = exchange.getIn().getHeader(AUTH_CONTEXT, AuthContext.class);+ String realm = exchange.getIn().getHeader(REALM_PARAM_NAME, String.class);++ if (webSocketChannel != null) {+ if (authContext == null) {+ authContext = (AuthContext) webSocketChannel.getAttribute(AUTH_CONTEXT);+ }+ if (realm == null) {+ realm = (String) webSocketChannel.getAttribute(REALM_PARAM_NAME);+ }+ }- exchange.getIn().setHeader(AUTH_CONTEXT, authContext);- exchange.getIn().setHeader(REALM_PARAM_NAME, realm);+ exchange.getIn().setHeader(AUTH_CONTEXT, authContext);+ exchange.getIn().setHeader(REALM_PARAM_NAME, realm);// Pass to gateway interceptor and abort if it stops the exchangeif (gatewayInterceptor != null) {@@ -459,6 +481,12 @@ public class ClientEventService extends RouteBuilder implements ContainerServicereturn;}+ if (subscription.getEventType().contains(SUBSCRIPTION_KEY_DELIMITER) || subscription.getSubscriptionId().contains(SUBSCRIPTION_KEY_DELIMITER)) {+ sendToWebsocketSession(sessionKey, new UnauthorizedEventSubscription<>(subscription));+ exchange.setRouteStop(true);+ return;+ }+// Force subscription to filter only value changed attribute eventsif (subscription.getFilter() instanceof AssetFilter assetFilter) {subscription.setFilter(assetFilter.setValueChanged(true));@@ -475,7 +503,7 @@ public class ClientEventService extends RouteBuilder implements ContainerServiceconsumers = new HashMap<>();}- String subscriptionKey = subscription.getEventType() + subscription.getSubscriptionId();+ String subscriptionKey = subscription.getEventType() + SUBSCRIPTION_KEY_DELIMITER + subscription.getSubscriptionId();consumers.put(subscriptionKey, consumer);addSubscription(subscription, consumer);return consumers;@@ -485,10 +513,25 @@ public class ClientEventService extends RouteBuilder implements ContainerServiceString sessionKey = getSessionKey(exchange);LOG.log(TRACE, () -> "Cancelling subscription for session '" + sessionKey + "': " + cancelEventSubscription);websocketSessionSubscriptionConsumers.computeIfPresent(sessionKey, (s, subscriptionConsumers) -> {- String subscriptionKey = cancelEventSubscription.getEventType() + cancelEventSubscription.getSubscriptionId();- Consumer<? extends Event> consumer = subscriptionConsumers.remove(subscriptionKey);- if (consumer != null) {- removeSubscription(consumer);+ Predicate<String> predicate = null;+ if (!cancelEventSubscription.getEventType().isEmpty() && !cancelEventSubscription.getSubscriptionId().isEmpty()) {+ predicate = key -> key.equals(cancelEventSubscription.getEventType() + SUBSCRIPTION_KEY_DELIMITER + cancelEventSubscription.getSubscriptionId());+ } else {+ if (!cancelEventSubscription.getSubscriptionId().isEmpty()) {+ predicate = key -> key.endsWith(SUBSCRIPTION_KEY_DELIMITER + cancelEventSubscription.getSubscriptionId());+ } else if (!cancelEventSubscription.getEventType().isEmpty()) {+ predicate = key -> key.startsWith(cancelEventSubscription.getEventType() + SUBSCRIPTION_KEY_DELIMITER);+ }+ }+ if (predicate != null) {+ final Predicate<String> finalPredicate = predicate;+ subscriptionConsumers.keySet().removeIf(key -> {+ if (finalPredicate.test(key)) {+ removeSubscription(subscriptionConsumers.get(key));+ return true;+ }+ return false;+ });}if (subscriptionConsumers.isEmpty()) {return null;diff --git a/manager/test/src/groovy/org/openremote/manager/event/ClientEventServiceSubscriptionTest.groovy b/manager/test/src/groovy/org/openremote/manager/event/ClientEventServiceSubscriptionTest.groovynew file mode 100644index 000000000..b7684043c--- /dev/null+++ b/manager/test/src/groovy/org/openremote/manager/event/ClientEventServiceSubscriptionTest.groovy@@ -0,0 +1,169 @@+/*+ * Copyright 2026, OpenRemote Inc.+ *+ * See the CONTRIBUTORS.txt file in the distribution for a+ * full listing of individual contributors.+ *+ * This program is free software: you can redistribute it and/or modify+ * it under the terms of the GNU Affero General Public License as+ * published by the Free Software Foundation, either version 3 of the+ * License, or (at your option) any later version.+ *+ * This program is distributed in the hope that it will be useful,+ * but WITHOUT ANY WARRANTY; without even the implied warranty of+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ * GNU Affero General Public License for more details.+ *+ * You should have received a copy of the GNU Affero General Public License+ * along with this program. If not, see <http://www.gnu.org/licenses/>.+ */+package org.openremote.manager.event++import io.undertow.websockets.core.WebSocketChannel+import org.apache.camel.Exchange+import org.apache.camel.component.undertow.UndertowConstants+import org.apache.camel.impl.DefaultCamelContext+import org.apache.camel.support.DefaultExchange+import org.openremote.container.security.AuthContext+import org.openremote.model.event.Event+import org.openremote.model.event.shared.CancelEventSubscription+import org.openremote.model.event.shared.EventSubscription+import org.openremote.model.event.shared.UnauthorizedEventSubscription+import org.openremote.model.alarm.AlarmEvent+import org.openremote.model.syslog.SyslogEvent+import spock.lang.Specification+import spock.lang.Unroll++import static org.openremote.model.Constants.AUTH_CONTEXT+import static org.openremote.model.Constants.REALM_PARAM_NAME++class ClientEventServiceSubscriptionTest extends Specification {++ def "subscribes and unsubscribes by event type and subscription id"() {+ given:+ def service = new TestClientEventService()+ def channel = dummyChannel()+ String sessionKey = "session-1"+ service.sessionChannels.put(sessionKey, channel)++ and:+ def subscription = new EventSubscription<>(SyslogEvent.class, null, "sub-1")++ when: "subscribing"+ service.procesInboundEvent(exchangeFor(sessionKey, channel, subscription))++ then:+ service.websocketSessionSubscriptionConsumers[sessionKey].size() == 1+ service.eventSubscriptions.size() == 1+ service.sentPayloads.last().is(subscription)++ when: "unsubscribing with event type + subscription id"+ service.procesInboundEvent(exchangeFor(sessionKey, channel, new CancelEventSubscription(SyslogEvent.class, "sub-1")))++ then:+ !service.websocketSessionSubscriptionConsumers.containsKey(sessionKey)+ service.eventSubscriptions.empty+ }++ def "unsubscribes all matching subscriptions when only event type is provided"() {+ given:+ def service = new TestClientEventService()+ def channel = dummyChannel()+ String sessionKey = "session-2"+ service.sessionChannels.put(sessionKey, channel)++ and:+ service.procesInboundEvent(exchangeFor(sessionKey, channel, new EventSubscription<>(SyslogEvent.class, null, "sub-a")))+ service.procesInboundEvent(exchangeFor(sessionKey, channel, new EventSubscription<>(SyslogEvent.class, null, "sub-b")))+ service.procesInboundEvent(exchangeFor(sessionKey, channel, new EventSubscription<>(AlarmEvent.class)))++ expect:+ service.websocketSessionSubscriptionConsumers[sessionKey].size() == 3++ when:+ service.procesInboundEvent(exchangeFor(sessionKey, channel, new CancelEventSubscription(Event.getEventType(SyslogEvent.class), null)))++ then:+ service.websocketSessionSubscriptionConsumers[sessionKey].size() == 1+ service.websocketSessionSubscriptionConsumers[sessionKey].keySet() == ["alarm::"] as Set+ service.eventSubscriptions.size() == 1+ }++ def "unsubscribes all matching subscriptions when only subscription id is provided"() {+ given:+ def service = new TestClientEventService()+ def channel = dummyChannel()+ String sessionKey = "session-3"+ service.sessionChannels.put(sessionKey, channel)++ and:+ service.procesInboundEvent(exchangeFor(sessionKey, channel, new EventSubscription<>(SyslogEvent.class, null, "shared-id")))+ service.procesInboundEvent(exchangeFor(sessionKey, channel, new EventSubscription<>(AlarmEvent.class, null, "shared-id")))+ service.procesInboundEvent(exchangeFor(sessionKey, channel, new EventSubscription<>(AlarmEvent.class)))++ expect:+ service.websocketSessionSubscriptionConsumers[sessionKey].size() == 3++ when:+ service.procesInboundEvent(exchangeFor(sessionKey, channel, new CancelEventSubscription("shared-id")))++ then:+ service.websocketSessionSubscriptionConsumers[sessionKey].size() == 1+ service.websocketSessionSubscriptionConsumers[sessionKey].keySet() == ["alarm::"] as Set+ service.eventSubscriptions.size() == 1+ }++ @Unroll+ def "rejects subscription when delimiter is present in #fieldName"() {+ given:+ def service = new TestClientEventService()+ def channel = dummyChannel()+ String sessionKey = "session-4"+ service.sessionChannels.put(sessionKey, channel)++ when:+ def exchange = exchangeFor(sessionKey, channel, subscription)+ service.procesInboundEvent(exchange)++ then:+ exchange.routeStop+ !service.websocketSessionSubscriptionConsumers.containsKey(sessionKey)+ service.eventSubscriptions.empty+ service.sentPayloads.size() == 1+ service.sentPayloads[0] instanceof UnauthorizedEventSubscription++ where:+ fieldName | subscription+ "eventType" | new EventSubscription<>("bad::event")+ "subscriptionId" | new EventSubscription<>(SyslogEvent.class, null, "bad::id")+ }++ private Exchange exchangeFor(String sessionKey, WebSocketChannel channel, Object body) {+ Exchange exchange = new DefaultExchange(new DefaultCamelContext())+ exchange.in.body = body+ exchange.in.setHeader(UndertowConstants.CONNECTION_KEY, sessionKey)+ exchange.in.setHeader(UndertowConstants.CHANNEL, channel)+ exchange.in.setHeader(AUTH_CONTEXT, Stub(AuthContext))+ exchange.in.setHeader(REALM_PARAM_NAME, "master")+ exchange+ }++ private WebSocketChannel dummyChannel() {+ Stub(WebSocketChannel)+ }++ private static class TestClientEventService extends ClientEventService {+ final List<Object> sentPayloads = []++ @Override+ boolean authorizeEventSubscription(String realm, AuthContext authContext, EventSubscription<?> subscription) {+ return true+ }++ @Override+ void sendToWebsocketSession(String sessionKey, Object data) {+ sentPayloads.add(data)+ }+ }+}+diff --git a/model/src/main/java/org/openremote/model/event/shared/EventSubscription.java b/model/src/main/java/org/openremote/model/event/shared/EventSubscription.javaindex 3aeafadd8..c97d5d8d3 100644--- a/model/src/main/java/org/openremote/model/event/shared/EventSubscription.java+++ b/model/src/main/java/org/openremote/model/event/shared/EventSubscription.java@@ -35,9 +35,22 @@ public class EventSubscription<E extends Event> {public static final String SUBSCRIBE_MESSAGE_PREFIX = "SUBSCRIBE:";public static final String SUBSCRIBED_MESSAGE_PREFIX = "SUBSCRIBED:";+ /**+ * Event type of the subscription to cancel.+ *+ * <p>Must not contain the reserved delimiter {@code "::"}.+ */protected String eventType;+protected EventFilter<E> filter;++ /**+ * Client-defined subscription identifier.+ *+ * <p>Must not contain the reserved delimiter {@code "::"}.+ */protected String subscriptionId;+@JsonIgnoreprotected boolean subscribed;