Skip to content

armgit / core

Public Imported from GitHub
0

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

User and asset provisioning now fully functional some minor enhancements to follow

Rich Turneref79af0e933e
diff --git a/agent/src/main/java/org/openremote/agent/protocol/mqtt/AbstractMQTT_IOClient.java b/agent/src/main/java/org/openremote/agent/protocol/mqtt/AbstractMQTT_IOClient.java
index 4e6a7326f..57fce11d9 100644
--- a/agent/src/main/java/org/openremote/agent/protocol/mqtt/AbstractMQTT_IOClient.java
+++ b/agent/src/main/java/org/openremote/agent/protocol/mqtt/AbstractMQTT_IOClient.java
@@ -30,6 +30,7 @@ import com.hivemq.client.mqtt.mqtt3.exceptions.Mqtt3DisconnectException;
import com.hivemq.client.mqtt.mqtt3.lifecycle.Mqtt3ClientDisconnectedContext;
import com.hivemq.client.mqtt.mqtt3.message.connect.Mqtt3ConnectBuilder;
import com.hivemq.client.mqtt.mqtt3.message.connect.connack.Mqtt3ConnAck;
+import com.hivemq.client.mqtt.mqtt3.message.subscribe.suback.Mqtt3SubAck;
import org.openremote.agent.protocol.io.IOClient;
import org.openremote.container.Container;
import org.openremote.container.util.UniqueIdentifierGenerator;
@@ -58,6 +59,7 @@ public abstract class AbstractMQTT_IOClient<S> implements IOClient<MQTTMessage<S
protected String host;
protected int port;
protected boolean secure;
+ protected boolean cleanSession;
protected UsernamePassword usernamePassword;
protected URI websocketURI;
protected Mqtt3AsyncClient client;
@@ -66,16 +68,18 @@ public abstract class AbstractMQTT_IOClient<S> implements IOClient<MQTTMessage<S
protected ScheduledExecutorService executorService;
protected ConnectionStatus connectionStatus = ConnectionStatus.DISCONNECTED;
protected boolean disconnected = true; // Need to use this flag to cancel client reconnect task
+ protected Consumer<String> topicSubscribeFailureConsumer;
- protected AbstractMQTT_IOClient(String host, int port, boolean secure, UsernamePassword usernamePassword, URI websocketURI) {
- this(UniqueIdentifierGenerator.generateId(), host, port, secure, usernamePassword, websocketURI);
+ protected AbstractMQTT_IOClient(String host, int port, boolean secure, boolean cleanSession, UsernamePassword usernamePassword, URI websocketURI) {
+ this(UniqueIdentifierGenerator.generateId(), host, port, secure, cleanSession, usernamePassword, websocketURI);
}
- protected AbstractMQTT_IOClient(String clientId, String host, int port, boolean secure, UsernamePassword usernamePassword, URI websocketURI) {
+ protected AbstractMQTT_IOClient(String clientId, String host, int port, boolean secure, boolean cleanSession, UsernamePassword usernamePassword, URI websocketURI) {
this.clientId = clientId;
this.host = host;
this.port = port;
this.secure = secure;
+ this.cleanSession = cleanSession;
this.usernamePassword = usernamePassword;
this.websocketURI = websocketURI;
this.executorService = Container.EXECUTOR_SERVICE;
@@ -171,50 +175,83 @@ public abstract class AbstractMQTT_IOClient<S> implements IOClient<MQTTMessage<S
addMessageConsumer("#", messageConsumer);
}
- public void addMessageConsumer(String topic, Consumer<MQTTMessage<S>> messageConsumer) {
+ @SuppressWarnings("SynchronizationOnLocalVariableOrMethodParameter")
+ public boolean addMessageConsumer(String topic, Consumer<MQTTMessage<S>> messageConsumer) {
if (client == null) {
- return;
+ return false;
}
- boolean initialise;
Set<Consumer<MQTTMessage<S>>> consumers;
synchronized (topicConsumerMap) {
consumers = topicConsumerMap.computeIfAbsent(topic, (t) -> new HashSet<>());
synchronized (consumers) {
- initialise = consumers.isEmpty();
- consumers.add(messageConsumer);
+ if (consumers.isEmpty()) {
+ // Create the subscription on the client
+ if (doClientSubscription(topic, consumers)) {
+ consumers.add(messageConsumer);
+ return true;
+ } else {
+ topicConsumerMap.remove(topic);
+ return false;
+ }
+ } else {
+ consumers.add(messageConsumer);
+ return true;
+ }
}
}
+ }
- if (initialise) {
- addSubscription(
- topic,
- message -> {
- if (!topicConsumerMap.containsKey(topic)) {
- return;
- }
- synchronized (consumers) {
- consumers.forEach(consumer -> {
- try {
- consumer.accept(message);
- } catch (Exception e) {
- LOG.log(Level.WARNING, "Message consumer threw an exception", e);
- }
- });
- }
- },
- () -> {
- synchronized (consumers) {
- consumers.remove(messageConsumer);
- if (consumers.isEmpty()) {
- synchronized (topicConsumerMap) {
- topicConsumerMap.remove(topic);
- }
- }
+ public void setTopicSubscribeFailureConsumer(Consumer<String> topicSubscribeFailureConsumer) {
+ this.topicSubscribeFailureConsumer = topicSubscribeFailureConsumer;
+ }
+
+ protected void onSubscribeFailed(String topic) {
+ if (this.topicSubscribeFailureConsumer != null) {
+ this.topicSubscribeFailureConsumer.accept(topic);
+ }
+ }
+
+ protected boolean doClientSubscription(String topic, Set<Consumer<MQTTMessage<S>>> consumers) {
+ Consumer<MQTTMessage<S>> messageConsumer = message -> {
+ if (!topicConsumerMap.containsKey(topic)) {
+ return;
+ }
+ synchronized (consumers) {
+ consumers.forEach(consumer -> {
+ try {
+ consumer.accept(message);
+ } catch (Exception e) {
+ LOG.log(Level.WARNING, "Message consumer threw an exception", e);
}
});
+ }
+ };
+
+ try {
+ Mqtt3SubAck subAck = client.subscribeWith()
+ .topicFilter(topic)
+ .callback(publish -> {
+ try {
+ String topicStr = publish.getTopic().toString();
+ S payload = messageFromBytes(publish.getPayloadAsBytes());
+ MQTTMessage<S> message = new MQTTMessage<>(topicStr, payload);
+ messageConsumer.accept(message);
+ } catch (Exception e) {
+ LOG.log(Level.WARNING, "Failed to process published message on client '" + getClientUri() + "'", e);
+ }
+ })
+ .send()
+ .get();
+
+ LOG.fine("Subscribed to topic '" + topic + "' on client '" + getClientUri() + "'");
+ return true;
+ } catch (Exception e) {
+ LOG.log(Level.WARNING, "Failed to subscribe to topic '" + topic + "' on client '" + getClientUri() + "'", e);
+ executorService.execute(() -> onSubscribeFailed(topic));
}
+ return false;
}
@Override
@@ -246,30 +283,6 @@ public abstract class AbstractMQTT_IOClient<S> implements IOClient<MQTTMessage<S
}
}
- protected void addSubscription(String topic, Consumer<MQTTMessage<S>> onPublish, Runnable onFailure) {
- client.subscribeWith()
- .topicFilter(topic)
- .callback(publish -> {
- try {
- String topicStr = publish.getTopic().toString();
- S payload = messageFromBytes(publish.getPayloadAsBytes());
- MQTTMessage<S> message = new MQTTMessage<>(topicStr, payload);
- onPublish.accept(message);
- } catch (Exception e) {
- LOG.log(Level.WARNING, "Failed to process published message on client '" + getClientUri() + "'", e);
- }
- })
- .send()
- .whenComplete((subAck, throwable) -> {
- if (throwable != null) {
- LOG.log(Level.WARNING, "Failed to subscribe to topic '" + topic + "' on client '" + getClientUri() + "'", throwable);
- onFailure.run();
- } else {
- LOG.fine("Subscribed to topic '" + topic + "' on client '" + getClientUri() + "'");
- }
- });
- }
-
protected void removeSubscription(String topic) {
if (client != null) {
client.unsubscribeWith()
@@ -321,7 +334,9 @@ public abstract class AbstractMQTT_IOClient<S> implements IOClient<MQTTMessage<S
LOG.info("Establishing connection: " + getClientUri());
- Mqtt3ConnectBuilder.Send<CompletableFuture<Mqtt3ConnAck>> completableFutureSend = client.connectWith().keepAlive(5);
+ Mqtt3ConnectBuilder.Send<CompletableFuture<Mqtt3ConnAck>> completableFutureSend = client.connectWith()
+ .cleanSession(cleanSession)
+ .keepAlive(5);
if (usernamePassword != null) {
completableFutureSend = completableFutureSend.simpleAuth()
@@ -330,7 +345,26 @@ public abstract class AbstractMQTT_IOClient<S> implements IOClient<MQTTMessage<S
.applySimpleAuth();
}
- completableFutureSend.send();
+ completableFutureSend.send().whenComplete((connAck, throwable) -> {
+ if (throwable != null) {
+ LOG.log(Level.INFO, "Connection failed:" + getClientUri(), throwable);
+ } else {
+ if (!this.cleanSession && !connAck.isSessionPresent()) {
+ // Need to re-instate the subscriptions as HiveMQ client doesn't do it
+ executorService.execute(() -> {
+ // Re-add all subscriptions
+ synchronized (topicConsumerMap) {
+ // Clone the map as subscribe failures will modify the map
+ new HashMap<>(topicConsumerMap).forEach((topic, consumers) -> {
+ if (!doClientSubscription(topic, consumers)) {
+ topicConsumerMap.remove(topic);
+ }
+ });
+ }
+ });
+ }
+ }
+ });
}
protected void onConnectionStatusChanged(ConnectionStatus connectionStatus) {
@@ -369,7 +403,9 @@ public abstract class AbstractMQTT_IOClient<S> implements IOClient<MQTTMessage<S
this.disconnected = true;
client.disconnect().whenComplete((unused, throwable) -> {
-
+ if (this.cleanSession) {
+ removeAllMessageConsumers();
+ }
if (throwable != null) {
LOG.info("Failed to disconnect");
}
diff --git a/agent/src/main/java/org/openremote/agent/protocol/mqtt/MQTTAgent.java b/agent/src/main/java/org/openremote/agent/protocol/mqtt/MQTTAgent.java
index 4c0094d2e..27c30c5a9 100644
--- a/agent/src/main/java/org/openremote/agent/protocol/mqtt/MQTTAgent.java
+++ b/agent/src/main/java/org/openremote/agent/protocol/mqtt/MQTTAgent.java
@@ -36,6 +36,7 @@ public class MQTTAgent extends IOAgent<MQTTAgent, MQTTProtocol, MQTTAgentLink> {
public static final AttributeDescriptor<Integer> MQTT_PORT = PORT.withOptional(false);
public static final AttributeDescriptor<String> CLIENT_ID = new AttributeDescriptor<>("clientId", ValueType.TEXT);
public static final AttributeDescriptor<Boolean> SECURE_MODE = new AttributeDescriptor<>("secureMode", ValueType.BOOLEAN);
+ public static final AttributeDescriptor<Boolean> RESUME_SESSION = new AttributeDescriptor<>("resumeSession", ValueType.BOOLEAN);
public static final AttributeDescriptor<Boolean> WEBSOCKET_MODE = new AttributeDescriptor<>("websocketMode", ValueType.BOOLEAN);
public static final AttributeDescriptor<String> WEBSOCKET_PATH = new AttributeDescriptor<>("websocketPath", ValueType.TEXT);
public static final AttributeDescriptor<String> WEBSOCKET_QUERY = new AttributeDescriptor<>("websocketQuery", ValueType.TEXT);
@@ -86,6 +87,15 @@ public class MQTTAgent extends IOAgent<MQTTAgent, MQTTProtocol, MQTTAgentLink> {
return this;
}
+ public Optional<Boolean> isResumeSession() {
+ return getAttributes().getValue(RESUME_SESSION);
+ }
+
+ public MQTTAgent setResumeSession(boolean resumeSession) {
+ getAttributes().addOrReplace(new Attribute<>(RESUME_SESSION, resumeSession));
+ return this;
+ }
+
public Optional<String> getWebsocketPath() {
return getAttributes().getValue(WEBSOCKET_PATH);
}
diff --git a/agent/src/main/java/org/openremote/agent/protocol/mqtt/MQTTProtocol.java b/agent/src/main/java/org/openremote/agent/protocol/mqtt/MQTTProtocol.java
index 776c1ede5..5f3ba81c9 100644
--- a/agent/src/main/java/org/openremote/agent/protocol/mqtt/MQTTProtocol.java
+++ b/agent/src/main/java/org/openremote/agent/protocol/mqtt/MQTTProtocol.java
@@ -101,7 +101,7 @@ public class MQTTProtocol extends AbstractMQTTClientProtocol<MQTTProtocol, MQTTA
websocketURI = builder.build();
}
- return new MQTT_IOClient(agent.getClientId().orElseGet(UniqueIdentifierGenerator::generateId), host, port, agent.isSecureMode().orElse(false), agent.getUsernamePassword().orElse(null), websocketURI);
+ return new MQTT_IOClient(agent.getClientId().orElseGet(UniqueIdentifierGenerator::generateId), host, port, agent.isSecureMode().orElse(false), !agent.isResumeSession().orElse(false), agent.getUsernamePassword().orElse(null), websocketURI);
}
@Override
diff --git a/agent/src/main/java/org/openremote/agent/protocol/mqtt/MQTT_IOClient.java b/agent/src/main/java/org/openremote/agent/protocol/mqtt/MQTT_IOClient.java
index 65264ff8a..93fd7b531 100644
--- a/agent/src/main/java/org/openremote/agent/protocol/mqtt/MQTT_IOClient.java
+++ b/agent/src/main/java/org/openremote/agent/protocol/mqtt/MQTT_IOClient.java
@@ -26,12 +26,12 @@ import java.nio.charset.StandardCharsets;
public class MQTT_IOClient extends AbstractMQTT_IOClient<String> {
- protected MQTT_IOClient(String host, int port, boolean secure, UsernamePassword usernamePassword, URI websocketURI) {
- super(host, port, secure, usernamePassword, websocketURI);
+ public MQTT_IOClient(String host, int port, boolean secure, boolean cleanSession, UsernamePassword usernamePassword, URI websocketURI) {
+ super(host, port, secure, cleanSession, usernamePassword, websocketURI);
}
- protected MQTT_IOClient(String clientId, String host, int port, boolean secure, UsernamePassword usernamePassword, URI websocketURI) {
- super(clientId, host, port, secure, usernamePassword, websocketURI);
+ public MQTT_IOClient(String clientId, String host, int port, boolean secure, boolean cleanSession, UsernamePassword usernamePassword, URI websocketURI) {
+ super(clientId, host, port, secure, cleanSession, usernamePassword, websocketURI);
}
@Override
diff --git a/container/src/main/java/org/openremote/container/persistence/PersistenceService.java b/container/src/main/java/org/openremote/container/persistence/PersistenceService.java
index 0e5e199d2..0cfc89da5 100644
--- a/container/src/main/java/org/openremote/container/persistence/PersistenceService.java
+++ b/container/src/main/java/org/openremote/container/persistence/PersistenceService.java
@@ -38,6 +38,8 @@ import org.openremote.model.datapoint.AssetDatapoint;
import org.openremote.model.gateway.GatewayConnection;
import org.openremote.model.notification.SentNotification;
import org.openremote.model.datapoint.AssetPredictedDatapoint;
+import org.openremote.model.provisioning.ProvisioningConfig;
+import org.openremote.model.provisioning.X509ProvisioningConfig;
import org.openremote.model.rules.AssetRuleset;
import org.openremote.model.rules.GlobalRuleset;
import org.openremote.model.rules.TenantRuleset;
@@ -282,6 +284,8 @@ public class PersistenceService implements ContainerService {
entityClasses.add(SyslogEvent.class.getName());
entityClasses.add(GatewayConnection.class.getName());
entityClasses.add(ConsoleAppConfig.class.getName());
+ entityClasses.add(ProvisioningConfig.class.getName());
+ entityClasses.add(X509ProvisioningConfig.class.getName());
// Add packages with package-info (don't think this is JPA spec but hibernate specific)
entityClasses.add("org.openremote.container.persistence");
diff --git a/docker-compose.yml b/docker-compose.yml
index cd20c8d97..9c105855a 100644
--- a/docker-compose.yml
+++ b/docker-compose.yml
@@ -39,7 +39,7 @@ services:
postgresql:
condition: service_healthy
environment:
- KEYCLOAK_FRONTEND_URL: ${EXTERNAL_URL:-https://localhost}/auth
+ KEYCLOAK_FRONTEND_URL: ${EXTERNAL_URL:-https://localhost}/auth}
KEYCLOAK_PASSWORD: ${SETUP_ADMIN_PASSWORD:-secret}
manager:
diff --git a/manager/src/main/java/org/openremote/manager/asset/AssetStorageService.java b/manager/src/main/java/org/openremote/manager/asset/AssetStorageService.java
index 55a33ee74..2ed6db7ba 100644
--- a/manager/src/main/java/org/openremote/manager/asset/AssetStorageService.java
+++ b/manager/src/main/java/org/openremote/manager/asset/AssetStorageService.java
@@ -751,16 +751,16 @@ public class AssetStorageService extends RouteBuilder implements ContainerServic
} else {
updatedAsset = em.merge(asset);
if (existingAsset == null) {
- if (LOG.isLoggable(Level.FINE)) {
- LOG.fine("Asset created: " + updatedAsset.toStringAll());
+ if (LOG.isLoggable(Level.FINER)) {
+ LOG.finer("Asset created: " + updatedAsset.toStringAll());
} else {
- LOG.info("Asset created: " + updatedAsset);
+ LOG.fine("Asset created: " + updatedAsset);
}
} else {
- if (LOG.isLoggable(Level.FINE)) {
- LOG.fine("Asset updated: new = " + updatedAsset.toStringAll() + ", old = " + existingAsset.toStringAll());
+ if (LOG.isLoggable(Level.FINER)) {
+ LOG.finer("Asset updated: new = " + updatedAsset.toStringAll() + ", old = " + existingAsset.toStringAll());
} else {
- LOG.info("Asset updated: " + updatedAsset);
+ LOG.fine("Asset updated: " + updatedAsset);
}
}
}
@@ -1198,7 +1198,7 @@ public class AssetStorageService extends RouteBuilder implements ContainerServic
String[] updatedProperties = Arrays.stream(persistenceEvent.getPropertyNames()).filter(propertyName -> {
Object oldValue = persistenceEvent.getPreviousState(propertyName);
Object newValue = persistenceEvent.getCurrentState(propertyName);
- return !Objects.equals(oldValue, newValue);
+ return !Objects.deepEquals(oldValue, newValue);
}).toArray(String[]::new);
// Fully load the asset
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 e26a3d6cd..8b190735d 100644
--- a/manager/src/main/java/org/openremote/manager/mqtt/MqttBrokerService.java
+++ b/manager/src/main/java/org/openremote/manager/mqtt/MqttBrokerService.java
@@ -21,6 +21,7 @@ package org.openremote.manager.mqtt;
import io.moquette.BrokerConstants;
import io.moquette.broker.Server;
+import io.moquette.broker.SessionRegistry;
import io.moquette.broker.config.MemoryConfig;
import io.moquette.broker.security.IAuthenticator;
import io.moquette.interception.InterceptHandler;
@@ -42,9 +43,11 @@ import org.openremote.model.syslog.SyslogCategory;
import org.openremote.model.util.TextUtil;
import org.openremote.model.util.ValueUtil;
+import java.lang.reflect.Field;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.*;
+import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.ScheduledExecutorService;
import java.util.logging.Level;
import java.util.logging.Logger;
@@ -198,7 +201,34 @@ public class MqttBrokerService implements ContainerService, IAuthenticator {
public MqttConnection removeConnection(String clientId) {
synchronized (clientIdConnectionMap) {
- return clientIdConnectionMap.remove(clientId);
+ MqttConnection connection = clientIdConnectionMap.remove(clientId);
+ if (connection != null && !connection.isCleanSession()) {
+ forceClearSession(clientId);
+ }
+ return connection;
+ }
+ }
+
+ /**
+ * We have this as there's no way to configure expiry time of sessions in Moquette so to make things simple we
+ * clear the session whenever the client disconnects; the client can then re-subscribe as needed
+ */
+ public void forceClearSession(String clientId) {
+ if (mqttBroker == null) {
+ return;
+ }
+
+ try {
+ Field sessionsField = Server.class.getDeclaredField("sessions");
+ Field poolField = SessionRegistry.class.getDeclaredField("pool");
+ sessionsField.setAccessible(true);
+ poolField.setAccessible(true);
+ SessionRegistry sessions = (SessionRegistry) sessionsField.get(mqttBroker);
+ ConcurrentMap<?,?> pool = (ConcurrentMap<?, ?>) poolField.get(sessions);
+ Object session = pool.get(clientId);
+ pool.remove(clientId, session);
+ } catch (Exception e) {
+ LOG.log(Level.WARNING, "Failed to clear session using reflection", e);
}
}
diff --git a/manager/src/main/java/org/openremote/manager/mqtt/MqttConnection.java b/manager/src/main/java/org/openremote/manager/mqtt/MqttConnection.java
index 8e33b658a..9602f403d 100644
--- a/manager/src/main/java/org/openremote/manager/mqtt/MqttConnection.java
+++ b/manager/src/main/java/org/openremote/manager/mqtt/MqttConnection.java
@@ -8,12 +8,8 @@ import org.openremote.container.security.keycloak.AccessTokenAuthContext;
import org.openremote.manager.security.ManagerKeycloakIdentityProvider;
import org.openremote.model.auth.OAuthClientCredentialsGrant;
import org.openremote.model.auth.OAuthGrant;
-import org.openremote.model.event.shared.SharedEvent;
import org.openremote.model.util.TextUtil;
-import java.util.HashMap;
-import java.util.Map;
-import java.util.function.Consumer;
import java.util.function.Supplier;
import java.util.logging.Level;
import java.util.logging.Logger;
@@ -26,19 +22,20 @@ import static org.openremote.model.Constants.KEYCLOAK_CLIENT_ID;
public class MqttConnection {
protected static final Logger LOG = Logger.getLogger(MqttConnection.class.getSimpleName());
- protected final String realm;
+ protected String realm;
protected String username; // This is OAuth clientId
protected String password;
protected boolean credentials;
protected final String clientId;
+ protected final boolean cleanSession;
protected Supplier<String> tokenSupplier;
protected ManagerKeycloakIdentityProvider identityProvider;
- public MqttConnection(ManagerKeycloakIdentityProvider identityProvider, String clientId, String realm, String username, String password) {
- this.realm = realm;
+ public MqttConnection(ManagerKeycloakIdentityProvider identityProvider, String clientId, String realm, String username, String password, boolean cleanSession) {
+ this.cleanSession = cleanSession;
this.clientId = clientId;
this.identityProvider = identityProvider;
- setCredentials(username, password);
+ setCredentials(realm, username, password);
}
public String getRealm() {
@@ -53,6 +50,10 @@ public class MqttConnection {
return this.password;
}
+ public boolean isCleanSession() {
+ return cleanSession;
+ }
+
public String getAccessToken() {
if (tokenSupplier == null) {
return null;
@@ -90,8 +91,9 @@ public class MqttConnection {
return credentials;
}
- public void setCredentials(String username, String password) {
+ public void setCredentials(String realm, String username, String password) {
+ this.realm = realm;
this.username = username;
this.password = password;
diff --git a/manager/src/main/java/org/openremote/manager/mqtt/ORAuthorizatorPolicy.java b/manager/src/main/java/org/openremote/manager/mqtt/ORAuthorizatorPolicy.java
index 4105f72be..fa3542882 100644
--- a/manager/src/main/java/org/openremote/manager/mqtt/ORAuthorizatorPolicy.java
+++ b/manager/src/main/java/org/openremote/manager/mqtt/ORAuthorizatorPolicy.java
@@ -55,11 +55,11 @@ public class ORAuthorizatorPolicy implements IAuthorizatorPolicy {
}
@SuppressWarnings({"rawtypes", "unchecked"})
- protected boolean verifyRights(Topic topic, String sessionId, String realm, String username, boolean isWrite) {
- MqttConnection connection = brokerService.clientIdConnectionMap.get(sessionId);
+ protected boolean verifyRights(Topic topic, String clientId, String realm, String username, boolean isWrite) {
+ MqttConnection connection = brokerService.clientIdConnectionMap.get(clientId);
if (connection == null) {
- LOG.warning("No connection found: sessionId=" + sessionId);
+ LOG.warning("No connection found: clientId=" + clientId);
return false;
}
diff --git a/manager/src/main/java/org/openremote/manager/mqtt/ORInterceptHandler.java b/manager/src/main/java/org/openremote/manager/mqtt/ORInterceptHandler.java
index e3abb7bc5..3a2dc9ac1 100644
--- a/manager/src/main/java/org/openremote/manager/mqtt/ORInterceptHandler.java
+++ b/manager/src/main/java/org/openremote/manager/mqtt/ORInterceptHandler.java
@@ -75,7 +75,7 @@ public class ORInterceptHandler extends AbstractInterceptHandler {
username = realmAndUsername[1];
}
- MqttConnection connection = new MqttConnection(identityProvider, msg.getClientID(), realm, username, password);
+ MqttConnection connection = new MqttConnection(identityProvider, msg.getClientID(), realm, username, password, msg.isCleanSession());
brokerService.addConnection(connection.getClientId(), connection);
// Notify all custom handlers
diff --git a/manager/src/main/java/org/openremote/manager/provisioning/ProvisioningService.java b/manager/src/main/java/org/openremote/manager/provisioning/ProvisioningService.java
index a53c4915e..575262476 100644
--- a/manager/src/main/java/org/openremote/manager/provisioning/ProvisioningService.java
+++ b/manager/src/main/java/org/openremote/manager/provisioning/ProvisioningService.java
@@ -19,29 +19,20 @@
*/
package org.openremote.manager.provisioning;
-import org.apache.commons.io.IOUtils;
import org.openremote.container.persistence.PersistenceService;
import org.openremote.manager.security.ManagerIdentityService;
import org.openremote.manager.web.ManagerWebService;
import org.openremote.model.Container;
import org.openremote.model.ContainerService;
-import org.openremote.model.asset.impl.WeatherAsset;
import org.openremote.model.provisioning.ProvisioningConfig;
-import org.openremote.model.provisioning.X509ProvisioningConfig;
-import org.openremote.model.provisioning.X509ProvisioningData;
-import org.openremote.model.provisioning.X509ProvisioningMessage;
-import org.openremote.model.security.ClientRole;
import org.openremote.model.util.ValueUtil;
-import java.io.ByteArrayInputStream;
-import java.io.IOException;
-import java.io.InputStream;
-import java.nio.charset.StandardCharsets;
-import java.security.cert.CertificateException;
+import javax.validation.ConstraintViolation;
+import javax.validation.ConstraintViolationException;
import java.security.cert.CertificateFactory;
-import java.security.cert.X509Certificate;
-import java.util.Collections;
import java.util.List;
+import java.util.Set;
+import java.util.logging.Level;
import java.util.logging.Logger;
public class ProvisioningService implements ContainerService {
@@ -77,34 +68,44 @@ public class ProvisioningService implements ContainerService {
}
- public List<ProvisioningConfig<?>> getProvisioningConfigs() {
- String caPemStr = null;
- try {
- caPemStr = IOUtils.toString(getClass().getResource("/org/openremote/test/provisioning/ca_long.pem"), StandardCharsets.UTF_8);
- } catch (IOException e) {
- e.printStackTrace();
- }
- return Collections.singletonList(
- new X509ProvisioningConfig().setData(
- new X509ProvisioningData()
- .setCACertPEM(caPemStr)
- ).setAssetTemplate(
- ValueUtil.asJSON(
- new WeatherAsset("Weather Asset")
- ).orElse("")
- ).setRealm("building")
- .setRestrictedUser(true)
- .setUserRoles(new ClientRole[] {
- ClientRole.WRITE_ASSETS,
- ClientRole.READ_ASSETS
- })
- );
-//
-// return persistenceService.doReturningTransaction(entityManager ->
-// entityManager.createQuery(
-// "select pc from " + ProvisioningConfig.class + " pc " +
-// "order by pc.name desc",
-// ProvisioningConfig.class)
-// .getResultList());
+ public <T extends ProvisioningConfig<?>> T merge(T provisioningConfig) {
+ return persistenceService.doReturningTransaction(entityManager -> {
+
+ // Do standard JSR-380 validation on the config
+ Set<ConstraintViolation<ProvisioningConfig<?>>> validationFailures = ValueUtil.validate(provisioningConfig);
+
+ if (validationFailures.size() > 0) {
+ String msg = "Provisioning config merge failed as failed constraint validation: config=" + provisioningConfig;
+ ConstraintViolationException ex = new ConstraintViolationException(validationFailures);
+ LOG.log(Level.WARNING, msg + ", exception=" + ex.getMessage(), ex);
+ throw ex;
+ }
+
+ T mergedConfig = entityManager.merge(provisioningConfig);
+ if (provisioningConfig.getId() != null) {
+ LOG.fine("Provisioning config updated: " + provisioningConfig);
+ } else {
+ LOG.fine("Provisioning config created: " + provisioningConfig);
+ }
+
+ return mergedConfig;
+ });
+ }
+
+ public void delete(Long id) {
+ persistenceService.doTransaction(entityManager -> {
+ ProvisioningConfig<?> provisioningConfig = entityManager.find(ProvisioningConfig.class, id);
+ if (provisioningConfig != null)
+ entityManager.remove(provisioningConfig);
+ });
+ }
+
+ public List<ProvisioningConfig> getProvisioningConfigs() {
+ return persistenceService.doReturningTransaction(entityManager ->
+ entityManager.createQuery(
+ "select pc from " + ProvisioningConfig.class.getSimpleName() + " pc " +
+ "order by pc.name desc",
+ ProvisioningConfig.class)
+ .getResultList());
}
}
diff --git a/manager/src/main/java/org/openremote/manager/provisioning/UserAssetProvisioningMQTTHandler.java b/manager/src/main/java/org/openremote/manager/provisioning/UserAssetProvisioningMQTTHandler.java
index e705bbae5..d102ea80b 100644
--- a/manager/src/main/java/org/openremote/manager/provisioning/UserAssetProvisioningMQTTHandler.java
+++ b/manager/src/main/java/org/openremote/manager/provisioning/UserAssetProvisioningMQTTHandler.java
@@ -217,6 +217,13 @@ public class UserAssetProvisioningMQTTHandler extends MQTTHandler {
return;
}
+ // Check if config is disabled
+ if (matchingConfig.isDisabled()) {
+ LOG.fine("Matching provisioning config is disabled for client certificate: topic=" + topic + ", connection=" + connection);
+ brokerService.publishMessage(getResponseTopic(topic), new ErrorResponseMessage(ErrorResponseMessage.Error.CONFIG_DISABLED), MqttQoS.AT_MOST_ONCE);
+ return;
+ }
+
// Validate unique ID
String certUniqueId = ProvisioningUtil.getSubjectCN(clientCertificate.getSubjectX500Principal());
String uniqueId = topicTokenIndexToString(topic, 1);
@@ -236,7 +243,7 @@ public class UserAssetProvisioningMQTTHandler extends MQTTHandler {
String realm = matchingConfig.getRealm();
// Get/create service user
- String serviceUsername = "PS-" + uniqueId;
+ String serviceUsername = ("ps-" + uniqueId).toLowerCase(); // Keycloak clients are case sensitive but pretends not to be so always force lowercase
User serviceUser;
try {
@@ -287,7 +294,7 @@ public class UserAssetProvisioningMQTTHandler extends MQTTHandler {
LOG.fine("Client successfully initialised: topic=" + topic + ", connection=" + connection);
// Update connection with service user credentials
- connection.setCredentials(serviceUser.getUsername(), serviceUser.getSecret());
+ connection.setCredentials(realm, serviceUser.getUsername(), serviceUser.getSecret());
brokerService.publishMessage(getResponseTopic(topic), new SuccessResponseMessage(realm, asset), MqttQoS.AT_MOST_ONCE);
}
@@ -301,7 +308,7 @@ public class UserAssetProvisioningMQTTHandler extends MQTTHandler {
try {
X509Certificate caCertificate = config.getCertificate();
if (caCertificate != null) {
- if (!caCertificate.getSubjectX500Principal().getName().equals(clientCertificate.getIssuerX500Principal().getName())) {
+ if (caCertificate.getSubjectX500Principal().getName().equals(clientCertificate.getIssuerX500Principal().getName())) {
LOG.fine("Client certificate issuer matches provisioning config CA certificate subject: connection=" + connection + ", config=" + config);
Date now = Date.from(timerService.getNow());
@@ -339,7 +346,8 @@ public class UserAssetProvisioningMQTTHandler extends MQTTHandler {
.setEnabled(true)
.setUsername(username);
- serviceUser = identityProvider.createUpdateUser(realm, serviceUser, null);
+ String secret = UniqueIdentifierGenerator.generateId();
+ serviceUser = identityProvider.createUpdateUser(realm, serviceUser, secret);
if (provisioningConfig.getUserRoles() != null && provisioningConfig.getUserRoles().length > 0) {
LOG.finer("Setting user roles: realm=" + realm + ", username=" + username + ", roles=" + Arrays.toString(provisioningConfig.getUserRoles()));
@@ -358,6 +366,8 @@ public class UserAssetProvisioningMQTTHandler extends MQTTHandler {
identityProvider.updateUserRoles(realm, serviceUser.getId(), null, RESTRICTED_USER_REALM_ROLE);
}
+ // Inject secret
+ serviceUser.setSecret(secret);
return serviceUser;
}
diff --git a/manager/src/main/resources/org/openremote/manager/setup/database/V20191202_01__Schema.sql b/manager/src/main/resources/org/openremote/manager/setup/database/V20191202_01__Schema.sql
index 5a4fe4c4d..873eb769f 100644
--- a/manager/src/main/resources/org/openremote/manager/setup/database/V20191202_01__Schema.sql
+++ b/manager/src/main/resources/org/openremote/manager/setup/database/V20191202_01__Schema.sql
@@ -88,12 +88,6 @@ create table USER_ASSET (
primary key (ASSET_ID, REALM, USER_ID)
);
-create table USER_CONFIGURATION (
- USER_ID varchar(36) not null,
- RESTRICTED boolean not null,
- primary key (USER_ID)
-);
-
create table NOTIFICATION (
ID int8 not null,
NAME varchar(255),
@@ -155,6 +149,21 @@ create table CONSOLE_APP_CONFIG (
primary key (ID)
);
+create table PROVISIONING_CONFIG (
+ ID int8 not null,
+ CREATED_ON timestamp with time zone not null,
+ DISABLED boolean not null default false,
+ LAST_MODIFIED timestamp with time zone not null,
+ NAME varchar(255) not null,
+ TYPE varchar(100) not null,
+ ROLES varchar(255)[] null,
+ REALM varchar(255) not null,
+ ASSET_TEMPLATE text null,
+ RESTRICTED_USER boolean not null default false,
+ DATA jsonb,
+ primary key (ID)
+);
+
/*
############################# FUNCTIONS #############################
*/
@@ -202,9 +211,6 @@ alter table TENANT_RULESET
alter table ASSET_RULESET
add foreign key (ASSET_ID) references ASSET (ID) on delete cascade;
-alter table USER_CONFIGURATION
- add foreign key (USER_ID) references PUBLIC.USER_ENTITY (ID) on delete cascade;
-
alter table USER_ASSET
add foreign key (USER_ID) references PUBLIC.USER_ENTITY (ID) on delete cascade;
@@ -214,6 +220,9 @@ alter table USER_ASSET
alter table USER_ASSET
add foreign key (REALM) references PUBLIC.REALM (NAME) on delete cascade;
+alter table PROVISIONING_CONFIG
+ add foreign key (REALM) references PUBLIC.REALM (NAME);
+
/*
############################# INDICES #############################
*/
diff --git a/manager/src/main/resources/org/openremote/manager/setup/database/V20211019_01__Schema.sql b/manager/src/main/resources/org/openremote/manager/setup/database/V20211019_01__Schema.sql
deleted file mode 100644
index f1e6a335b..000000000
--- a/manager/src/main/resources/org/openremote/manager/setup/database/V20211019_01__Schema.sql
+++ /dev/null
@@ -1 +0,0 @@
-drop table USER_CONFIGURATION
\ No newline at end of file
diff --git a/model/src/main/java/org/openremote/model/attribute/Attribute.java b/model/src/main/java/org/openremote/model/attribute/Attribute.java
index 41d3e7020..6a2a3da7e 100644
--- a/model/src/main/java/org/openremote/model/attribute/Attribute.java
+++ b/model/src/main/java/org/openremote/model/attribute/Attribute.java
@@ -323,7 +323,7 @@ public class Attribute<T> extends AbstractNameValueHolder<T> implements MetaHold
"name='" + name + '\'' +
", value='" + value + '\'' +
", timestamp='" + getTimestamp().orElse(0L) + '\'' +
- ", meta='" + getMeta().values().stream().map(MetaItem::toString).collect(Collectors.joining(",")) + '\'' +
+ ", meta='" + (meta == null ? "" : getMeta().values().stream().map(MetaItem::toString).collect(Collectors.joining(","))) + '\'' +
"} ";
}
@@ -366,9 +366,11 @@ public class Attribute<T> extends AbstractNameValueHolder<T> implements MetaHold
return false;
Attribute<?> that = (Attribute<?>) obj;
- return Objects.equals(timestamp, that.timestamp)
- && Objects.equals(meta, that.meta)
- && super.equals(obj);
+ boolean timestampMatches = Objects.equals(timestamp, that.timestamp);
+ boolean metaMatches = (meta == null && that.meta != null && that.meta.isEmpty()) || (that.meta == null && meta != null && meta.isEmpty()) || Objects.equals(meta, that.meta);
+ boolean superMatches = super.equals(obj);
+ boolean result = timestampMatches && metaMatches && superMatches;
+ return result;
}
public boolean equals(Object obj, Comparator<Attribute<?>> comparator) {
diff --git a/model/src/main/java/org/openremote/model/provisioning/ErrorResponseMessage.java b/model/src/main/java/org/openremote/model/provisioning/ErrorResponseMessage.java
index 6ec289772..62fc31123 100644
--- a/model/src/main/java/org/openremote/model/provisioning/ErrorResponseMessage.java
+++ b/model/src/main/java/org/openremote/model/provisioning/ErrorResponseMessage.java
@@ -19,6 +19,8 @@
*/
package org.openremote.model.provisioning;
+import com.fasterxml.jackson.annotation.JsonCreator;
+
public class ErrorResponseMessage extends ProvisioningMessage {
public enum Error {
@@ -35,6 +37,7 @@ public class ErrorResponseMessage extends ProvisioningMessage {
protected Error error;
+ @JsonCreator
public ErrorResponseMessage(Error error) {
this.error = error;
}
diff --git a/model/src/main/java/org/openremote/model/provisioning/ProvisioningConfig.java b/model/src/main/java/org/openremote/model/provisioning/ProvisioningConfig.java
index 8b9a8e0f9..8d407748f 100644
--- a/model/src/main/java/org/openremote/model/provisioning/ProvisioningConfig.java
+++ b/model/src/main/java/org/openremote/model/provisioning/ProvisioningConfig.java
@@ -21,34 +21,20 @@ package org.openremote.model.provisioning;
import com.fasterxml.jackson.annotation.JsonSubTypes;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
-import com.vladmihalcea.hibernate.type.array.EnumArrayType;
-import org.hibernate.annotations.Parameter;
-import org.hibernate.annotations.Type;
-import org.hibernate.annotations.TypeDef;
-import org.hibernate.annotations.TypeDefs;
+import org.openremote.model.Constants;
import org.openremote.model.security.ClientRole;
import javax.persistence.*;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;
+import javax.validation.constraints.Size;
import java.util.Arrays;
import java.util.Date;
import static javax.persistence.DiscriminatorType.STRING;
-import static org.openremote.model.Constants.*;
-
-@TypeDefs({
- @TypeDef(
- typeClass = EnumArrayType.class,
- defaultForType = ClientRole[].class,
- parameters = {
- @Parameter(
- name = EnumArrayType.SQL_ARRAY_TYPE,
- value = "client_role"
- )
- }
- )
-})
+import static org.openremote.model.Constants.PERSISTENCE_SEQUENCE_ID_GENERATOR;
+
+@Entity
@Table(name = "provisioning_config")
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
@DiscriminatorColumn(name = "TYPE", discriminatorType = STRING)
@@ -74,13 +60,15 @@ public abstract class ProvisioningConfig<T> {
protected Date lastModified;
@NotNull
- @Column(name = "NAME", nullable = false, columnDefinition = "text")
+ @Column(name = "NAME", nullable = false)
+ @Size(min = 3, max = 255, message = "{ProvisioningConfig.name.Size}")
protected String name;
- @Column(name = "TYPE", columnDefinition = "text")
+ @Column(name = "TYPE", nullable = false, updatable = false, insertable = false, length = 100, columnDefinition = "char(100)")
+ @Size(min = 3, max = 100, message = "{ProvisioningConfig.type.Size}")
protected String type;
- @Column(name = "REALM", columnDefinition = "text")
+ @Column(name = "REALM")
protected String realm;
@Column(name = "ASSET_TEMPLATE", columnDefinition = "text")
@@ -90,17 +78,18 @@ public abstract class ProvisioningConfig<T> {
protected boolean restrictedUser;
@Column(name = "ROLES", columnDefinition = "client_role[]")
+ @org.hibernate.annotations.Type(type = Constants.PERSISTENCE_STRING_ARRAY_TYPE)
+ @Enumerated(EnumType.STRING)
protected ClientRole[] userRoles;
@Column(name = "DISABLED", nullable = false)
- protected boolean disabled;
+ protected boolean disabled = false;
- /**
- * JSON serialisable data for a specific implementation
- */
- @Column(name = "DATA", columnDefinition = "jsonb")
- @org.hibernate.annotations.Type(type = PERSISTENCE_JSON_VALUE_TYPE)
- protected T data;
+ protected ProvisioningConfig() {}
+
+ protected ProvisioningConfig(String name) {
+ this.name = name;
+ }
public Long getId() {
return id;
@@ -114,6 +103,12 @@ public abstract class ProvisioningConfig<T> {
return lastModified;
}
+ @PreUpdate
+ @PrePersist
+ protected void updateLastModified() {
+ lastModified = new Date();
+ }
+
public String getName() {
return name;
}
@@ -163,14 +158,11 @@ public abstract class ProvisioningConfig<T> {
return this;
}
- public T getData() {
- return data;
- }
-
- public ProvisioningConfig<T> setData(T data) {
- this.data = data;
- return this;
- }
+ /**
+ * Implementors must annotate the data field with @Column as JPA (Hibernate) doesn't work with generic fields
+ */
+ public abstract T getData();
+ public abstract ProvisioningConfig<T> setData(T data);
public String getRealm() {
return realm;
@@ -190,11 +182,11 @@ public abstract class ProvisioningConfig<T> {
", name='" + name + '\'' +
", type='" + type + '\'' +
", realm='" + realm + '\'' +
- ", assetTemplate='" + assetTemplate + '\'' +
+ ", assetTemplateSet='" + (assetTemplate != null) + '\'' +
", restrictedUser=" + restrictedUser +
", userRoles=" + Arrays.toString(userRoles) +
", disabled=" + disabled +
- ", data=" + data +
+ ", data=" + getData() +
'}';
}
}
diff --git a/model/src/main/java/org/openremote/model/provisioning/SuccessResponseMessage.java b/model/src/main/java/org/openremote/model/provisioning/SuccessResponseMessage.java
index d6bd45e10..82a12bbd4 100644
--- a/model/src/main/java/org/openremote/model/provisioning/SuccessResponseMessage.java
+++ b/model/src/main/java/org/openremote/model/provisioning/SuccessResponseMessage.java
@@ -19,6 +19,7 @@
*/
package org.openremote.model.provisioning;
+import com.fasterxml.jackson.annotation.JsonCreator;
import org.openremote.model.asset.Asset;
public class SuccessResponseMessage extends ProvisioningMessage {
@@ -26,6 +27,7 @@ public class SuccessResponseMessage extends ProvisioningMessage {
protected String realm;
protected Asset<?> asset;
+ @JsonCreator
public SuccessResponseMessage(String realm, Asset<?> asset) {
this.realm = realm;
this.asset = asset;
diff --git a/model/src/main/java/org/openremote/model/provisioning/X509ProvisioningConfig.java b/model/src/main/java/org/openremote/model/provisioning/X509ProvisioningConfig.java
index a1197010d..254811a35 100644
--- a/model/src/main/java/org/openremote/model/provisioning/X509ProvisioningConfig.java
+++ b/model/src/main/java/org/openremote/model/provisioning/X509ProvisioningConfig.java
@@ -21,12 +21,15 @@ package org.openremote.model.provisioning;
import org.openremote.model.util.TextUtil;
+import javax.persistence.Column;
import javax.persistence.DiscriminatorValue;
import javax.persistence.Entity;
import javax.persistence.Transient;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
+import static org.openremote.model.Constants.PERSISTENCE_JSON_VALUE_TYPE;
+
@Entity
@DiscriminatorValue("x509")
public class X509ProvisioningConfig extends ProvisioningConfig<X509ProvisioningData> {
@@ -36,6 +39,28 @@ public class X509ProvisioningConfig extends ProvisioningConfig<X509ProvisioningD
@Transient boolean valid = true;
+ @Column(name = "DATA", columnDefinition = "jsonb")
+ @org.hibernate.annotations.Type(type = PERSISTENCE_JSON_VALUE_TYPE)
+ protected X509ProvisioningData data;
+
+ protected X509ProvisioningConfig() {}
+
+ @Override
+ public X509ProvisioningData getData() {
+ return data;
+ }
+
+ @Override
+ public ProvisioningConfig<X509ProvisioningData> setData(X509ProvisioningData data) {
+ this.data = data;
+ return this;
+ }
+
+ public X509ProvisioningConfig(String name, X509ProvisioningData data) {
+ super(name);
+ this.data = data;
+ }
+
public synchronized X509Certificate getCertificate() throws IllegalStateException, CertificateException {
if (!valid) {
return null;
diff --git a/model/src/main/java/org/openremote/model/provisioning/X509ProvisioningData.java b/model/src/main/java/org/openremote/model/provisioning/X509ProvisioningData.java
index d0734086c..7b0fcbb81 100644
--- a/model/src/main/java/org/openremote/model/provisioning/X509ProvisioningData.java
+++ b/model/src/main/java/org/openremote/model/provisioning/X509ProvisioningData.java
@@ -23,7 +23,6 @@ public class X509ProvisioningData {
protected String CACertPEM;
protected boolean ignoreExpiryDate;
- protected String overrideUniqueIdAttribute;
public String getCACertPEM() {
return CACertPEM;
@@ -43,21 +42,11 @@ public class X509ProvisioningData {
return this;
}
- public String getOverrideUniqueIdAttribute() {
- return overrideUniqueIdAttribute;
- }
-
- public X509ProvisioningData setOverrideUniqueIdAttribute(String overrideUniqueIdAttribute) {
- this.overrideUniqueIdAttribute = overrideUniqueIdAttribute;
- return this;
- }
-
@Override
public String toString() {
return getClass().getSimpleName() +"{" +
- "CACertPEM='" + CACertPEM + '\'' +
+ "CACertPEM='" + (CACertPEM != null ? CACertPEM.substring(0, 20) + "..." : null) + '\'' +
", ignoreExpiryDate=" + ignoreExpiryDate +
- ", overrideUniqueIdAttribute='" + overrideUniqueIdAttribute + '\'' +
'}';
}
}
diff --git a/model/src/main/java/org/openremote/model/provisioning/X509ProvisioningMessage.java b/model/src/main/java/org/openremote/model/provisioning/X509ProvisioningMessage.java
index 07f587739..9cbead08f 100644
--- a/model/src/main/java/org/openremote/model/provisioning/X509ProvisioningMessage.java
+++ b/model/src/main/java/org/openremote/model/provisioning/X509ProvisioningMessage.java
@@ -19,9 +19,12 @@
*/
package org.openremote.model.provisioning;
+import com.fasterxml.jackson.annotation.JsonCreator;
+
public class X509ProvisioningMessage extends ProvisioningMessage {
protected String cert;
+ @JsonCreator
public X509ProvisioningMessage(String cert) {
this.cert = cert;
}
diff --git a/mvp/mvp-docker-compose-awslogs.yml b/mvp/mvp-docker-compose-awslogs.yml
index 1a9bf0069..71cdcaf0a 100644
--- a/mvp/mvp-docker-compose-awslogs.yml
+++ b/mvp/mvp-docker-compose-awslogs.yml
@@ -125,7 +125,7 @@ services:
- deployment-data:/deployment
environment:
KEYCLOAK_PASSWORD: ${PASSWORD:-secret}
- KEYCLOAK_FRONTEND_URL: "${EXTERNAL_URL:-https://localhost}/auth"
+ KEYCLOAK_FRONTEND_URL: ${EXTERNAL_URL:-https://localhost}/auth
<<: *awslogs
postgresql:
diff --git a/mvp/mvp-docker-compose.yml b/mvp/mvp-docker-compose.yml
index 077529a1b..12ad3dc7a 100644
--- a/mvp/mvp-docker-compose.yml
+++ b/mvp/mvp-docker-compose.yml
@@ -116,7 +116,7 @@ services:
- deployment-data:/deployment
environment:
KEYCLOAK_PASSWORD: ${PASSWORD:-secret}
- KEYCLOAK_FRONTEND_URL: "${EXTERNAL_URL:-https://localhost}/auth"
+ KEYCLOAK_FRONTEND_URL: ${EXTERNAL_URL:-https://localhost}/auth
postgresql:
image: openremote/postgresql:${POSTGRESQL_VERSION:-9.6.21.0}
diff --git a/swarm/kube-docker-compose.yml b/swarm/kube-docker-compose.yml
index b01ced7e6..19df9f17c 100644
--- a/swarm/kube-docker-compose.yml
+++ b/swarm/kube-docker-compose.yml
@@ -148,7 +148,7 @@ services:
DB_PASSWORD: CHANGE_ME_DB_USER_PASSWORD
KEYCLOAK_USER: admin
PROXY_ADDRESS_FORWARDING: 'true'
- KEYCLOAK_FRONTEND_URL: '${EXTERNAL_URL:-https://localhost}/auth'
+ KEYCLOAK_FRONTEND_URL: ${EXTERNAL_URL:-https://localhost}/auth
# CHANGE THIS PASSWORD BEFORE STARTING THE STACK! THIS IS ONLY FOR DEMO!
KEYCLOAK_PASSWORD: ${SETUP_ADMIN_PASSWORD:-secret}
diff --git a/swarm/swarm-docker-compose.yml b/swarm/swarm-docker-compose.yml
index 90656a1f3..540f4bf3d 100644
--- a/swarm/swarm-docker-compose.yml
+++ b/swarm/swarm-docker-compose.yml
@@ -201,7 +201,7 @@ services:
# SETUP_ADMIN_PASSWORD: # Allow override on CLI
# Configure how Keycloak connects to the database
- KEYCLOAK_FRONTEND_URL: '${EXTERNAL_URL:-https://localhost}/auth'
+ KEYCLOAK_FRONTEND_URL: ${EXTERNAL_URL:-https://localhost}/auth
# CHANGE THIS PASSWORD BEFORE STARTING THE STACK! THIS IS ONLY FOR DEMO!
KEYCLOAK_PASSWORD: ${SETUP_ADMIN_PASSWORD:-secret}
diff --git a/test/src/main/resources/org/openremote/test/provisioning/ca_forged.key b/test/src/main/resources/org/openremote/test/provisioning/ca_forged.key
new file mode 100644
index 000000000..357b412a8
--- /dev/null
+++ b/test/src/main/resources/org/openremote/test/provisioning/ca_forged.key
@@ -0,0 +1,51 @@
+-----BEGIN RSA PRIVATE KEY-----
+MIIJKQIBAAKCAgEAwzWU9PTh67LhkCIDaVJWeVFexUzPfCufz4C0HXFcd+gCjTLK
+d3D+I3gA93BSTQV+6V4W/XjLjRhnCpDKrP5exwd55j7G6Phmho+YPCxXekqOszzS
+2oWA8rq2gFdpgB40R+Iw2J2xJ51yZfcgq+ozNpMl8uS8ioQqbpjf+CB8Tb6JTSE1
+CFt849ZksoGNA6HpxENS5D7e/6x73T3ecdleDAqXoze4EUh/tsySmbRkoEO8dfXG
+YL5309qvY50Ehc78yFpavr2JkhVOjFNJel5yFhcsHCcmScsZcboELa7f0q+3EV2F
+zYZdak+/3Fo+eohAaJYjH1BpeGBJoWuk5xHBSghOXPIO9HIkXyTTsxWnQOwabBc9
+08kdduj5qBDJ+AkP+EXv/8C1SSjbYlkNGoaTIf0RGaDLeNJhfUrlxkbuAy19celG
+TR4cFiazzHT6DYtTjX7J7b0lceGwsb2OIYQ53opaKnJvwuEXIAzcSD9qILJaEYpN
+IQL6Hq9kDRaHDTp25t76PIHPSvl8PwlHVehBS6adj1FIZtTF9oSmgdR9vVX7Oa68
+Lvc7KzvIt1AwZm8W+nXn8hBShvgnrrBDhqEmnBWAHJPI145PibFmQl0g1fq68AR9
+3b9uxo3EVbc1L6Dn5kD38zCQ0BO2GMqTTxk8JO5uMhJTiNZ7jg+7khnVSKECAwEA
+AQKCAgEAoIU4FvIjsNCowP/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zqlQbrbVC6gpv98XI6WL
+3A+C+VN4tk+HyGQzposMLWi8OfUWmxZsG/NpjIc8vJvkmljPTLA/J5wKyD0uFcgA
+y6Y0/6T77uEwpzEZ9JFGBzM8cqUGYcgjXv4Db1IJnXW7FoUuuzM/rfIytfj6hbUB
+Fbvhv7kNgZWWXdentyqTsRbPyq2IdfDrBEBO1H61/AxuaszYmyc/zvvVEU15dmLu
+QMaX3B+UB42RytfnZioP0APVVPSbnnGassoYkhvKuMuwNc5tUq3Bt2LUWyCiMCvi
+3iUJJX6VXQcpEQN3dOKOJnA2ynj5eNcLSOFlCFiEQKurxa357j5+4fNBsrNC
+-----END RSA PRIVATE KEY-----
diff --git a/test/src/main/resources/org/openremote/test/provisioning/ca_forged.pem b/test/src/main/resources/org/openremote/test/provisioning/ca_forged.pem
new file mode 100644
index 000000000..a47bba05f
--- /dev/null
+++ b/test/src/main/resources/org/openremote/test/provisioning/ca_forged.pem
@@ -0,0 +1,35 @@
+-----BEGIN CERTIFICATE-----
+MIIF/TCCA+WgAwIBAgIUJHvme1WGRKjsZhrt2hNDn2LerMYwDQYJKoZIhvcNAQEL
+BQAwgYwxCzAJBgNVBAYTAk5MMRYwFAYDVQQIDA1Ob3J0aCBCcmFiYW50MRIwEAYD
+VQQHDAlFaW5kaG92ZW4xEzARBgNVBAoMCk9wZW5SZW1vdGUxFjAUBgNVBAMMDW9w
+ZW5yZW1vdGUuaW8xJDAiBgkqhkiG9w0BCQEWFXN1cHBvcnRAb3BlbnJlbW90ZS5p
+bzAgFw0yMTEwMzExOTUzNDNaGA8yMDcxMDIxMTE5NTM0M1owgYwxCzAJBgNVBAYT
+Ak5MMRYwFAYDVQQIDA1Ob3J0aCBCcmFiYW50MRIwEAYDVQQHDAlFaW5kaG92ZW4x
+EzARBgNVBAoMCk9wZW5SZW1vdGUxFjAUBgNVBAMMDW9wZW5yZW1vdGUuaW8xJDAi
+BgkqhkiG9w0BCQEWFXN1cHBvcnRAb3BlbnJlbW90ZS5pbz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kvhmg89gulbgWvgnImyUWo2k8NE8djhgbGZvBivdQoG+YDCEgc3VJS998TmW
+RjMk9VigVJzXkFJchBOT22zwjSSj2ah9ZoilH9PsmuIqWMzUa8cY/kzE7Nh7B1nw
+Z+4wQjUhkxcI/h3we7ZF2Z8wL6j9QwS8NRfYhU9k+woipts7p/nxufScoagjuRFc
+X/C+Ka8d3nDXA4Zcl3StfCrzvKtZ8p0us94ROXOOHsjD/rZYWUvsazCYvRiNarss
+kOsDJ+dvDiIWTV9v3Ja75TDhlGuSuZUgH7Lhm0pnHrfB5yXPRotLUd5MkIb8ECDq
+tUU6Gn9MHjM01V5EJIIlB6rLw6nw3T22e56qEQ8GOTXSszbkzU1CTCfcMgG0DGPP
+A3JI01PRpu1sBAYoiXLMj6HfeGF2vBotgyBCg2zrdBUpHomF/MZuL21aqrHSeKjB
+zeRu72USLsesY3iWxBU3pmLk2p+rVgHGkUijfMrRghYtcQ6CG/faXqEeGFUm+4ZC
+IQ==
+-----END CERTIFICATE-----
diff --git a/test/src/main/resources/org/openremote/test/provisioning/ca_forged.srl b/test/src/main/resources/org/openremote/test/provisioning/ca_forged.srl
new file mode 100644
index 000000000..939fe3107
--- /dev/null
+++ b/test/src/main/resources/org/openremote/test/provisioning/ca_forged.srl
@@ -0,0 +1 @@
+51D5E62DB775B5F385BD3DB1094E55F2F48A9C7F
diff --git a/test/src/main/resources/org/openremote/test/provisioning/device4.csr b/test/src/main/resources/org/openremote/test/provisioning/device4.csr
new file mode 100644
index 000000000..ce6dda26b
--- /dev/null
+++ b/test/src/main/resources/org/openremote/test/provisioning/device4.csr
@@ -0,0 +1,17 @@
+-----BEGIN CERTIFICATE REQUEST-----
+MIICzDCCAbQCAQAwgYYxCzAJBgNVBAYTAk5MMRYwFAYDVQQIDA1Ob3J0aCBCcmFi
+YW50MRIwEAYDVQQHDAlFaW5kaG92ZW4xEzARBgNVBAoMCk9wZW5SZW1vdGUxEDAO
+BgNVBAMMB2RldmljZTQxJDAiBgkqhkiG9w0BCQEWFXN1cHBvcnRAb3BlbnJlbW90
+ZS5pbzCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAMzd5ZzgygNa+Bt9
+ZbTeIuGLlsQ0ecWTfOMy0t4ByJkA/rsfQ8/twBPoCqzXY0MGXu/C6oevIFTYffcy
+4f4yiO5qrQAjjUBt1N45lK0ae5ge+G898++ufhhNNNIqwIXdRtsiSY9mfxMwrCly
+zhPgGZhls6SITsz61im6y7B2gsy5O9j8Ame4wgmISZfo4G3A1ObEFXzWBWNRDnhQ
+Rx8JemdCwRmw3ow0kCmKMdReGyJZVEmMEFAnU6YmgxVOFy0VZO/6OhvwhJWI8f8K
+qqc6Qd548UWEoopXiFegRClyKiuQ7U7qBjsnpOO/pV4ixCZFSMdPvBs1HsyeTpJR
+JobjSLECAwEAAaAAMA0GCSqGSIb3DQEBCwUAA4IBAQCZg3lf3g7Xl3w5poQAhwig
+pKkAzijyRSVLp741/pJMFmVB2x8++TW2b8zkFsRY9+aNUQM0f6JqAiqsDdb6RMWk
+AInYZETLE5vn9v0qeMyB77hulxfn5jZBHXuDfuh6YKhM7QUc7WDu1IO7gAxWN2U7
+mZ/KX/gmqa6kBNxeKYK2jy72J6OMfJePIUAC205Qvxgmi16VsF2Beu6CQgifteE4
+jR6/msD8jj9XkyKSQo7lmNJ2OdduboqEfUOoo60/MpZahJPu0WpPXRpY0K8Ld7mr
+Sav2VtjRgHHCY8PHpI6/39FhepEprWccquHK39Rm4oE/Ve3mF2RjssG1u22EZFb3
+-----END CERTIFICATE REQUEST-----
diff --git a/test/src/main/resources/org/openremote/test/provisioning/device4.key b/test/src/main/resources/org/openremote/test/provisioning/device4.key
new file mode 100644
index 000000000..a7b0bdc20
--- /dev/null
+++ b/test/src/main/resources/org/openremote/test/provisioning/device4.key
@@ -0,0 +1,27 @@
+-----BEGIN RSA PRIVATE KEY-----
+MIIEpQIBAAKCAQEAzN3lnODKA1r4G31ltN4i4YuWxDR5xZN84zLS3gHImQD+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R6bXjffnO42IajjVdnZDsxzwdXn/f1FWgV
+27N379jexMWKmWr5KAjgvWmd5A2kel3gyVP7696lmUVLGd4oaw87+4aGDyHzkmlr
+LxYofy2Jc4DHVz5xH8npClf1AoGAUwVJCf9fngKPjB9k8yhsU0l+TvS+qVTY2zIZ
+LE+JQ1o/Va9MBZy+9JEZS/EiGbxPPrw8RFaASufAX9ekaZPH1xyAYnTJwkC0T+SI
+xdHpHaO5Ke800N7dygpvd0PyhxFTS7pQ9zioAEhoy5eDRY7xDZmg5Pw5l2nBi9Ep
+Mr92g/kCgYEAuZs+rSQkC46G+oA5STAh0ILnvrVYcitx567YJsvf4llZXz4o3Gic
+BOAHC9JF6c6dKlRxVPVQpEM9N69ky65R6/1WucHPao4NwIFSp8uyG6kjgzh138c3
+Gtd3GldFihK+sogEXZT7WolXSYxkJ4xpglh1M5SFDaVTkQPIGk8OouY=
+-----END RSA PRIVATE KEY-----
diff --git a/test/src/main/resources/org/openremote/test/provisioning/device4_forged.pem b/test/src/main/resources/org/openremote/test/provisioning/device4_forged.pem
new file mode 100644
index 000000000..e39013897
--- /dev/null
+++ b/test/src/main/resources/org/openremote/test/provisioning/device4_forged.pem
@@ -0,0 +1,27 @@
+-----BEGIN CERTIFICATE-----
+MIIEnTCCAoUCFFHV5i23dbXzhb09sQlOVfL0ipx/MA0GCSqGSIb3DQEBCwUAMIGM
+MQswCQYDVQQGEwJOTDEWMBQGA1UECAwNTm9ydGggQnJhYmFudDESMBAGA1UEBwwJ
+RWluZGhvdmVuMRMwEQYDVQQKDApPcGVuUmVtb3RlMRYwFAYDVQQDDA1vcGVucmVt
+b3RlLmlvMSQwIgYJKoZIhvcNAQkBFhVzdXBwb3J0QG9wZW5yZW1vdGUuaW8wIBcN
+MjExMDMxMTk1NjMwWhgPMjA3MTAyMTExOTU2MzBaMIGGMQswCQYDVQQGEwJOTDEW
+MBQGA1UECAwNTm9ydGggQnJhYmFudDESMBAGA1UEBwwJRWluZGhvdmVuMRMwEQYD
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+gQUwJpwqmnTWada6Ur0qCJkUlZL2Dh9efOeuuR61h1b1jxJGz91FN/
+v4wJgWM964j/5cbgNFhq1h2NrCzIOXl5n7k7t4h5wnV9RaHadPtJKmuxxULZOXMQ
+ExnQifI8vEQCVEsSyGPIOxc8O7YKZMto5awJyOnN/neT
+-----END CERTIFICATE-----
diff --git a/test/src/test/groovy/org/openremote/test/mqtt/MqttBrokerTest.groovy b/test/src/test/groovy/org/openremote/test/mqtt/MqttBrokerTest.groovy
index 8d564b255..b91fe8378 100644
--- a/test/src/test/groovy/org/openremote/test/mqtt/MqttBrokerTest.groovy
+++ b/test/src/test/groovy/org/openremote/test/mqtt/MqttBrokerTest.groovy
@@ -59,7 +59,7 @@ class MqttBrokerTest extends Specification implements ManagerContainerTrait {
when: "a mqtt client connects with invalid credentials"
def wrongUsername = "master:" + KeycloakTestSetup.serviceUserId
- MQTT_IOClient client = new MQTT_IOClient(mqttClientId, mqttHost, mqttPort, false, new UsernamePassword(wrongUsername, password), null)
+ MQTT_IOClient client = new MQTT_IOClient(mqttClientId, mqttHost, mqttPort, false, true, new UsernamePassword(wrongUsername, password), null)
client.connect()
then: "the client connection status should be in error"
@@ -70,7 +70,7 @@ class MqttBrokerTest extends Specification implements ManagerContainerTrait {
when: "a mqtt client connects with valid credentials"
client.disconnect()
mqttClientId = UniqueIdentifierGenerator.generateId()
- client = new MQTT_IOClient(mqttClientId, mqttHost, mqttPort, false, new UsernamePassword(username, password), null)
+ client = new MQTT_IOClient(mqttClientId, mqttHost, mqttPort, false, true, new UsernamePassword(username, password), null)
client.connect()
then: "mqtt connection should exist"
diff --git a/test/src/test/groovy/org/openremote/test/provisioning/UserAndAssetProvisioningTest.groovy b/test/src/test/groovy/org/openremote/test/provisioning/UserAndAssetProvisioningTest.groovy
index 738d357ac..9b7d7365e 100644
--- a/test/src/test/groovy/org/openremote/test/provisioning/UserAndAssetProvisioningTest.groovy
+++ b/test/src/test/groovy/org/openremote/test/provisioning/UserAndAssetProvisioningTest.groovy
@@ -20,41 +20,31 @@
package org.openremote.test.provisioning
import io.moquette.BrokerConstants
-import org.junit.Ignore
-import org.openremote.agent.protocol.mqtt.MQTTAgent
-import org.openremote.agent.protocol.mqtt.MQTTAgentLink
import org.openremote.agent.protocol.mqtt.MQTTMessage
-import org.openremote.agent.protocol.mqtt.MQTTProtocol
import org.openremote.agent.protocol.mqtt.MQTT_IOClient
-import org.openremote.agent.protocol.simulator.SimulatorProtocol
import org.openremote.container.util.UniqueIdentifierGenerator
-import org.openremote.manager.agent.AgentService
import org.openremote.manager.asset.AssetProcessingService
import org.openremote.manager.asset.AssetStorageService
import org.openremote.manager.event.ClientEventService
+import org.openremote.manager.mqtt.DefaultMQTTHandler
import org.openremote.manager.mqtt.MqttBrokerService
import org.openremote.manager.provisioning.ProvisioningService
-import org.openremote.manager.provisioning.UserAssetProvisioningMQTTHandler
+import org.openremote.manager.security.ManagerIdentityService
import org.openremote.manager.setup.SetupService
-import org.openremote.model.Constants
-import org.openremote.model.asset.agent.Agent
+import org.openremote.model.asset.AssetEvent
import org.openremote.model.asset.agent.ConnectionStatus
-import org.openremote.model.asset.agent.Protocol
-import org.openremote.model.asset.impl.ThingAsset
import org.openremote.model.asset.impl.WeatherAsset
import org.openremote.model.attribute.Attribute
import org.openremote.model.attribute.AttributeEvent
import org.openremote.model.attribute.MetaItem
-import org.openremote.model.auth.UsernamePassword
-import org.openremote.model.provisioning.ErrorResponseMessage
-import org.openremote.model.provisioning.ProvisioningMessage
-import org.openremote.model.provisioning.SuccessResponseMessage
-import org.openremote.model.provisioning.X509ProvisioningConfig
-import org.openremote.model.provisioning.X509ProvisioningData
-import org.openremote.model.provisioning.X509ProvisioningMessage
+import org.openremote.model.event.shared.SharedEvent
+import org.openremote.model.provisioning.*
+import org.openremote.model.security.ClientRole
+import org.openremote.model.security.User
import org.openremote.model.util.ValueUtil
+import org.openremote.model.value.MetaItemType
+import org.openremote.model.value.ValueType
import org.openremote.test.ManagerContainerTrait
-import org.openremote.test.setup.KeycloakTestSetup
import org.openremote.test.setup.ManagerTestSetup
import spock.lang.Specification
import spock.util.concurrent.PollingConditions
@@ -65,11 +55,9 @@ import static org.openremote.container.util.MapAccess.getInteger
import static org.openremote.container.util.MapAccess.getString
import static org.openremote.manager.mqtt.MqttBrokerService.MQTT_SERVER_LISTEN_HOST
import static org.openremote.manager.mqtt.MqttBrokerService.MQTT_SERVER_LISTEN_PORT
-import static org.openremote.model.value.MetaItemType.AGENT_LINK
-import static org.openremote.model.value.ValueType.NUMBER
import static org.openremote.manager.provisioning.UserAssetProvisioningMQTTHandler.*
+import static org.openremote.model.value.ValueType.NUMBER
-@Ignore
class UserAndAssetProvisioningTest extends Specification implements ManagerContainerTrait {
@SuppressWarnings("GroovyAccessibility")
@@ -83,41 +71,67 @@ class UserAndAssetProvisioningTest extends Specification implements ManagerConta
def assetStorageService = container.getService(AssetStorageService.class)
def provisioningService = container.getService(ProvisioningService.class)
def mqttBrokerService = container.getService(MqttBrokerService.class)
+ def clientEventService = container.getService(ClientEventService.class)
def assetProcessingService = container.getService(AssetProcessingService.class)
+ def identityService = container.getService(ManagerIdentityService.class)
def managerTestSetup = container.getService(SetupService.class).getTaskOfType(ManagerTestSetup.class)
- def keycloakTestSetup = container.getService(SetupService.class).getTaskOfType(KeycloakTestSetup.class)
def mqttHost = getString(container.getConfig(), MQTT_SERVER_LISTEN_HOST, BrokerConstants.HOST)
def mqttPort = getInteger(container.getConfig(), MQTT_SERVER_LISTEN_PORT, BrokerConstants.PORT)
+ and: "an internal attribute event subscriber is added for test validation purposes"
+ List<AttributeEvent> internalAttributeEvents = []
+ Consumer<AttributeEvent> internalConsumer = { ev ->
+ internalAttributeEvents.add(ev)
+ }
+ clientEventService.addInternalSubscription(AttributeEvent.class, null, internalConsumer)
+
+ // TODO: Switch to use provisioning resource once implemented
when: "a provisioning realm config is added to the system"
- // TODO: implement config persistence and resource implementation
-// def provisioningConfig = new X509ProvisioningConfig().setData(
-// new X509ProvisioningData()
-// .setCACertPEM("")
-// ).setAssetTemplate(
-// ValueUtil.asJSON(
-// new WeatherAsset("Weather Asset")
-// ).orElse("")
-// )
+ def provisioningConfig = new X509ProvisioningConfig("Valid Test Config",
+ new X509ProvisioningData()
+ .setCACertPEM(getClass().getResource("/org/openremote/test/provisioning/ca_long.pem").text)
+ ).setAssetTemplate(
+ ValueUtil.asJSON(
+ new WeatherAsset("Weather Asset")
+ .addAttributes(
+ new Attribute<>("customAttribute", NUMBER).addMeta(
+ new MetaItem<>(MetaItemType.ACCESS_RESTRICTED_READ),
+ new MetaItem<>(MetaItemType.ACCESS_RESTRICTED_WRITE)
+ ),
+ new Attribute<>("serialNumber", ValueType.TEXT, UNIQUE_ID_PLACEHOLDER)
+ )
+ ).orElse("")
+ ).setRealm("building")
+ .setRestrictedUser(true)
+ .setUserRoles([
+ ClientRole.WRITE_ASSETS,
+ ClientRole.WRITE_ATTRIBUTES,
+ ClientRole.READ_ASSETS
+ ] as ClientRole[])
+ provisioningConfig = provisioningService.merge(provisioningConfig)
then: "then the config should be available in the system"
conditions.eventually {
- assert provisioningService.getProvisioningConfigs().size() == 1
- assert provisioningService.getProvisioningConfigs().get(0) instanceof X509ProvisioningConfig
- assert ((X509ProvisioningConfig)provisioningService.getProvisioningConfigs().get(0)).getData() != null
- //assert ((X509ProvisioningConfig)provisioningService.getProvisioningConfigs().get(0)).getData().getCACertPEM() == provisioningConfig.getData().getCACertPEM()
+ def storedConfigs = provisioningService.getProvisioningConfigs()
+ assert storedConfigs.size() == 1
+ assert storedConfigs.get(0) instanceof X509ProvisioningConfig
+ assert ((X509ProvisioningConfig)storedConfigs.get(0)).getData() != null
+ assert ((X509ProvisioningConfig)storedConfigs.get(0)).getData().getCACertPEM() == provisioningConfig.getData().getCACertPEM()
}
when: "a mqtt client connects"
- def device1UniqueId = "Device1SerialNumber"
- def mqttClientId = UniqueIdentifierGenerator.generateId()
- MQTT_IOClient client = new MQTT_IOClient(mqttClientId, mqttHost, mqttPort, false, null, null)
- client.connect()
+ def device1UniqueId = "device1"
+ def mqttDevice1ClientId = UniqueIdentifierGenerator.generateId()
+ List<String> subscribeFailures = []
+ Consumer<String> subscribeFailureCallback = {String topic -> subscribeFailures.add(topic)}
+ MQTT_IOClient device1Client = new MQTT_IOClient(mqttDevice1ClientId, mqttHost, mqttPort, false, false, null, null)
+ device1Client.setTopicSubscribeFailureConsumer(subscribeFailureCallback)
+ device1Client.connect()
then: "mqtt connection should exist"
conditions.eventually {
- assert client.getConnectionStatus() == ConnectionStatus.CONNECTED
- assert mqttBrokerService.clientIdConnectionMap.get(mqttClientId) != null
+ assert device1Client.getConnectionStatus() == ConnectionStatus.CONNECTED
+ assert mqttBrokerService.clientIdConnectionMap.get(mqttDevice1ClientId) != null
}
when: "the client subscribes to the provisioning endpoints"
@@ -127,30 +141,419 @@ class UserAndAssetProvisioningTest extends Specification implements ManagerConta
}
def device1RequestTopic = "$PROVISIONING_TOKEN/$device1UniqueId/$REQUEST_TOKEN".toString()
def device1ResponseTopic = "$PROVISIONING_TOKEN/$device1UniqueId/$RESPONSE_TOKEN".toString()
- client.addMessageConsumer(device1ResponseTopic, device1MessageConsumer)
+ device1Client.addMessageConsumer(device1ResponseTopic, device1MessageConsumer)
then: "the subscriptions should succeed"
conditions.eventually {
- assert client.topicConsumerMap.get(device1ResponseTopic) != null
- assert client.topicConsumerMap.get(device1ResponseTopic).size() == 1
- assert mqttBrokerService.clientIdConnectionMap.get(mqttClientId) != null
+ assert device1Client.topicConsumerMap.get(device1ResponseTopic) != null
+ assert device1Client.topicConsumerMap.get(device1ResponseTopic).size() == 1
+ assert mqttBrokerService.clientIdConnectionMap.get(mqttDevice1ClientId) != null
}
when: "the client publishes a valid x509 certificate that has been signed by the CA stored in the provisioning config"
- client.sendMessage(
+ device1Client.sendMessage(
new MQTTMessage<String>(device1RequestTopic, ValueUtil.asJSON(
new X509ProvisioningMessage(getClass().getResource("/org/openremote/test/provisioning/device1.pem").text)
).orElse(null))
)
- then: "the broker should have published to the response topic a success message"
+ then: "the broker should have published to the response topic a success message containing the provisioned asset"
conditions.eventually {
assert device1Responses.size() == 1
assert device1Responses.get(0) instanceof SuccessResponseMessage
assert ((SuccessResponseMessage)device1Responses.get(0)).realm == managerTestSetup.realmBuildingTenant
- assert ((SuccessResponseMessage)device1Responses.get(0)).asset != null
+ def asset = ((SuccessResponseMessage)device1Responses.get(0)).asset
+ assert asset != null
+ assert asset instanceof WeatherAsset
+ assert asset.getAttribute("serialNumber").flatMap{it.getValue()}.orElse(null) == device1UniqueId
+ }
+
+ when: "the client then subscribes to attribute events for the generated asset and asset events for all assets"
+ def asset = ((SuccessResponseMessage)device1Responses.get(0)).asset
+ def assetSubscriptionTopic = "$provisioningConfig.realm/$mqttDevice1ClientId/$DefaultMQTTHandler.ASSET_TOPIC/#".toString()
+ def attributeSubscriptionTopic = "$provisioningConfig.realm/$mqttDevice1ClientId/$DefaultMQTTHandler.ATTRIBUTE_TOPIC/+/$asset.id".toString()
+ List<AssetEvent> assetEvents = []
+ List<AttributeEvent> attributeEvents = []
+ Consumer<MQTTMessage<String>> eventConsumer = { MQTTMessage<String> msg ->
+ def event = ValueUtil.parse(msg.payload, SharedEvent.class).orElse(null)
+ if (event instanceof AssetEvent) {
+ assetEvents.add(event as AssetEvent)
+ } else {
+ attributeEvents.add(event as AttributeEvent)
+ }
+ }
+ device1Client.addMessageConsumer(assetSubscriptionTopic, eventConsumer)
+ device1Client.addMessageConsumer(attributeSubscriptionTopic, eventConsumer)
+
+ then: "the subscriptions should be in place"
+ conditions.eventually {
+ assert device1Client.topicConsumerMap.get(assetSubscriptionTopic) != null
+ assert device1Client.topicConsumerMap.get(attributeSubscriptionTopic) != null
+ assert device1Client.topicConsumerMap.get(assetSubscriptionTopic).size() == 1
+ assert device1Client.topicConsumerMap.get(attributeSubscriptionTopic).size() == 1
+ assert mqttBrokerService.clientIdConnectionMap.get(mqttDevice1ClientId) != null
+ assert clientEventService.eventSubscriptions.sessionSubscriptionIdMap.containsKey(mqttDevice1ClientId)
+ assert clientEventService.eventSubscriptions.sessionSubscriptionIdMap.get(mqttDevice1ClientId).size() == 2
+ }
+
+ when: "the client updates one of the provisioned asset's attributes"
+ device1Client.sendMessage(
+ new MQTTMessage<String>(
+ "$provisioningConfig.realm/$mqttDevice1ClientId/$DefaultMQTTHandler.ATTRIBUTE_WRITE_TOPIC",
+ ValueUtil.asJSON(new AttributeEvent(asset.id, "customAttribute", 99d)).orElse(null)
+ )
+ )
+
+ then: "the attribute should have been updated"
+ conditions.eventually {
+ asset = assetStorageService.find(asset.id)
+ assert asset.getAttribute("customAttribute").flatMap{it.getValue()}.orElse(0d) == 99d
+ }
+
+ and: "the client should have been notified about the attribute change"
+ conditions.eventually {
+ assert attributeEvents.size() == 1
+ assert attributeEvents.get(0).assetId == asset.id
+ assert attributeEvents.get(0).attributeName == "customAttribute"
+ assert attributeEvents.get(0).value.orElse(0d) == 99d
+ }
+
+ when: "the provisioned asset is modified"
+ asset.name = "New Asset Name"
+ asset = assetStorageService.merge(asset)
+
+ then: "the client should have been notified about the asset change and all attributes should have generated an attribute event"
+ conditions.eventually {
+ assert assetEvents.size() == 1
+ assert assetEvents.get(0).assetId == asset.id
+ assert assetEvents.get(0).assetName == asset.name
+ }
+
+ when: "another asset's attribute is updated within the system"
+ assetProcessingService.sendAttributeEvent(
+ new AttributeEvent(managerTestSetup.apartment2LivingroomId, "lightSwitch", true)
+ )
+
+ then: "the internal consumer should have been notified"
+ conditions.eventually {
+ assert internalAttributeEvents.size() == 2
+ assert internalAttributeEvents.get(1).assetId == managerTestSetup.apartment2LivingroomId
+ assert internalAttributeEvents.get(1).attributeName == "lightSwitch"
+ assert internalAttributeEvents.get(1).value.orElse(false)
+ }
+
+ and: "the client should not have been notified"
+ conditions.eventually {
+ assert attributeEvents.size() == 1
+ }
+
+ when: "the client disconnects"
+ device1Client.disconnect()
+
+ then: "all subscriptions should be removed"
+ conditions.eventually {
+ assert mqttBrokerService.clientIdConnectionMap.get(mqttDevice1ClientId) == null
+ assert !clientEventService.eventSubscriptions.sessionSubscriptionIdMap.containsKey(mqttDevice1ClientId)
+ }
+
+ when: "the client reconnects"
+ device1Client.connect()
+
+ then: "the client should be connected and subscriptions reset"
+ conditions.eventually {
+ assert device1Client.getConnectionStatus() == ConnectionStatus.CONNECTED
+ assert mqttBrokerService.clientIdConnectionMap.get(mqttDevice1ClientId) != null
+ }
+
+ and: "the provisioning subscription should be re-instated but the attribute and asset subscriptions should fail"
+ conditions.eventually {
+ assert device1Client.topicConsumerMap.get(assetSubscriptionTopic) == null
+ assert device1Client.topicConsumerMap.get(attributeSubscriptionTopic) == null
+ assert mqttBrokerService.clientIdConnectionMap.get(mqttDevice1ClientId) != null
+ assert !clientEventService.eventSubscriptions.sessionSubscriptionIdMap.containsKey(mqttDevice1ClientId)
+ assert subscribeFailures.size() == 2
+ assert subscribeFailures.contains(assetSubscriptionTopic)
+ assert subscribeFailures.contains(attributeSubscriptionTopic)
+ }
+
+ when: "the client re-authenticates"
+ device1Responses.clear()
+ device1Client.sendMessage(
+ new MQTTMessage<String>(device1RequestTopic, ValueUtil.asJSON(
+ new X509ProvisioningMessage(getClass().getResource("/org/openremote/test/provisioning/device1.pem").text)
+ ).orElse(null))
+ )
+
+ then: "the broker should have published to the response topic a success message containing the provisioned asset"
+ conditions.eventually {
+ assert device1Responses.size() == 1
+ assert device1Responses.get(0) instanceof SuccessResponseMessage
+ assert ((SuccessResponseMessage)device1Responses.get(0)).realm == managerTestSetup.realmBuildingTenant
+ asset = ((SuccessResponseMessage)device1Responses.get(0)).asset
+ assert asset != null
+ assert asset instanceof WeatherAsset
+ assert asset.getAttribute("serialNumber").flatMap{it.getValue()}.orElse(null) == device1UniqueId
+ }
+
+ when: "the client subscribes again to the asset and attributes"
+ device1Client.addMessageConsumer(assetSubscriptionTopic, eventConsumer)
+ device1Client.addMessageConsumer(attributeSubscriptionTopic, eventConsumer)
+
+ then: "the subscriptions should be in place"
+ conditions.eventually {
+ assert device1Client.topicConsumerMap.get(assetSubscriptionTopic) != null
+ assert device1Client.topicConsumerMap.get(attributeSubscriptionTopic) != null
+ assert device1Client.topicConsumerMap.get(assetSubscriptionTopic).size() == 1
+ assert device1Client.topicConsumerMap.get(attributeSubscriptionTopic).size() == 1
+ assert mqttBrokerService.clientIdConnectionMap.get(mqttDevice1ClientId) != null
+ assert clientEventService.eventSubscriptions.sessionSubscriptionIdMap.containsKey(mqttDevice1ClientId)
+ assert clientEventService.eventSubscriptions.sessionSubscriptionIdMap.get(mqttDevice1ClientId).size() == 2
+ }
+
+ when: "a second device connects"
+ def deviceNUniqueId = "device2"
+ def deviceNRequestTopic = "$PROVISIONING_TOKEN/$deviceNUniqueId/$REQUEST_TOKEN".toString()
+ def deviceNResponseTopic = "$PROVISIONING_TOKEN/$deviceNUniqueId/$RESPONSE_TOKEN".toString()
+ def mqttDeviceNClientId = UniqueIdentifierGenerator.generateId()
+ MQTT_IOClient deviceNClient = new MQTT_IOClient(mqttDeviceNClientId, mqttHost, mqttPort, false, false, null, null)
+ deviceNClient.setTopicSubscribeFailureConsumer(subscribeFailureCallback)
+ deviceNClient.connect()
+
+ then: "mqtt connection should exist"
+ conditions.eventually {
+ assert deviceNClient.getConnectionStatus() == ConnectionStatus.CONNECTED
+ assert mqttBrokerService.clientIdConnectionMap.get(mqttDeviceNClientId) != null
+ }
+
+ when: "the client subscribes to the provisioning endpoints"
+ List<ProvisioningMessage> deviceNResponses = []
+ Consumer<MQTTMessage<String>> deviceNMessageConsumer = { MQTTMessage<String> msg ->
+ deviceNResponses.add(ValueUtil.parse(msg.payload, ProvisioningMessage.class).orElse(null))
+ }
+ deviceNClient.addMessageConsumer(deviceNResponseTopic, deviceNMessageConsumer)
+
+ then: "the subscriptions should succeed"
+ conditions.eventually {
+ assert deviceNClient.topicConsumerMap.get(deviceNResponseTopic) != null
+ assert deviceNClient.topicConsumerMap.get(deviceNResponseTopic).size() == 1
+ assert mqttBrokerService.clientIdConnectionMap.get(mqttDeviceNClientId) != null
+ }
+
+ when: "the client publishes an expired but valid x509 certificate that has been signed by the CA stored in the provisioning config"
+ deviceNClient.sendMessage(
+ new MQTTMessage<String>(deviceNRequestTopic, ValueUtil.asJSON(
+ new X509ProvisioningMessage(getClass().getResource("/org/openremote/test/provisioning/device2_expired.pem").text)
+ ).orElse(null))
+ )
+
+ then: "the broker should have published to the response topic an error message"
+ conditions.eventually {
+ assert deviceNResponses.size() == 1
+ assert deviceNResponses.get(0) instanceof ErrorResponseMessage
+ assert ((ErrorResponseMessage)deviceNResponses.get(0)).error == ErrorResponseMessage.Error.UNAUTHORIZED
+ }
+
+ when: "the client disconnects"
+ deviceNClient.removeAllMessageConsumers()
+ deviceNClient.disconnect()
+
+ then: "the connection should be removed from the broker"
+ conditions.eventually {
+ assert mqttBrokerService.clientIdConnectionMap.get(mqttDeviceNClientId) == null
+ }
+
+ when: "another device connects"
+ deviceNResponses.clear()
+ deviceNUniqueId = "device4"
+ deviceNRequestTopic = "$PROVISIONING_TOKEN/$deviceNUniqueId/$REQUEST_TOKEN".toString()
+ deviceNResponseTopic = "$PROVISIONING_TOKEN/$deviceNUniqueId/$RESPONSE_TOKEN".toString()
+ deviceNClient.connect()
+
+ then: "mqtt connection should exist"
+ conditions.eventually {
+ assert deviceNClient.getConnectionStatus() == ConnectionStatus.CONNECTED
+ assert mqttBrokerService.clientIdConnectionMap.get(mqttDeviceNClientId) != null
+ }
+
+ when: "the client subscribes to the provisioning endpoints"
+ deviceNClient.addMessageConsumer(deviceNResponseTopic, deviceNMessageConsumer)
+
+ then: "the subscriptions should succeed"
+ conditions.eventually {
+ assert deviceNClient.topicConsumerMap.get(deviceNResponseTopic) != null
+ assert deviceNClient.topicConsumerMap.get(deviceNResponseTopic).size() == 1
+ assert mqttBrokerService.clientIdConnectionMap.get(mqttDeviceNClientId) != null
+ }
+
+ when: "the client publishes a forged x509 certificate that has been signed by a forged CA"
+ deviceNClient.sendMessage(
+ new MQTTMessage<String>(deviceNRequestTopic, ValueUtil.asJSON(
+ new X509ProvisioningMessage(getClass().getResource("/org/openremote/test/provisioning/device4_forged.pem").text)
+ ).orElse(null))
+ )
+
+ then: "the broker should have published to the response topic an error message"
+ conditions.eventually {
+ assert deviceNResponses.size() == 1
+ assert deviceNResponses.get(0) instanceof ErrorResponseMessage
+ assert ((ErrorResponseMessage)deviceNResponses.get(0)).error == ErrorResponseMessage.Error.UNAUTHORIZED
+ }
+
+ when: "the client disconnects"
+ deviceNClient.removeAllMessageConsumers()
+ deviceNClient.disconnect()
+
+ then: "the connection should be removed from the broker"
+ conditions.eventually {
+ assert mqttBrokerService.clientIdConnectionMap.get(mqttDeviceNClientId) == null
}
+ when: "another device connects"
+ deviceNResponses.clear()
+ deviceNUniqueId = "device3"
+ deviceNRequestTopic = "$PROVISIONING_TOKEN/$deviceNUniqueId/$REQUEST_TOKEN".toString()
+ deviceNResponseTopic = "$PROVISIONING_TOKEN/$deviceNUniqueId/$RESPONSE_TOKEN".toString()
+ deviceNClient.connect()
+ then: "mqtt connection should exist"
+ conditions.eventually {
+ assert deviceNClient.getConnectionStatus() == ConnectionStatus.CONNECTED
+ assert mqttBrokerService.clientIdConnectionMap.get(mqttDeviceNClientId) != null
+ }
+
+ when: "the client subscribes to the provisioning endpoints"
+ deviceNClient.addMessageConsumer(deviceNResponseTopic, deviceNMessageConsumer)
+
+ then: "the subscriptions should succeed"
+ conditions.eventually {
+ assert deviceNClient.topicConsumerMap.get(deviceNResponseTopic) != null
+ assert deviceNClient.topicConsumerMap.get(deviceNResponseTopic).size() == 1
+ assert mqttBrokerService.clientIdConnectionMap.get(mqttDeviceNClientId) != null
+ }
+
+ when: "the client publishes a valid x509 certificate that has been signed by the CA stored in the provisioning config but against an expired certificate"
+ deviceNClient.sendMessage(
+ new MQTTMessage<String>(deviceNRequestTopic, ValueUtil.asJSON(
+ new X509ProvisioningMessage(getClass().getResource("/org/openremote/test/provisioning/device3_caexpired.pem").text)
+ ).orElse(null))
+ )
+
+ then: "the broker should have published to the response topic a success message containing the provisioned asset"
+ conditions.eventually {
+ assert deviceNResponses.size() == 1
+ assert deviceNResponses.get(0) instanceof SuccessResponseMessage
+ assert ((SuccessResponseMessage)deviceNResponses.get(0)).realm == managerTestSetup.realmBuildingTenant
+ asset = ((SuccessResponseMessage)deviceNResponses.get(0)).asset
+ assert asset != null
+ assert asset instanceof WeatherAsset
+ assert asset.getAttribute("serialNumber").flatMap{it.getValue()}.orElse(null) == deviceNUniqueId
+ }
+
+ when: "the client disconnects"
+ deviceNClient.removeAllMessageConsumers()
+ deviceNClient.disconnect()
+
+ then: "the connection should be removed from the broker"
+ conditions.eventually {
+ assert mqttBrokerService.clientIdConnectionMap.get(mqttDeviceNClientId) == null
+ }
+
+ when: "the provisioning config is updated to disabled"
+ provisioningConfig.setDisabled(true)
+ provisioningConfig = provisioningService.merge(provisioningConfig)
+
+ and: "a device re-connects"
+ deviceNResponses.clear()
+ deviceNClient.connect()
+
+ then: "mqtt connection should exist"
+ conditions.eventually {
+ assert deviceNClient.getConnectionStatus() == ConnectionStatus.CONNECTED
+ assert mqttBrokerService.clientIdConnectionMap.get(mqttDeviceNClientId) != null
+ }
+
+ when: "the client subscribes to the provisioning endpoints"
+ deviceNClient.addMessageConsumer(deviceNResponseTopic, deviceNMessageConsumer)
+
+ then: "the subscriptions should succeed"
+ conditions.eventually {
+ assert deviceNClient.topicConsumerMap.get(deviceNResponseTopic) != null
+ assert deviceNClient.topicConsumerMap.get(deviceNResponseTopic).size() == 1
+ assert mqttBrokerService.clientIdConnectionMap.get(mqttDeviceNClientId) != null
+ }
+
+ when: "the client publishes a valid x509 certificate that has been signed by the CA stored in the provisioning config but against an expired certificate"
+ deviceNClient.sendMessage(
+ new MQTTMessage<String>(deviceNRequestTopic, ValueUtil.asJSON(
+ new X509ProvisioningMessage(getClass().getResource("/org/openremote/test/provisioning/device3_caexpired.pem").text)
+ ).orElse(null))
+ )
+
+ then: "the broker should have published to the response topic an error message"
+ conditions.eventually {
+ assert deviceNResponses.size() == 1
+ assert deviceNResponses.get(0) instanceof ErrorResponseMessage
+ assert ((ErrorResponseMessage)deviceNResponses.get(0)).error == ErrorResponseMessage.Error.CONFIG_DISABLED
+ }
+
+ when: "the client disconnects"
+ deviceNClient.removeAllMessageConsumers()
+ deviceNClient.disconnect()
+
+ then: "the connection should be removed from the broker"
+ conditions.eventually {
+ assert mqttBrokerService.clientIdConnectionMap.get(mqttDeviceNClientId) == null
+ }
+
+ when: "the provisioning config is updated to enabled"
+ provisioningConfig.setDisabled(false)
+ provisioningConfig = provisioningService.merge(provisioningConfig)
+
+ and: "a device user is disabled"
+ def user = identityService.getIdentityProvider().getUserByUsername(managerTestSetup.realmBuildingTenant, User.SERVICE_ACCOUNT_PREFIX + "ps-" + deviceNUniqueId)
+ user.setEnabled(false)
+ user = identityService.getIdentityProvider().createUpdateUser(managerTestSetup.realmBuildingTenant, user, null)
+
+ and: "a device with disabled user account re-connects"
+ deviceNResponses.clear()
+ deviceNClient.connect()
+
+ then: "mqtt connection should exist"
+ conditions.eventually {
+ assert deviceNClient.getConnectionStatus() == ConnectionStatus.CONNECTED
+ assert mqttBrokerService.clientIdConnectionMap.get(mqttDeviceNClientId) != null
+ }
+
+ when: "the client subscribes to the provisioning endpoints"
+ deviceNClient.addMessageConsumer(deviceNResponseTopic, deviceNMessageConsumer)
+
+ then: "the subscriptions should succeed"
+ conditions.eventually {
+ assert deviceNClient.topicConsumerMap.get(deviceNResponseTopic) != null
+ assert deviceNClient.topicConsumerMap.get(deviceNResponseTopic).size() == 1
+ assert mqttBrokerService.clientIdConnectionMap.get(mqttDeviceNClientId) != null
+ }
+
+ when: "the client publishes a valid x509 certificate that has been signed by the CA stored in the provisioning config but against an expired certificate"
+ deviceNClient.sendMessage(
+ new MQTTMessage<String>(deviceNRequestTopic, ValueUtil.asJSON(
+ new X509ProvisioningMessage(getClass().getResource("/org/openremote/test/provisioning/device3_caexpired.pem").text)
+ ).orElse(null))
+ )
+
+ then: "the broker should have published to the response topic an error message"
+ conditions.eventually {
+ assert deviceNResponses.size() == 1
+ assert deviceNResponses.get(0) instanceof ErrorResponseMessage
+ assert ((ErrorResponseMessage)deviceNResponses.get(0)).error == ErrorResponseMessage.Error.USER_DISABLED
+ }
+
+ cleanup: "disconnect the clients"
+ if (device1Client != null) {
+ device1Client.disconnect()
+ }
+ if (deviceNClient != null) {
+ deviceNClient.disconnect()
+ }
}
}