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..e2d81c43ef 100644 --- a/manager/src/main/java/org/openremote/manager/mqtt/MQTTBrokerService.java +++ b/manager/src/main/java/org/openremote/manager/mqtt/MQTTBrokerService.java @@ -274,13 +274,16 @@ public MeterRegistry getRegistry() { serverConfiguration.setAuthenticationCacheSize(0); serverConfiguration.setAuthorizationCacheSize(0); - // Load custom handlers + // Load custom handlers, discarding any that have been replaced by another handler this.customHandlers = - stream(ServiceLoader.load(MQTTHandler.class).spliterator(), false) - .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); @@ -361,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); @@ -455,8 +462,16 @@ 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()) + 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( handler -> { try { @@ -588,6 +603,96 @@ public void onUnsubscribe(RemotingConnection connection, String topicStr) { } } + /** + * 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 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( + handler -> { + MQTTHandler replacement = replacedBy.get(handler.getClass()); + if (replacement != null) { + LOG.log( + INFO, + "MQTT handler '" + + handler.getName() + + "' replaced by '" + + replacement.getName() + + "'"); + } + return replacement == null; + }) + .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() { 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..e8d057b70c 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,18 @@ 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. 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(); + } + /** Provides a name to identify this custom handler for logging purposes etc. */ public String getName() { return this.getClass().getSimpleName(); 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/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/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() 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;