Skip to content

armgit / core

Public Imported from GitHub
0

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

Fix restricted user AssetEvent bug and realm API bug (#1020)

Rich Turner4cc82cd12b9d
diff --git a/manager/src/main/java/org/openremote/manager/event/EventSubscriptions.java b/manager/src/main/java/org/openremote/manager/event/EventSubscriptions.java
index e638720fb..6884f03ee 100644
--- a/manager/src/main/java/org/openremote/manager/event/EventSubscriptions.java
+++ b/manager/src/main/java/org/openremote/manager/event/EventSubscriptions.java
@@ -141,8 +141,8 @@ public class EventSubscriptions {
T filteredEvent = sessionSub.subscription.getFilter() == null ? event : sessionSub.subscription.getFilter().apply(event);
if (filteredEvent != null) {
- LOG.finest("Creating message for subscribed session '" + sessionKey + "': " + event);
- List<T> events = Collections.singletonList(event);
+ LOG.finest("Creating message for subscribed session '" + sessionKey + "': " + filteredEvent);
+ List<T> events = Collections.singletonList(filteredEvent);
TriggeredEventSubscription<T> triggeredEventSubscription = new TriggeredEventSubscription<>(events, sessionSub.subscriptionId);
if (sessionSub.subscription.getInternalConsumer() == null) {
diff --git a/manager/src/main/java/org/openremote/manager/security/ManagerIdentityProvider.java b/manager/src/main/java/org/openremote/manager/security/ManagerIdentityProvider.java
index 4abd66ca9..6f7bdc85a 100644
--- a/manager/src/main/java/org/openremote/manager/security/ManagerIdentityProvider.java
+++ b/manager/src/main/java/org/openremote/manager/security/ManagerIdentityProvider.java
@@ -299,6 +299,9 @@ public interface ManagerIdentityProvider extends IdentityProvider {
return o1.getName().compareTo(o2.getName());
});
+ // TODO: Remove this once migrated to hibernate 6.2.x+
+ realms.forEach(r -> r.getRealmRoles().size());
+
return realms.toArray(new Realm[realms.size()]);
});
}
@@ -307,6 +310,10 @@ public interface ManagerIdentityProvider extends IdentityProvider {
return persistenceService.doReturningTransaction(em -> {
List<Realm> realms = em.createQuery("select r from Realm r where r.name = :realm", Realm.class)
.setParameter("realm", realm).getResultList();
+
+ // TODO: Remove this once migrated to hibernate 6.2.x+
+ realms.forEach(r -> r.getRealmRoles().size());
+
return realms.size() == 1 ? realms.get(0) : null;
}
);
diff --git a/model/src/main/java/org/openremote/model/asset/AssetFilter.java b/model/src/main/java/org/openremote/model/asset/AssetFilter.java
index b831f9a46..c25f130f5 100644
--- a/model/src/main/java/org/openremote/model/asset/AssetFilter.java
+++ b/model/src/main/java/org/openremote/model/asset/AssetFilter.java
@@ -177,17 +177,18 @@ public class AssetFilter<T extends SharedEvent & AssetInfo> extends EventFilter<
}
}
- if (attributeNames != null && attributeNames.length > 0) {
- if (filterAttributesBy != null) {
- // Filter attributes before doing name match
- AssetEvent assetEvent = (AssetEvent) event;
- if (assetEvent.getAsset() != null) {
- Asset<?> asset = ValueUtil.clone(assetEvent.getAsset());
- MetaItemDescriptor<?> finalFilterAttributesBy = filterAttributesBy;
- asset.setAttributes(asset.getAttributes().values().stream().filter(attribute -> attribute.hasMeta(finalFilterAttributesBy)).collect(Collectors.toList()));
- event = (T) new AssetEvent(assetEvent.getCause(), asset, assetEvent.getUpdatedProperties());
- }
+ if (filterAttributesBy != null) {
+ // Filter attributes before doing name match
+ AssetEvent assetEvent = (AssetEvent) event;
+ if (assetEvent.getAsset() != null) {
+ Asset<?> asset = ValueUtil.clone(assetEvent.getAsset());
+ MetaItemDescriptor<?> finalFilterAttributesBy = filterAttributesBy;
+ asset.setAttributes(asset.getAttributes().values().stream().filter(attribute -> attribute.hasMeta(finalFilterAttributesBy)).collect(Collectors.toList()));
+ event = (T) new AssetEvent(assetEvent.getCause(), asset, assetEvent.getUpdatedProperties());
}
+ }
+
+ if (attributeNames != null && attributeNames.length > 0) {
List<String> eventAttributeNames = Arrays.asList(event.getAttributeNames());
if (Arrays.stream(attributeNames).noneMatch(eventAttributeNames::contains)) {
return null;
diff --git a/setup/src/integration/java/org/openremote/setup/integration/ManagerTestSetup.java b/setup/src/integration/java/org/openremote/setup/integration/ManagerTestSetup.java
index 86fd4d987..dfcee03f1 100644
--- a/setup/src/integration/java/org/openremote/setup/integration/ManagerTestSetup.java
+++ b/setup/src/integration/java/org/openremote/setup/integration/ManagerTestSetup.java
@@ -52,7 +52,7 @@ public class ManagerTestSetup extends ManagerSetup {
// Update these numbers whenever you change a RULE_STATE flag in test data
public static final int DEMO_RULE_STATES_APARTMENT_1 = 44;
- public static final int DEMO_RULE_STATES_APARTMENT_2 = 13;
+ public static final int DEMO_RULE_STATES_APARTMENT_2 = 14;
public static final int DEMO_RULE_STATES_APARTMENT_3 = 0;
public static final int DEMO_RULE_STATES_SMART_OFFICE = 5;
public static final int DEMO_RULE_STATES_SMART_BUILDING = DEMO_RULE_STATES_APARTMENT_1 + DEMO_RULE_STATES_APARTMENT_2 + DEMO_RULE_STATES_APARTMENT_3;
@@ -515,6 +515,7 @@ public class ManagerTestSetup extends ManagerSetup {
new MetaItem<>(RULE_STATE, true)
)
);
+ addDemoApartmentTemperatureControl(apartment2Livingroom, false, null);
apartment2Livingroom = assetStorageService.merge(apartment2Livingroom);
apartment2LivingroomId = apartment2Livingroom.getId();
diff --git a/test/src/test/groovy/org/openremote/test/assets/AssetQueryTest.groovy b/test/src/test/groovy/org/openremote/test/assets/AssetQueryTest.groovy
index 7bb393c98..32d2b32d0 100644
--- a/test/src/test/groovy/org/openremote/test/assets/AssetQueryTest.groovy
+++ b/test/src/test/groovy/org/openremote/test/assets/AssetQueryTest.groovy
@@ -140,10 +140,11 @@ class AssetQueryTest extends Specification implements ManagerContainerTrait {
then: "only one asset should be retrieved"
assets.size() == 1
assets.get(0).id == managerTestSetup.apartment2LivingroomId
- assets.get(0).getAttributes().size() == 1
+ assets.get(0).getAttributes().size() == 2
assets.get(0).getAttribute("windowOpen").isPresent()
!assets.get(0).getAttribute("windowOpen").flatMap{it.value}.orElse(false)
!assets.get(0).getAttribute("windowOpen").get().getMeta().isEmpty()
+ assets.get(0).getAttribute("targetTemperature").isPresent()
when: "a recursive query is executed for apartment 1 assets"
assets = assetStorageService.findAll(
diff --git a/test/src/test/groovy/org/openremote/test/protocol/websocket/WebsocketClientTest.groovy b/test/src/test/groovy/org/openremote/test/protocol/websocket/WebsocketClientTest.groovy
index 15756e34f..f4f6192a9 100644
--- a/test/src/test/groovy/org/openremote/test/protocol/websocket/WebsocketClientTest.groovy
+++ b/test/src/test/groovy/org/openremote/test/protocol/websocket/WebsocketClientTest.groovy
@@ -27,6 +27,11 @@ import org.openremote.manager.agent.AgentService
import org.openremote.manager.asset.AssetProcessingService
import org.openremote.manager.asset.AssetStorageService
import org.openremote.manager.setup.SetupService
+import org.openremote.model.asset.AssetEvent
+import org.openremote.model.attribute.Attribute
+import org.openremote.model.event.shared.SharedEvent
+import org.openremote.model.value.ValueType
+import org.openremote.setup.integration.KeycloakTestSetup
import org.openremote.setup.integration.ManagerTestSetup
import org.openremote.model.asset.AssetFilter
import org.openremote.model.asset.agent.ConnectionStatus
@@ -39,8 +44,6 @@ import org.openremote.test.ManagerContainerTrait
import spock.lang.Specification
import spock.util.concurrent.PollingConditions
-import java.util.concurrent.TimeUnit
-
import static org.openremote.container.util.MapAccess.getString
import static org.openremote.manager.security.ManagerIdentityProvider.OR_ADMIN_PASSWORD
import static org.openremote.manager.security.ManagerIdentityProvider.OR_ADMIN_PASSWORD_DEFAULT
@@ -53,10 +56,12 @@ import static org.openremote.model.Constants.MASTER_REALM_ADMIN_USER
*/
class WebsocketClientTest extends Specification implements ManagerContainerTrait {
- protected static <T> T messageFromString(String message, String prefix, Class<T> clazz) {
+ protected static <T> T messageFromString(String message) {
try {
- message = message.substring(prefix.length())
- return ValueUtil.JSON.readValue(message, clazz)
+ def isSubscription = message.startsWith(EventSubscription.SUBSCRIBED_MESSAGE_PREFIX)
+ def isTriggered = !isSubscription && message.startsWith(TriggeredEventSubscription.MESSAGE_PREFIX)
+ message = message.substring(message.indexOf(":")+1)
+ return ValueUtil.JSON.readValue(message, isSubscription ? EventSubscription.class : isTriggered ? TriggeredEventSubscription.class : SharedEvent.class)
} catch (Exception e) {
throw new IllegalArgumentException("Unable to parse message")
}
@@ -71,6 +76,194 @@ class WebsocketClientTest extends Specification implements ManagerContainerTrait
}
}
+ def "Check restricted client"() {
+ given: "expected conditions"
+ def conditions = new PollingConditions(timeout: 15, delay: 0.2)
+
+ and: "the container is started"
+ def container = startContainer(defaultConfig(), defaultServices())
+ def assetProcessingService = container.getService(AssetProcessingService.class)
+ def assetStorageService = container.getService(AssetStorageService.class)
+ def agentService = container.getService(AgentService.class)
+ def managerTestSetup = container.getService(SetupService.class).getTaskOfType(ManagerTestSetup.class)
+ def keycloakTestSetup = container.getService(SetupService.class).getTaskOfType(KeycloakTestSetup.class)
+
+ and: "a simple Websocket client with restricted user"
+ def client = new WebsocketIOClient<String>(
+ new URIBuilder("ws://127.0.0.1:$serverPort/websocket/events?Realm=building").build(),
+ null,
+ new OAuthPasswordGrant("http://127.0.0.1:$serverPort/auth/realms/building/protocol/openid-connect/token",
+ KEYCLOAK_CLIENT_ID,
+ null,
+ null,
+ "testuser3",
+ "testuser3"))
+ client.setEncoderDecoderProvider({
+ [new AbstractNettyIOClient.MessageToMessageDecoder<String>(String.class, client)].toArray(new ChannelHandler[0])
+ })
+
+ and: "another Websocket client with another restricted user"
+ def client2 = new WebsocketIOClient<String>(
+ new URIBuilder("ws://127.0.0.1:$serverPort/websocket/events?Realm=building").build(),
+ null,
+ new OAuthPasswordGrant("http://127.0.0.1:$serverPort/auth/realms/building/protocol/openid-connect/token",
+ KEYCLOAK_CLIENT_ID,
+ null,
+ null,
+ "building",
+ "building"))
+ client2.setEncoderDecoderProvider({
+ [new AbstractNettyIOClient.MessageToMessageDecoder<String>(String.class, client2)].toArray(new ChannelHandler[0])
+ })
+
+ and: "we add callback consumers to the clients"
+ def connectionStatus = client.getConnectionStatus()
+ def connectionStatus2 = client2.getConnectionStatus()
+ List<Object> receivedMessages = []
+ List<Object> receivedMessages2 = []
+ client.addMessageConsumer({
+ message -> receivedMessages.add(messageFromString(message))
+ })
+ client.addConnectionStatusConsumer({
+ status -> connectionStatus = status
+ })
+ client2.addMessageConsumer({
+ message -> receivedMessages2.add(messageFromString(message))
+ })
+ client2.addConnectionStatusConsumer({
+ status -> connectionStatus2 = status
+ })
+
+ and: "the system settles down"
+ noEventProcessedIn(assetProcessingService, 500)
+
+ when: "we call connect on the clients"
+ client.connect()
+ client2.connect()
+
+ then: "the clients status should become CONNECTED"
+ conditions.eventually {
+ assert client.connectionStatus == ConnectionStatus.CONNECTED
+ assert connectionStatus == ConnectionStatus.CONNECTED
+ assert client2.connectionStatus == ConnectionStatus.CONNECTED
+ assert connectionStatus2 == ConnectionStatus.CONNECTED
+ }
+
+ // TODO: Remove this once client supports some better connection logic
+ and: "some time passes to allow the connection to be fully initialised"
+ sleep(3000)
+
+ when: "we subscribe to attribute events produced by the server"
+ client.sendMessage(messageToString(EventSubscription.SUBSCRIBE_MESSAGE_PREFIX,
+ new EventSubscription(
+ AttributeEvent.class,
+ null,
+ "attributes",
+ null)))
+ client2.sendMessage(messageToString(EventSubscription.SUBSCRIBE_MESSAGE_PREFIX,
+ new EventSubscription(
+ AttributeEvent.class,
+ null,
+ "attributes2",
+ null)))
+
+ and: "we subscribe to asset events produced by the server"
+ client.sendMessage(messageToString(EventSubscription.SUBSCRIBE_MESSAGE_PREFIX,
+ new EventSubscription(
+ AssetEvent.class,
+ null,
+ "assets",
+ null)))
+ client2.sendMessage(messageToString(EventSubscription.SUBSCRIBE_MESSAGE_PREFIX,
+ new EventSubscription(
+ AssetEvent.class,
+ null,
+ "assets2",
+ null)))
+
+ then: "the server should confirm the subscriptions"
+ conditions.eventually {
+ assert receivedMessages.size() == 2
+ assert receivedMessages.any {it instanceof EventSubscription && it.subscriptionId == "attributes"}
+ assert receivedMessages.any {it instanceof EventSubscription && it.subscriptionId == "assets"}
+ assert receivedMessages2.size() == 2
+ assert receivedMessages2.any {it instanceof EventSubscription && it.subscriptionId == "attributes2"}
+ assert receivedMessages2.any {it instanceof EventSubscription && it.subscriptionId == "assets2"}
+ }
+
+ when: "apartment 1 living room temp changes"
+ receivedMessages.clear()
+ receivedMessages2.clear()
+ assetProcessingService.sendAttributeEvent(new AttributeEvent(managerTestSetup.apartment1LivingroomId, "targetTemperature", 5))
+
+ then: "the testuser3 client receives the event"
+ conditions.eventually {
+ assert receivedMessages.size() == 1
+ TriggeredEventSubscription triggeredEvent = receivedMessages[0] as TriggeredEventSubscription
+ assert triggeredEvent.subscriptionId == "attributes"
+ assert triggeredEvent.events.size() == 1
+ assert ((AttributeEvent) triggeredEvent.events[0]).assetId == managerTestSetup.apartment1LivingroomId
+ assert ((AttributeEvent) triggeredEvent.events[0]).attributeName == "targetTemperature"
+ assert ((AttributeEvent) triggeredEvent.events[0]).value.orElse(0) == 5
+ }
+
+ then: "the building user should not have received the event"
+ conditions.eventually {
+ assert receivedMessages2.isEmpty()
+ }
+
+ when: "apartment 2 living room temp changes"
+ receivedMessages.clear()
+ receivedMessages2.clear()
+ assetProcessingService.sendAttributeEvent(new AttributeEvent(managerTestSetup.apartment2LivingroomId, "targetTemperature", 15))
+
+ then: "the building client receives the event"
+ conditions.eventually {
+ assert receivedMessages2.size() == 1
+ TriggeredEventSubscription triggeredEvent = receivedMessages2[0] as TriggeredEventSubscription
+ assert triggeredEvent.subscriptionId == "attributes2"
+ assert triggeredEvent.events.size() == 1
+ assert ((AttributeEvent) triggeredEvent.events[0]).assetId == managerTestSetup.apartment2LivingroomId
+ assert ((AttributeEvent) triggeredEvent.events[0]).attributeName == "targetTemperature"
+ assert ((AttributeEvent) triggeredEvent.events[0]).value.orElse(0) == 15
+ }
+
+ then: "the testuser3 user should not have received the event"
+ assert receivedMessages.isEmpty()
+
+ when: "apartment 1 living room asset is modified"
+ receivedMessages.clear()
+ receivedMessages2.clear()
+ def apartment1Livingroom = assetStorageService.find(managerTestSetup.apartment1LivingroomId)
+ apartment1Livingroom.addAttributes(
+ new Attribute<>("testAttribute", ValueType.BOOLEAN)
+ )
+ apartment1Livingroom = assetStorageService.merge(apartment1Livingroom)
+
+ then: "the testuser3 client should be notified with only accessible attributes"
+ conditions.eventually {
+ assert receivedMessages.size() == 1
+ assert receivedMessages.get(0) instanceof TriggeredEventSubscription
+ assert (receivedMessages.get(0) as TriggeredEventSubscription).subscriptionId == "assets"
+ assert (receivedMessages.get(0) as TriggeredEventSubscription).events.size() == 1
+ assert (receivedMessages.get(0) as TriggeredEventSubscription).events.get(0) instanceof AssetEvent
+ assert ((receivedMessages.get(0) as TriggeredEventSubscription).events.get(0) as AssetEvent).assetId == managerTestSetup.apartment1LivingroomId
+ assert ((receivedMessages.get(0) as TriggeredEventSubscription).events.get(0) as AssetEvent).attributeNames.size() == 7
+ assert !((receivedMessages.get(0) as TriggeredEventSubscription).events.get(0) as AssetEvent).attributeNames.contains("testAttribute")
+ }
+
+ then: "the building user should not have received the event"
+ assert receivedMessages2.isEmpty()
+
+ cleanup: "the server should be stopped"
+ if (client != null) {
+ client.disconnect()
+ }
+ if (client2 != null) {
+ client2.disconnect()
+ }
+ }
+
def "Check client"() {
given: "expected conditions"
@@ -100,9 +293,9 @@ class WebsocketClientTest extends Specification implements ManagerContainerTrait
and: "we add callback consumers to the client"
def connectionStatus = client.getConnectionStatus()
List<String> receivedMessages = []
- client.addMessageConsumer({
- message -> receivedMessages.add(message)
- })
+ client.addMessageConsumer(
+ message -> receivedMessages.add(messageFromString(message))
+ )
client.addConnectionStatusConsumer({
status -> connectionStatus = status
})
@@ -134,7 +327,7 @@ class WebsocketClientTest extends Specification implements ManagerContainerTrait
then: "the server should return a subscribed event"
conditions.eventually {
assert receivedMessages.size() == 1
- def subscription = messageFromString(receivedMessages[0], EventSubscription.SUBSCRIBED_MESSAGE_PREFIX, EventSubscription.class)
+ EventSubscription subscription = receivedMessages[0] as EventSubscription
assert subscription != null
assert subscription.subscriptionId == "1"
}
@@ -146,7 +339,7 @@ class WebsocketClientTest extends Specification implements ManagerContainerTrait
then: "the client receives the event"
conditions.eventually {
assert receivedMessages.size() == 1
- def triggeredEvent = messageFromString(receivedMessages[0], TriggeredEventSubscription.MESSAGE_PREFIX, TriggeredEventSubscription.class)
+ TriggeredEventSubscription triggeredEvent = receivedMessages[0] as TriggeredEventSubscription
assert triggeredEvent.subscriptionId == "1"
assert triggeredEvent.events.size() == 1
assert ((AttributeEvent)triggeredEvent.events[0]).assetId == managerTestSetup.apartment1LivingroomId
@@ -154,17 +347,14 @@ class WebsocketClientTest extends Specification implements ManagerContainerTrait
assert ((AttributeEvent)triggeredEvent.events[0]).value.orElse(0) == 5
}
- when: "time advances"
- advancePseudoClock(1, TimeUnit.SECONDS, container)
-
- and: "when apartment 1 living room temp is set to the same value again"
+ when: "when apartment 1 living room temp is set to the same value again"
receivedMessages.clear()
assetProcessingService.sendAttributeEvent(new AttributeEvent(managerTestSetup.apartment1LivingroomId, "targetTemperature", 5))
then: "the client should receive the event"
conditions.eventually {
assert receivedMessages.size() == 1
- def triggeredEvent = messageFromString(receivedMessages[0], TriggeredEventSubscription.MESSAGE_PREFIX, TriggeredEventSubscription.class)
+ TriggeredEventSubscription triggeredEvent = receivedMessages[0] as TriggeredEventSubscription
assert triggeredEvent.subscriptionId == "1"
assert triggeredEvent.events.size() == 1
assert ((AttributeEvent)triggeredEvent.events[0]).assetId == managerTestSetup.apartment1LivingroomId
@@ -172,17 +362,14 @@ class WebsocketClientTest extends Specification implements ManagerContainerTrait
assert ((AttributeEvent)triggeredEvent.events[0]).value.orElse(0) == 5
}
- when: "time advances"
- advancePseudoClock(1, TimeUnit.SECONDS, container)
-
- and: "when apartment 1 living room temp is set to null"
+ when: "when apartment 1 living room temp is set to null"
receivedMessages.clear()
assetProcessingService.sendAttributeEvent(new AttributeEvent(managerTestSetup.apartment1LivingroomId, "targetTemperature", null))
then: "the client receives the event"
conditions.eventually {
assert receivedMessages.size() == 1
- def triggeredEvent = messageFromString(receivedMessages[0], TriggeredEventSubscription.MESSAGE_PREFIX, TriggeredEventSubscription.class)
+ TriggeredEventSubscription triggeredEvent = receivedMessages[0] as TriggeredEventSubscription
assert triggeredEvent.subscriptionId == "1"
assert triggeredEvent.events.size() == 1
assert ((AttributeEvent)triggeredEvent.events[0]).assetId == managerTestSetup.apartment1LivingroomId
@@ -190,10 +377,7 @@ class WebsocketClientTest extends Specification implements ManagerContainerTrait
assert !((AttributeEvent)triggeredEvent.events[0]).value.isPresent()
}
- when: "time advances"
- advancePseudoClock(1, TimeUnit.SECONDS, container)
-
- and: "when apartment 1 bathroom temp changes"
+ when: "when apartment 1 bathroom temp changes"
receivedMessages.clear()
assetProcessingService.sendAttributeEvent(new AttributeEvent(managerTestSetup.apartment1BathroomId, "targetTemperature", 10))