From 464dc4b09db12c20005e0226fa93ec128432cea4 Mon Sep 17 00:00:00 2001 From: Rich Turner <7072278+richturner@users.noreply.github.com> Date: Wed, 2 Dec 2026 12:00:47 +0000 Subject: [PATCH 1/5] Revert provisioning MQTT topic back to `provisioning` Restores the original `provisioning` topic token changed in #3590. Custom projects that need the old mechanism on this topic can instead replace the built-in handler. The X.509 challenge prefix change from #3590 is kept. --- .../UserAssetProvisioningMQTTHandler.java | 2 +- .../mqtt/X509ProvisioningProofTest.groovy | 48 +++++++++---------- 2 files changed, 25 insertions(+), 25 deletions(-) diff --git a/manager/src/main/java/org/openremote/manager/mqtt/UserAssetProvisioningMQTTHandler.java b/manager/src/main/java/org/openremote/manager/mqtt/UserAssetProvisioningMQTTHandler.java index fe8aceb7e5..7aedc12d5a 100644 --- a/manager/src/main/java/org/openremote/manager/mqtt/UserAssetProvisioningMQTTHandler.java +++ b/manager/src/main/java/org/openremote/manager/mqtt/UserAssetProvisioningMQTTHandler.java @@ -164,7 +164,7 @@ public void configure() throws Exception { protected static final Logger LOG = SyslogCategory.getLogger(API, UserAssetProvisioningMQTTHandler.class); - public static final String PROVISIONING_TOKEN = "provisioningv2"; + public static final String PROVISIONING_TOKEN = "provisioning"; public static final String REQUEST_TOKEN = "request"; public static final String RESPONSE_TOKEN = "response"; public static final String UNIQUE_ID_PLACEHOLDER = "%UNIQUE_ID%"; diff --git a/manager/test/src/groovy/org/openremote/manager/mqtt/X509ProvisioningProofTest.groovy b/manager/test/src/groovy/org/openremote/manager/mqtt/X509ProvisioningProofTest.groovy index 2801578e1c..6240877a32 100644 --- a/manager/test/src/groovy/org/openremote/manager/mqtt/X509ProvisioningProofTest.groovy +++ b/manager/test/src/groovy/org/openremote/manager/mqtt/X509ProvisioningProofTest.groovy @@ -50,14 +50,14 @@ class X509ProvisioningProofTest extends Specification { isOpen() >> true } } - def topic = Topic.parse("provisioningv2/device1/request") + def topic = Topic.parse("provisioning/device1/request") def keyPair = KeyPairGenerator.getInstance("RSA").generateKeyPair() def certificate = certificateFor(keyPair) def setup() { handler.isKeycloak = true - assert handler.canSubscribe(connection, null, Topic.parse("provisioningv2/device1/response")) - handler.onSubscribe(connection, Topic.parse("provisioningv2/device1/response")) + assert handler.canSubscribe(connection, null, Topic.parse("provisioning/device1/response")) + handler.onSubscribe(connection, Topic.parse("provisioning/device1/response")) } def "a valid #keyAlgorithm proof succeeds exactly once"() { @@ -105,7 +105,7 @@ class X509ProvisioningProofTest extends Specification { def otherCertificate = certificateFor(KeyPairGenerator.getInstance("RSA").generateKeyPair()) expect: - !handler.verifyX509Proof(connection, Topic.parse("provisioningv2/device2/request"), certificate, signature) + !handler.verifyX509Proof(connection, Topic.parse("provisioning/device2/request"), certificate, signature) when: handler.issueX509Challenge(connection, topic, certificate) @@ -164,7 +164,7 @@ class X509ProvisioningProofTest extends Specification { and: "nobody else may, so an attacker cannot inject errors into the device's exchange" !handler.canPublish(attacker, null, topic) - !handler.canPublish(connection, null, Topic.parse("provisioningv2/device2/request")) + !handler.canPublish(connection, null, Topic.parse("provisioning/device2/request")) handler.messages.isEmpty() } @@ -175,19 +175,19 @@ class X509ProvisioningProofTest extends Specification { isOpen() >> true } } - def unsubscribed = Topic.parse("provisioningv2/device2/request") + def unsubscribed = Topic.parse("provisioning/device2/request") expect: !handler.canPublish(device2, null, unsubscribed) when: - handler.canSubscribe(device2, null, Topic.parse("provisioningv2/device2/response")) + handler.canSubscribe(device2, null, Topic.parse("provisioning/device2/response")) then: handler.canPublish(device2, null, unsubscribed) when: - handler.onUnsubscribe(device2, Topic.parse("provisioningv2/device2/response")) + handler.onUnsubscribe(device2, Topic.parse("provisioning/device2/response")) then: !handler.canPublish(device2, null, unsubscribed) @@ -195,8 +195,8 @@ class X509ProvisioningProofTest extends Specification { def "a connection can own only one response topic"() { given: - def device1Response = Topic.parse("provisioningv2/device1/response") - def device2Response = Topic.parse("provisioningv2/device2/response") + def device1Response = Topic.parse("provisioning/device1/response") + def device2Response = Topic.parse("provisioning/device2/response") expect: "re-authorizing the topic it already owns is allowed" handler.canSubscribe(connection, null, device1Response) @@ -224,10 +224,10 @@ class X509ProvisioningProofTest extends Specification { } expect: "another connection cannot take the owned topic" - !handler.canSubscribe(other, null, Topic.parse("provisioningv2/device1/response")) + !handler.canSubscribe(other, null, Topic.parse("provisioning/device1/response")) and: "but can still claim a free one" - handler.canSubscribe(other, null, Topic.parse("provisioningv2/device2/response")) + handler.canSubscribe(other, null, Topic.parse("provisioning/device2/response")) } def "only the response subscriber can obtain a challenge"() { @@ -245,8 +245,8 @@ class X509ProvisioningProofTest extends Specification { def "a message processed after its connection lost the response topic is dropped silently"() { given: "the topic changes hands after the message was authorized but before it is processed" def newOwner = openConnection() - handler.onUnsubscribe(connection, Topic.parse("provisioningv2/device1/response")) - assert handler.canSubscribe(newOwner, null, Topic.parse("provisioningv2/device1/response")) + handler.onUnsubscribe(connection, Topic.parse("provisioning/device1/response")) + assert handler.canSubscribe(newOwner, null, Topic.parse("provisioning/device1/response")) when: handler.processX509ProvisioningMessage(connection, topic, cert, signature, challengeRequest) @@ -266,10 +266,10 @@ class X509ProvisioningProofTest extends Specification { given: handler.issueX509Challenge(connection, topic, certificate) def signature = sign(handler.messages.last(), keyPair) - handler.onUnsubscribe(connection, Topic.parse("provisioningv2/device1/response")) + handler.onUnsubscribe(connection, Topic.parse("provisioning/device1/response")) def otherConnection = Stub(RemotingConnection) - assert handler.canSubscribe(otherConnection, null, Topic.parse("provisioningv2/device1/response")) - handler.onSubscribe(otherConnection, Topic.parse("provisioningv2/device1/response")) + assert handler.canSubscribe(otherConnection, null, Topic.parse("provisioning/device1/response")) + handler.onSubscribe(otherConnection, Topic.parse("provisioning/device1/response")) expect: !handler.verifyX509Proof(connection, topic, certificate, signature) @@ -305,18 +305,18 @@ class X509ProvisioningProofTest extends Specification { handler.onDisconnect(closing) expect: "the late subscribe is refused and no claim survives" - !handler.canSubscribe(closing, null, Topic.parse("provisioningv2/device2/response")) - !handler.responseTopicOwners.containsKey("provisioningv2/device2/response") + !handler.canSubscribe(closing, null, Topic.parse("provisioning/device2/response")) + !handler.responseTopicOwners.containsKey("provisioning/device2/response") !handler.connectionResponseTopics.containsKey(closing) and: "the topic stays free for the real device" - handler.canSubscribe(realDevice, null, Topic.parse("provisioningv2/device2/response")) + handler.canSubscribe(realDevice, null, Topic.parse("provisioning/device2/response")) } def "concurrent subscribe and disconnect never leak a claim"() { given: def executor = Executors.newFixedThreadPool(2) - def responseTopic = Topic.parse("provisioningv2/device2/response") + def responseTopic = Topic.parse("provisioning/device2/response") when: "a subscribe and the disconnect cleanup of the same connection race many times" def leaks = (1..500).count { @@ -369,7 +369,7 @@ class X509ProvisioningProofTest extends Specification { getTransportConnection() >> transport } } - def responseTopic = Topic.parse("provisioningv2/device2/response") + def responseTopic = Topic.parse("provisioning/device2/response") def executor = Executors.newFixedThreadPool(2) when: @@ -383,8 +383,8 @@ class X509ProvisioningProofTest extends Specification { handler.responseTopicOwners[responseTopic.toString()].is(connections[results.indexOf(true)]) and: "only the winner may publish the matching request topic" - handler.canPublish(connections[results.indexOf(true)], null, Topic.parse("provisioningv2/device2/request")) - !handler.canPublish(connections[results.indexOf(false)], null, Topic.parse("provisioningv2/device2/request")) + handler.canPublish(connections[results.indexOf(true)], null, Topic.parse("provisioning/device2/request")) + !handler.canPublish(connections[results.indexOf(false)], null, Topic.parse("provisioning/device2/request")) cleanup: executor.shutdownNow() From 3970a27a6f9a50a6f76bf2f9de250a24aabd4c9b Mon Sep 17 00:00:00 2001 From: Rich Turner <7072278+richturner@users.noreply.github.com> Date: Wed, 2 Dec 2026 12:02:33 +0000 Subject: [PATCH 2/5] Allow custom MQTT handlers to replace built-in handlers Adds `MQTTHandler.getReplacedHandlers()` so a custom project can take over the topic of a built-in handler (e.g. `UserAssetProvisioningMQTTHandler`). A handler that extends another loaded handler replaces it implicitly. Replaced handlers are discarded on load, so they are never initialized or started and never consume messages; ordering by priority alone was not enough because every handler receives published messages on its topics. --- .../manager/mqtt/MQTTBrokerService.java | 34 +++++++++++++++++-- .../openremote/manager/mqtt/MQTTHandler.java | 10 ++++++ 2 files changed, 42 insertions(+), 2 deletions(-) diff --git a/manager/src/main/java/org/openremote/manager/mqtt/MQTTBrokerService.java b/manager/src/main/java/org/openremote/manager/mqtt/MQTTBrokerService.java index 94e38a6a2f..01f6de23c1 100644 --- a/manager/src/main/java/org/openremote/manager/mqtt/MQTTBrokerService.java +++ b/manager/src/main/java/org/openremote/manager/mqtt/MQTTBrokerService.java @@ -274,9 +274,12 @@ public MeterRegistry getRegistry() { serverConfiguration.setAuthenticationCacheSize(0); serverConfiguration.setAuthorizationCacheSize(0); - // Load custom handlers + // Load custom handlers, discarding any that have been replaced by another handler + List loadedHandlers = + stream(ServiceLoader.load(MQTTHandler.class).spliterator(), false).toList(); this.customHandlers = - stream(ServiceLoader.load(MQTTHandler.class).spliterator(), false) + loadedHandlers.stream() + .filter(handler -> !isHandlerReplaced(handler, loadedHandlers)) .sorted(Comparator.comparingInt(MQTTHandler::getPriority)) .collect(Collectors.toList()); @@ -588,6 +591,33 @@ public void onUnsubscribe(RemotingConnection connection, String topicStr) { } } + /** + * A handler is replaced when another loaded handler declares it in {@link + * MQTTHandler#getReplacedHandlers} or extends it. + */ + protected static boolean isHandlerReplaced(MQTTHandler handler, List handlers) { + Class handlerClass = handler.getClass(); + return handlers.stream() + .filter(other -> other.getClass() != handlerClass) + .filter( + other -> + other.getReplacedHandlers().contains(handlerClass) + || handlerClass.isAssignableFrom(other.getClass())) + .findFirst() + .map( + replacement -> { + LOG.log( + INFO, + "MQTT handler '" + + handler.getName() + + "' replaced by '" + + replacement.getName() + + "'"); + return true; + }) + .orElse(false); + } + public Iterable getCustomHandlers() { return customHandlers; } diff --git a/manager/src/main/java/org/openremote/manager/mqtt/MQTTHandler.java b/manager/src/main/java/org/openremote/manager/mqtt/MQTTHandler.java index 4bcf0be75d..1f46a33c3e 100644 --- a/manager/src/main/java/org/openremote/manager/mqtt/MQTTHandler.java +++ b/manager/src/main/java/org/openremote/manager/mqtt/MQTTHandler.java @@ -81,6 +81,16 @@ public int getPriority() { return 0; } + /** + * Gets the handlers that this handler replaces, allowing a custom project to take over a topic + * of a built-in handler. Replaced handlers are discarded when the handlers are loaded, so they are + * never initialized or started and never consume any messages. A handler that extends another + * loaded handler replaces it implicitly, so it does not need to declare it here. + */ + public Set> getReplacedHandlers() { + return Set.of(); + } + /** Provides a name to identify this custom handler for logging purposes etc. */ public String getName() { return this.getClass().getSimpleName(); From 26138ae31e32f5aa958b6d527b3ee0fc3a663c2b Mon Sep 17 00:00:00 2001 From: Rich Turner <7072278+richturner@users.noreply.github.com> Date: Wed, 2 Dec 2026 12:03:01 +0000 Subject: [PATCH 3/5] Stop the running MQTT handlers in MQTTBrokerService.stop() stop() reloaded the handlers via ServiceLoader, so it stopped new instances that were never initialized instead of the running ones, and ignored replaced handlers. It now stops the loaded handlers in reverse priority order. --- .../java/org/openremote/manager/mqtt/MQTTBrokerService.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/manager/src/main/java/org/openremote/manager/mqtt/MQTTBrokerService.java b/manager/src/main/java/org/openremote/manager/mqtt/MQTTBrokerService.java index 01f6de23c1..c4d67f2add 100644 --- a/manager/src/main/java/org/openremote/manager/mqtt/MQTTBrokerService.java +++ b/manager/src/main/java/org/openremote/manager/mqtt/MQTTBrokerService.java @@ -458,8 +458,8 @@ public void stop(Container container) throws Exception { server.stop(); LOG.log(DEBUG, "Stopped MQTT broker"); - stream(ServiceLoader.load(MQTTHandler.class).spliterator(), false) - .sorted(Comparator.comparingInt(MQTTHandler::getPriority).reversed()) + // Stop the running handlers in reverse order (customHandlers is already sorted by priority) + customHandlers.reversed() .forEach( handler -> { try { From a551e25a0b286b05864417eca9fd72588467007d Mon Sep 17 00:00:00 2001 From: Rich Turner <7072278+richturner@users.noreply.github.com> Date: Wed, 2 Dec 2026 14:33:08 +0000 Subject: [PATCH 4/5] SpotlessApply --- .../java/org/openremote/manager/mqtt/MQTTBrokerService.java | 3 ++- .../main/java/org/openremote/manager/mqtt/MQTTHandler.java | 4 ++-- 2 files changed, 4 insertions(+), 3 deletions(-) diff --git a/manager/src/main/java/org/openremote/manager/mqtt/MQTTBrokerService.java b/manager/src/main/java/org/openremote/manager/mqtt/MQTTBrokerService.java index c4d67f2add..671591cc72 100644 --- a/manager/src/main/java/org/openremote/manager/mqtt/MQTTBrokerService.java +++ b/manager/src/main/java/org/openremote/manager/mqtt/MQTTBrokerService.java @@ -459,7 +459,8 @@ public void stop(Container container) throws Exception { LOG.log(DEBUG, "Stopped MQTT broker"); // Stop the running handlers in reverse order (customHandlers is already sorted by priority) - customHandlers.reversed() + customHandlers + .reversed() .forEach( handler -> { try { diff --git a/manager/src/main/java/org/openremote/manager/mqtt/MQTTHandler.java b/manager/src/main/java/org/openremote/manager/mqtt/MQTTHandler.java index 1f46a33c3e..8a1d3b261b 100644 --- a/manager/src/main/java/org/openremote/manager/mqtt/MQTTHandler.java +++ b/manager/src/main/java/org/openremote/manager/mqtt/MQTTHandler.java @@ -82,8 +82,8 @@ public int getPriority() { } /** - * Gets the handlers that this handler replaces, allowing a custom project to take over a topic - * of a built-in handler. Replaced handlers are discarded when the handlers are loaded, so they are + * Gets the handlers that this handler replaces, allowing a custom project to take over a topic of + * a built-in handler. Replaced handlers are discarded when the handlers are loaded, so they are * never initialized or started and never consume any messages. A handler that extends another * loaded handler replaces it implicitly, so it does not need to declare it here. */ From 74027199a7ab9d5b364b8187e53411405fa0d014 Mon Sep 17 00:00:00 2001 From: Rich Turner <7072278+richturner@users.noreply.github.com> Date: Thu, 3 Dec 2026 09:23:36 +0000 Subject: [PATCH 5/5] Apply review changes --- .../manager/mqtt/MQTTBrokerService.java | 134 +++++++++--- .../openremote/manager/mqtt/MQTTHandler.java | 6 +- .../mqtt/MQTTHandlerReplacementTest.groovy | 190 ++++++++++++++++++ ...9ProvisioningChallengeResponseMessage.java | 2 +- 4 files changed, 299 insertions(+), 33 deletions(-) create mode 100644 manager/src/test/groovy/org/openremote/manager/mqtt/MQTTHandlerReplacementTest.groovy diff --git a/manager/src/main/java/org/openremote/manager/mqtt/MQTTBrokerService.java b/manager/src/main/java/org/openremote/manager/mqtt/MQTTBrokerService.java index 671591cc72..e2d81c43ef 100644 --- a/manager/src/main/java/org/openremote/manager/mqtt/MQTTBrokerService.java +++ b/manager/src/main/java/org/openremote/manager/mqtt/MQTTBrokerService.java @@ -275,15 +275,15 @@ public MeterRegistry getRegistry() { serverConfiguration.setAuthorizationCacheSize(0); // Load custom handlers, discarding any that have been replaced by another handler - List loadedHandlers = - stream(ServiceLoader.load(MQTTHandler.class).spliterator(), false).toList(); this.customHandlers = - loadedHandlers.stream() - .filter(handler -> !isHandlerReplaced(handler, loadedHandlers)) - .sorted(Comparator.comparingInt(MQTTHandler::getPriority)) - .collect(Collectors.toList()); + selectHandlers(stream(ServiceLoader.load(MQTTHandler.class).spliterator(), false).toList()); - // Init each custom handler + initHandlers(container, serverConfiguration); + } + + /** Initializes the selected handlers in priority order. */ + protected void initHandlers(Container container, Configuration serverConfiguration) + throws Exception { for (MQTTHandler handler : customHandlers) { try { handler.init(container, serverConfiguration); @@ -364,7 +364,11 @@ public void start(Container container) throws Exception { serverLocator = ActiveMQClient.createServerLocator("vm://0").setProducerWindowSize(-1); sessionFactory = serverLocator.createSessionFactory(); - // Start each custom handler + startHandlers(container); + } + + /** Starts the selected handlers in priority order. */ + protected void startHandlers(Container container) throws Exception { for (MQTTHandler handler : customHandlers) { try { handler.start(container); @@ -458,7 +462,14 @@ public void stop(Container container) throws Exception { server.stop(); LOG.log(DEBUG, "Stopped MQTT broker"); - // Stop the running handlers in reverse order (customHandlers is already sorted by priority) + stopHandlers(); + } + + /** + * Stops the selected handlers in reverse priority order; an exception from one handler is logged + * and does not prevent the others from stopping. + */ + protected void stopHandlers() { customHandlers .reversed() .forEach( @@ -593,30 +604,93 @@ public void onUnsubscribe(RemotingConnection connection, String topicStr) { } /** - * A handler is replaced when another loaded handler declares it in {@link - * MQTTHandler#getReplacedHandlers} or extends it. + * Selects the handlers to run from those loaded, sorted by priority. A handler is discarded when + * another loaded handler declares its class in {@link MQTTHandler#getReplacedHandlers}; extending + * a handler does not replace it. A handler declaring its own class is ignored. + * + * @throws IllegalStateException if the replacement declarations form a cycle, as no handler in + * the cycle could otherwise run */ - protected static boolean isHandlerReplaced(MQTTHandler handler, List handlers) { - Class handlerClass = handler.getClass(); - return handlers.stream() - .filter(other -> other.getClass() != handlerClass) + protected static List selectHandlers(List loadedHandlers) { + Map, List>> replacements = + new LinkedHashMap<>(); + for (MQTTHandler handler : loadedHandlers) { + replacements.putIfAbsent(handler.getClass(), new ArrayList<>()); + } + for (MQTTHandler handler : loadedHandlers) { + for (Class replaced : handler.getReplacedHandlers()) { + if (replaced != handler.getClass() && replacements.containsKey(replaced)) { + replacements.get(handler.getClass()).add(replaced); + } + } + } + + throwIfReplacementCycle(replacements); + + Map, MQTTHandler> replacedBy = new HashMap<>(); + for (MQTTHandler handler : loadedHandlers) { + for (Class replaced : replacements.get(handler.getClass())) { + replacedBy.putIfAbsent(replaced, handler); + } + } + + return loadedHandlers.stream() .filter( - other -> - other.getReplacedHandlers().contains(handlerClass) - || handlerClass.isAssignableFrom(other.getClass())) - .findFirst() - .map( - replacement -> { - LOG.log( - INFO, - "MQTT handler '" - + handler.getName() - + "' replaced by '" - + replacement.getName() - + "'"); - return true; + handler -> { + MQTTHandler replacement = replacedBy.get(handler.getClass()); + if (replacement != null) { + LOG.log( + INFO, + "MQTT handler '" + + handler.getName() + + "' replaced by '" + + replacement.getName() + + "'"); + } + return replacement == null; }) - .orElse(false); + .sorted(Comparator.comparingInt(MQTTHandler::getPriority)) + .collect(Collectors.toList()); + } + + protected static void throwIfReplacementCycle( + Map, List>> replacements) { + Set> visited = new HashSet<>(); + for (Class start : replacements.keySet()) { + findReplacementCycle(start, replacements, visited, new ArrayList<>()) + .ifPresent( + cycle -> { + throw new IllegalStateException( + "MQTT handlers declare a replacement cycle, so none of them could run: " + + cycle.stream().map(Class::getName).collect(Collectors.joining(" -> "))); + }); + } + } + + private static Optional>> findReplacementCycle( + Class current, + Map, List>> replacements, + Set> visited, + List> path) { + int index = path.indexOf(current); + if (index >= 0) { + List> cycle = new ArrayList<>(path.subList(index, path.size())); + cycle.add(current); + return Optional.of(cycle); + } + if (!visited.add(current)) { + return Optional.empty(); + } + path.add(current); + for (Class replaced : replacements.get(current)) { + Optional>> cycle = + findReplacementCycle(replaced, replacements, visited, path); + if (cycle.isPresent()) { + return cycle; + } + } + path.remove(path.size() - 1); + return Optional.empty(); } public Iterable getCustomHandlers() { diff --git a/manager/src/main/java/org/openremote/manager/mqtt/MQTTHandler.java b/manager/src/main/java/org/openremote/manager/mqtt/MQTTHandler.java index 8a1d3b261b..e8d057b70c 100644 --- a/manager/src/main/java/org/openremote/manager/mqtt/MQTTHandler.java +++ b/manager/src/main/java/org/openremote/manager/mqtt/MQTTHandler.java @@ -84,8 +84,10 @@ public int getPriority() { /** * Gets the handlers that this handler replaces, allowing a custom project to take over a topic of * a built-in handler. Replaced handlers are discarded when the handlers are loaded, so they are - * never initialized or started and never consume any messages. A handler that extends another - * loaded handler replaces it implicitly, so it does not need to declare it here. + * never initialized or started and never consume any messages. Replacement must be declared here: + * extending a handler does not replace it, so a subclass serving another topic can run alongside + * its parent. Handlers that replace each other, directly or through others, stop the broker from + * initializing. */ public Set> getReplacedHandlers() { return Set.of(); diff --git a/manager/src/test/groovy/org/openremote/manager/mqtt/MQTTHandlerReplacementTest.groovy b/manager/src/test/groovy/org/openremote/manager/mqtt/MQTTHandlerReplacementTest.groovy new file mode 100644 index 0000000000..54e0e29b53 --- /dev/null +++ b/manager/src/test/groovy/org/openremote/manager/mqtt/MQTTHandlerReplacementTest.groovy @@ -0,0 +1,190 @@ +/* + * Copyright 2026, OpenRemote Inc. + * + * 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 . + * + * SPDX-License-Identifier: AGPL-3.0-or-later + */ +package org.openremote.manager.mqtt + +import io.netty.buffer.ByteBuf +import org.apache.activemq.artemis.core.config.Configuration +import org.apache.activemq.artemis.spi.core.protocol.RemotingConnection +import org.openremote.container.security.AuthContext +import org.openremote.model.Container +import org.openremote.model.protocol.mqtt.Topic +import spock.lang.Specification + +import java.util.logging.Logger + +class MQTTHandlerReplacementTest extends Specification { + + def "only the selected handlers are initialized and started, and the same instances stop once in reverse order"() { + given: "a built-in handler, a replacement for it and an unrelated peer" + def events = [] + def builtIn = new BuiltInHandler(events: events) + def replacement = new ReplacementHandler(events: events) + def peer = new PeerHandler(events: events) + def broker = new MQTTBrokerService() + def container = Stub(Container) + def configuration = Stub(Configuration) + + when: "the handlers are selected and taken through their lifecycle" + broker.customHandlers = MQTTBrokerService.selectHandlers([builtIn, peer, replacement]) + broker.initHandlers(container, configuration) + broker.startHandlers(container) + broker.stopHandlers() + + then: "the replaced handler is discarded and the others run in priority order" + broker.customHandlers == [replacement, peer] + + and: "only the selected instances receive lifecycle callbacks, stopping once in reverse order" + events == [ + [replacement, "init"], + [peer, "init"], + [replacement, "start"], + [peer, "start"], + [peer, "stop"], + [replacement, "stop"] + ] + } + + def "a handler that extends another without declaring it runs alongside its parent"() { + given: + def parent = new BuiltInHandler(events: []) + def subclass = new BuiltInSubclassHandler(events: []) + + expect: + MQTTBrokerService.selectHandlers([parent, subclass]) as Set == [parent, subclass] as Set + } + + def "a handler declaring its own class is not discarded"() { + given: + def handler = new SelfReplacingHandler(events: []) + + expect: + MQTTBrokerService.selectHandlers([handler]) == [handler] + } + + def "a replacement cycle is rejected naming the participating handlers"() { + when: + MQTTBrokerService.selectHandlers([new CycleAHandler(events: []), new CycleBHandler(events: []), new PeerHandler(events: [])]) + + then: + IllegalStateException ex = thrown() + ex.message.contains(CycleAHandler.name) + ex.message.contains(CycleBHandler.name) + !ex.message.contains(PeerHandler.name) + } + + def "a declared replacement that is not loaded is ignored"() { + given: + def replacement = new ReplacementHandler(events: []) + + expect: + MQTTBrokerService.selectHandlers([replacement]) == [replacement] + } + + static abstract class RecordingHandler extends MQTTHandler { + List events + + @Override + void init(Container container, Configuration serverConfiguration) { + events << [this, "init"] + } + + @Override + void start(Container container) { + events << [this, "start"] + } + + @Override + void stop() { + events << [this, "stop"] + } + + @Override + protected boolean topicMatches(Topic topic) { + false + } + + @Override + protected Logger getLogger() { + Logger.getLogger(getClass().name) + } + + @Override + boolean canSubscribe(RemotingConnection connection, AuthContext authContext, Topic topic) { + false + } + + @Override + boolean canPublish(RemotingConnection connection, AuthContext authContext, Topic topic) { + false + } + + @Override + void onSubscribe(RemotingConnection connection, Topic topic) {} + + @Override + void onUnsubscribe(RemotingConnection connection, Topic topic) {} + + @Override + Set getPublishListenerTopics() { + [] as Set + } + + @Override + void onPublish(RemotingConnection connection, Topic topic, ByteBuf body) {} + } + + static class BuiltInHandler extends RecordingHandler {} + + static class BuiltInSubclassHandler extends BuiltInHandler {} + + static class ReplacementHandler extends RecordingHandler { + @Override + Set> getReplacedHandlers() { + [BuiltInHandler] as Set + } + } + + static class PeerHandler extends RecordingHandler { + @Override + int getPriority() { + 10 + } + } + + static class SelfReplacingHandler extends RecordingHandler { + @Override + Set> getReplacedHandlers() { + [SelfReplacingHandler] as Set + } + } + + static class CycleAHandler extends RecordingHandler { + @Override + Set> getReplacedHandlers() { + [CycleBHandler] as Set + } + } + + static class CycleBHandler extends RecordingHandler { + @Override + Set> getReplacedHandlers() { + [CycleAHandler] as Set + } + } +} diff --git a/model/src/main/java/org/openremote/model/provisioning/X509ProvisioningChallengeResponseMessage.java b/model/src/main/java/org/openremote/model/provisioning/X509ProvisioningChallengeResponseMessage.java index 07e30ecb39..084bbee984 100644 --- a/model/src/main/java/org/openremote/model/provisioning/X509ProvisioningChallengeResponseMessage.java +++ b/model/src/main/java/org/openremote/model/provisioning/X509ProvisioningChallengeResponseMessage.java @@ -35,7 +35,7 @@ public class X509ProvisioningChallengeResponseMessage extends ProvisioningMessage { /** Domain separator that every challenge issued by the manager starts with. */ - public static final String CHALLENGE_PREFIX = "OpenRemote MQTT X509 Challenge\n"; + public static final String CHALLENGE_PREFIX = "OpenRemote MQTT X509 provisioning v1\n"; protected String challenge; protected String algorithm;