Skip to content

armgit / core

Public Imported from GitHub
0

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

Made it possible to add custom IAuthorizerPolicy and custom InterceptorHandler for MqttBrokerService

Michael Rademaker6128c69d1eb9
diff --git a/manager/src/main/java/org/openremote/manager/mqtt/EventInterceptHandler.java b/manager/src/main/java/org/openremote/manager/mqtt/EventInterceptHandler.java
index 5dbc1a5ac..a9bb32d62 100644
--- a/manager/src/main/java/org/openremote/manager/mqtt/EventInterceptHandler.java
+++ b/manager/src/main/java/org/openremote/manager/mqtt/EventInterceptHandler.java
@@ -123,47 +123,51 @@ public class EventInterceptHandler extends AbstractInterceptHandler {
MqttConnection connection = mqttConnectionMap.get(interceptSubscribeMessage.getClientID());
if (connection != null) {
String[] topicParts = interceptSubscribeMessage.getTopicFilter().split(TOPIC_SEPARATOR);
- String assetId = topicParts[1];
- AttributeRef attributeRef = null;
- boolean isValueSubscription = false;
- if (topicParts.length > 2) { //attribute specific
- attributeRef = new AttributeRef(assetId, topicParts[2]);
- }
- if (topicParts.length == 4 && topicParts[3].equals(ASSET_ATTRIBUTE_VALUE_TOPIC)) {
- isValueSubscription = true;
- }
- String subscriptionId;
- if (attributeRef == null) {
- subscriptionId = connection.assetSubscriptions.remove(assetId);
- } else {
- if (isValueSubscription) {
- subscriptionId = connection.assetAttributeValueSubscriptions.remove(attributeRef);
+ if (topicParts.length > 1) {
+ String assetId = topicParts[1];
+ AttributeRef attributeRef = null;
+ boolean isValueSubscription = false;
+ if (topicParts.length > 2) { //attribute specific
+ attributeRef = new AttributeRef(assetId, topicParts[2]);
+ }
+ if (topicParts.length == 4 && topicParts[3].equals(ASSET_ATTRIBUTE_VALUE_TOPIC)) {
+ isValueSubscription = true;
+ }
+ String subscriptionId;
+ if (attributeRef == null) {
+ subscriptionId = connection.assetSubscriptions.remove(assetId);
} else {
- subscriptionId = connection.assetAttributeSubscriptions.remove(attributeRef);
+ if (isValueSubscription) {
+ subscriptionId = connection.assetAttributeValueSubscriptions.remove(attributeRef);
+ } else {
+ subscriptionId = connection.assetAttributeSubscriptions.remove(attributeRef);
+ }
}
- }
- AssetFilter<AttributeEvent> attributeAssetFilter = new AssetFilter<AttributeEvent>().setRealm(connection.realm).setAssetIds(assetId);
- EventSubscription<AttributeEvent> subscription = new EventSubscription<>(
- AttributeEvent.class,
- attributeAssetFilter,
- TextUtil.isNullOrEmpty(subscriptionId) ? String.valueOf(connection.getNextSubscriptionId()) : subscriptionId);
+ AssetFilter<AttributeEvent> attributeAssetFilter = new AssetFilter<AttributeEvent>().setRealm(connection.realm).setAssetIds(assetId);
+ EventSubscription<AttributeEvent> subscription = new EventSubscription<>(
+ AttributeEvent.class,
+ attributeAssetFilter,
+ TextUtil.isNullOrEmpty(subscriptionId) ? String.valueOf(connection.getNextSubscriptionId()) : subscriptionId);
- if (attributeRef == null) { //attribute specific
- connection.assetSubscriptions.put(assetId, subscription.getSubscriptionId());
- } else {
- attributeAssetFilter.setAttributeNames(attributeRef.getName());
- if (isValueSubscription) {
- connection.assetAttributeValueSubscriptions.put(attributeRef, subscription.getSubscriptionId());
+ if (attributeRef == null) { //attribute specific
+ connection.assetSubscriptions.put(assetId, subscription.getSubscriptionId());
} else {
- connection.assetAttributeSubscriptions.put(attributeRef, subscription.getSubscriptionId());
+ attributeAssetFilter.setAttributeNames(attributeRef.getName());
+ if (isValueSubscription) {
+ connection.assetAttributeValueSubscriptions.put(attributeRef, subscription.getSubscriptionId());
+ } else {
+ connection.assetAttributeSubscriptions.put(attributeRef, subscription.getSubscriptionId());
+ }
}
- }
- Map<String, Object> headers = prepareHeaders(connection);
- messageBrokerService.getProducerTemplate().sendBodyAndHeaders(ClientEventService.CLIENT_EVENT_QUEUE, subscription, headers);
+ Map<String, Object> headers = prepareHeaders(connection);
+ messageBrokerService.getProducerTemplate().sendBodyAndHeaders(ClientEventService.CLIENT_EVENT_QUEUE, subscription, headers);
+ } else {
+ LOG.info("Couldn't process message for topic: " + interceptSubscribeMessage.getTopicFilter());
+ }
} else {
- throw new IllegalStateException("Connection with clientId " + interceptSubscribeMessage.getClientID() + " not found.");
+ LOG.info("No connection found for clientId: " + interceptSubscribeMessage.getClientID());
}
}
@@ -172,23 +176,29 @@ public class EventInterceptHandler extends AbstractInterceptHandler {
MqttConnection connection = mqttConnectionMap.get(interceptUnsubscribeMessage.getClientID());
if (connection != null) {
String[] topicParts = interceptUnsubscribeMessage.getTopicFilter().split(TOPIC_SEPARATOR);
- String assetId = topicParts[1];
- String subscriptionId;
+ if (topicParts.length > 1) {
+ String assetId = topicParts[1];
+ String subscriptionId;
- if (topicParts.length > 2) { //attribute specific
- if (topicParts.length == 4 && topicParts[3].equals(ASSET_ATTRIBUTE_VALUE_TOPIC)) {
- subscriptionId = connection.assetAttributeValueSubscriptions.remove(new AttributeRef(assetId, topicParts[2]));
+ if (topicParts.length > 2) { //attribute specific
+ if (topicParts.length == 4 && topicParts[3].equals(ASSET_ATTRIBUTE_VALUE_TOPIC)) {
+ subscriptionId = connection.assetAttributeValueSubscriptions.remove(new AttributeRef(assetId, topicParts[2]));
+ } else {
+ subscriptionId = connection.assetAttributeSubscriptions.remove(new AttributeRef(assetId, topicParts[2]));
+ }
} else {
- subscriptionId = connection.assetAttributeSubscriptions.remove(new AttributeRef(assetId, topicParts[2]));
+ subscriptionId = connection.assetSubscriptions.remove(assetId);
}
- } else {
- subscriptionId = connection.assetSubscriptions.remove(assetId);
- }
- if (subscriptionId != null) {
- Map<String, Object> headers = prepareHeaders(connection);
- CancelEventSubscription cancelEventSubscription = new CancelEventSubscription(AttributeEvent.class, subscriptionId);
- messageBrokerService.getProducerTemplate().sendBodyAndHeaders(ClientEventService.CLIENT_EVENT_QUEUE, cancelEventSubscription, headers);
+ if (subscriptionId != null) {
+ Map<String, Object> headers = prepareHeaders(connection);
+ CancelEventSubscription cancelEventSubscription = new CancelEventSubscription(AttributeEvent.class, subscriptionId);
+ messageBrokerService.getProducerTemplate().sendBodyAndHeaders(ClientEventService.CLIENT_EVENT_QUEUE, cancelEventSubscription, headers);
+ }
+ } else {
+ LOG.info("Couldn't process message for topic: " + interceptUnsubscribeMessage.getTopicFilter());
}
+ } else {
+ LOG.info("No connection found for clientId: " + interceptUnsubscribeMessage.getClientID());
}
}
@@ -197,42 +207,48 @@ public class EventInterceptHandler extends AbstractInterceptHandler {
MqttConnection connection = mqttConnectionMap.get(msg.getClientID());
if (connection != null) {
String[] topicParts = msg.getTopicName().split(TOPIC_SEPARATOR);
- String assetId = topicParts[1];
- AttributeRef attributeRef = null;
- if (topicParts.length > 2) { //attribute specific
- attributeRef = new AttributeRef(assetId, topicParts[2]);
- }
- if (attributeRef == null) {
- String payloadContent = msg.getPayload().toString(Charset.defaultCharset());
- Values.parse(payloadContent).flatMap(Values::asJSONObject).ifPresent(objectValue -> {
- Map<String, Object> headers = prepareHeaders(connection);
- Map.Entry<String, JsonNode> firstElem = objectValue.fields().next();
- AttributeEvent attributeEvent = new AttributeEvent(assetId, firstElem.getKey(), firstElem.getValue());
- messageBrokerService.getProducerTemplate().sendBodyAndHeaders(ClientEventService.CLIENT_EVENT_QUEUE, attributeEvent, headers);
- });
- } else {
- String payloadContent = msg.getPayload().toString(Charset.defaultCharset());
- Object value = null;
- if (Character.isLetter(payloadContent.charAt(0))) {
- if (payloadContent.equals(Boolean.TRUE.toString())) {
- value = true;
+ if (topicParts.length > 1) {
+ String assetId = topicParts[1];
+ AttributeRef attributeRef = null;
+ if (topicParts.length > 2) { //attribute specific
+ attributeRef = new AttributeRef(assetId, topicParts[2]);
+ }
+ if (attributeRef == null) {
+ String payloadContent = msg.getPayload().toString(Charset.defaultCharset());
+ Values.parse(payloadContent).flatMap(Values::asJSONObject).ifPresent(objectValue -> {
+ Map<String, Object> headers = prepareHeaders(connection);
+ Map.Entry<String, JsonNode> firstElem = objectValue.fields().next();
+ AttributeEvent attributeEvent = new AttributeEvent(assetId, firstElem.getKey(), firstElem.getValue());
+ messageBrokerService.getProducerTemplate().sendBodyAndHeaders(ClientEventService.CLIENT_EVENT_QUEUE, attributeEvent, headers);
+ });
+ } else {
+ String payloadContent = msg.getPayload().toString(Charset.defaultCharset());
+ Object value = null;
+ if (Character.isLetter(payloadContent.charAt(0))) {
+ if (payloadContent.equals(Boolean.TRUE.toString())) {
+ value = true;
+ }
+ if (payloadContent.equals(Boolean.FALSE.toString())) {
+ value = false;
+ }
+ payloadContent = '"' + payloadContent + '"';
}
- if (payloadContent.equals(Boolean.FALSE.toString())) {
- value = false;
+ if (value == null) {
+ value = Values.parse(payloadContent);
+ }
+ if (value == null) {
+ value = payloadContent;
}
- payloadContent = '"' + payloadContent + '"';
- }
- if (value == null) {
- value = Values.parse(payloadContent);
- }
- if (value == null) {
- value = payloadContent;
- }
- Map<String, Object> headers = prepareHeaders(connection);
- AttributeEvent attributeEvent = new AttributeEvent(assetId, attributeRef.getName(), value);
- messageBrokerService.getProducerTemplate().sendBodyAndHeaders(ClientEventService.CLIENT_EVENT_QUEUE, attributeEvent, headers);
+ Map<String, Object> headers = prepareHeaders(connection);
+ AttributeEvent attributeEvent = new AttributeEvent(assetId, attributeRef.getName(), value);
+ messageBrokerService.getProducerTemplate().sendBodyAndHeaders(ClientEventService.CLIENT_EVENT_QUEUE, attributeEvent, headers);
+ }
+ } else {
+ LOG.info("Couldn't process message for topic: " + msg.getTopicName());
}
+ } else {
+ LOG.info("No connection found for clientId: " + msg.getClientID());
}
}
diff --git a/manager/src/main/java/org/openremote/manager/mqtt/KeycloakAuthorizatorPolicy.java b/manager/src/main/java/org/openremote/manager/mqtt/KeycloakAuthorizatorPolicy.java
index 3a5fbb19d..cabf9236c 100644
--- a/manager/src/main/java/org/openremote/manager/mqtt/KeycloakAuthorizatorPolicy.java
+++ b/manager/src/main/java/org/openremote/manager/mqtt/KeycloakAuthorizatorPolicy.java
@@ -3,6 +3,7 @@ package org.openremote.manager.mqtt;
import io.moquette.broker.security.IAuthorizatorPolicy;
import io.moquette.broker.subscriptions.Token;
import io.moquette.broker.subscriptions.Topic;
+
import org.keycloak.adapters.rotation.AdapterTokenVerifier;
import org.keycloak.common.VerificationException;
import org.keycloak.representations.AccessToken;
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 9b6d10af2..6309a79b0 100644
--- a/manager/src/main/java/org/openremote/manager/mqtt/MqttBrokerService.java
+++ b/manager/src/main/java/org/openremote/manager/mqtt/MqttBrokerService.java
@@ -23,6 +23,7 @@ import com.fasterxml.jackson.core.JsonProcessingException;
import io.moquette.BrokerConstants;
import io.moquette.broker.Server;
import io.moquette.broker.config.MemoryConfig;
+import io.moquette.broker.security.IAuthorizatorPolicy;
import io.moquette.interception.InterceptHandler;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
@@ -35,7 +36,6 @@ import org.openremote.manager.asset.AssetStorageService;
import org.openremote.manager.event.ClientEventService;
import org.openremote.manager.security.ManagerIdentityService;
import org.openremote.manager.security.ManagerKeycloakIdentityProvider;
-import org.openremote.manager.web.ManagerWebService;
import org.openremote.model.attribute.AttributeEvent;
import org.openremote.model.event.TriggeredEventSubscription;
import org.openremote.model.value.Values;
@@ -51,7 +51,7 @@ import static org.openremote.agent.protocol.ProtocolClientEventService.getSessio
public class MqttBrokerService implements ContainerService {
- public static final int PRIORITY = ManagerWebService.PRIORITY - 100;
+ public static final int PRIORITY = MED_PRIORITY;
private static final Logger LOG = Logger.getLogger(MqttBrokerService.class.getName());
public static final String MQTT_CLIENT_QUEUE = "seda://MqttClientQueue?waitForTaskToComplete=IfReplyExpected&timeout=10000&purgeWhenStopping=true&discardIfNoConsumers=false&size=25000";
@@ -67,8 +67,10 @@ public class MqttBrokerService implements ContainerService {
protected ManagerKeycloakIdentityProvider identityProvider;
protected ClientEventService clientEventService;
protected MessageBrokerService messageBrokerService;
+ protected ORAuthorizatorPolicy mainAuthorizatorPolicy;
protected Map<String, MqttConnection> mqttConnectionMap;
+ protected List<InterceptHandler> interceptHandlers;
protected boolean active;
protected String host;
@@ -85,7 +87,9 @@ public class MqttBrokerService implements ContainerService {
host = getString(container.getConfig(), MQTT_SERVER_LISTEN_HOST, BrokerConstants.HOST);
port = getInteger(container.getConfig(), MQTT_SERVER_LISTEN_PORT, BrokerConstants.PORT);
+ mainAuthorizatorPolicy = new ORAuthorizatorPolicy();
mqttConnectionMap = new HashMap<>();
+ interceptHandlers = new ArrayList<>();
clientEventService = container.getService(ClientEventService.class);
ManagerIdentityService identityService = container.getService(ManagerIdentityService.class);
@@ -137,10 +141,12 @@ public class MqttBrokerService implements ContainerService {
properties.setProperty(BrokerConstants.HOST_PROPERTY_NAME, host);
properties.setProperty(BrokerConstants.PORT_PROPERTY_NAME, String.valueOf(port));
properties.setProperty(BrokerConstants.ALLOW_ANONYMOUS_PROPERTY_NAME, String.valueOf(false));
- List<? extends InterceptHandler> interceptHandlers = Collections.singletonList(new EventInterceptHandler(identityProvider, messageBrokerService, mqttConnectionMap));
+ interceptHandlers.add(new EventInterceptHandler(identityProvider, messageBrokerService, mqttConnectionMap));
AssetStorageService assetStorageService = container.getService(AssetStorageService.class);
- mqttBroker.startServer(new MemoryConfig(properties), interceptHandlers, null, new KeycloakAuthenticator(identityProvider), new KeycloakAuthorizatorPolicy(identityProvider, assetStorageService, clientEventService, mqttConnectionMap));
+ mainAuthorizatorPolicy.addAuthorizatorPolicy(new KeycloakAuthorizatorPolicy(identityProvider, assetStorageService, clientEventService, mqttConnectionMap));
+
+ mqttBroker.startServer(new MemoryConfig(properties), interceptHandlers, null, new KeycloakAuthenticator(identityProvider), mainAuthorizatorPolicy);
LOG.fine("Started MQTT broker");
}
@@ -177,4 +183,13 @@ public class MqttBrokerService implements ContainerService {
mqttBroker.internalPublish(publishMessage, clientId);
}
+
+ public MqttBrokerService addInterceptHandler(InterceptHandler interceptHandler) {
+ interceptHandlers.add(interceptHandler);
+ return this;
+ }
+
+ public void addAuthorizerPolicy(IAuthorizatorPolicy authorizatorPolicy) {
+ mainAuthorizatorPolicy.addAuthorizatorPolicy(authorizatorPolicy);
+ }
}
diff --git a/manager/src/main/java/org/openremote/manager/mqtt/ORAuthorizatorPolicy.java b/manager/src/main/java/org/openremote/manager/mqtt/ORAuthorizatorPolicy.java
new file mode 100644
index 000000000..422833465
--- /dev/null
+++ b/manager/src/main/java/org/openremote/manager/mqtt/ORAuthorizatorPolicy.java
@@ -0,0 +1,28 @@
+package org.openremote.manager.mqtt;
+
+import java.util.Collection;
+import java.util.concurrent.CopyOnWriteArraySet;
+
+import io.moquette.broker.security.IAuthorizatorPolicy;
+import io.moquette.broker.subscriptions.Topic;
+
+public class ORAuthorizatorPolicy implements IAuthorizatorPolicy {
+
+ final protected Collection<IAuthorizatorPolicy> authorizatorPolicies = new CopyOnWriteArraySet<>();
+
+ @Override
+ public boolean canRead(Topic topic, String username, String clientId) {
+ return authorizatorPolicies.stream()
+ .anyMatch(authorizer -> authorizer.canRead(topic, username, clientId));
+ }
+
+ @Override
+ public boolean canWrite(Topic topic, String username, String clientId) {
+ return authorizatorPolicies.stream()
+ .anyMatch(authorizer -> authorizer.canWrite(topic, username, clientId));
+ }
+
+ public void addAuthorizatorPolicy(IAuthorizatorPolicy authorizer) {
+ this.authorizatorPolicies.add(authorizer);
+ }
+}