100% open-source IoT Platform - Integrate your devices, add intelligence, build custom apps
Java asset-managementbuildingdashboarddataplatformdevice-managementedge-computingenergyenergy-managementenergy-monitorfleet-managementfleet-telematicsiotiot-applicationiot-platformmodbusmqttmqtt-brokerota-updaterules-enginesmartcity
Merge commit from fork
Eric Bariauxc4b36206d5a1
diff --git a/manager/src/main/java/org/openremote/manager/asset/console/ConsoleResourceImpl.java b/manager/src/main/java/org/openremote/manager/asset/console/ConsoleResourceImpl.javaindex d81e2f185..8c4b61de7 100644--- a/manager/src/main/java/org/openremote/manager/asset/console/ConsoleResourceImpl.java+++ b/manager/src/main/java/org/openremote/manager/asset/console/ConsoleResourceImpl.java@@ -20,6 +20,7 @@package org.openremote.manager.asset.console;import jakarta.ws.rs.BadRequestException;+import jakarta.ws.rs.WebApplicationException;import org.openremote.container.timer.TimerService;import org.openremote.manager.asset.AssetStorageService;import org.openremote.manager.event.ClientEventService;@@ -47,6 +48,9 @@ import java.util.Map;import java.util.Objects;import java.util.concurrent.ConcurrentHashMap;+import static jakarta.ws.rs.core.Response.Status.CONFLICT;+import static jakarta.ws.rs.core.Response.Status.FORBIDDEN;+public class ConsoleResourceImpl extends ManagerWebResource implements ConsoleResource {public static final String CONSOLE_PARENT_ASSET_NAME = "Consoles";@@ -78,7 +82,12 @@ public class ConsoleResourceImpl extends ManagerWebResource implements ConsoleRethrow new BadRequestException("Invalid realm");}+ if (isAuthenticated() && !isRealmAccessibleByUser(getRequestRealmName())) {+ throw new WebApplicationException("Console can only be registered in an accessible realm", FORBIDDEN);+ }+ConsoleAsset consoleAsset = null;+ boolean existingConsole = false;// If console registration has an id and asset exists then ensure asset type is consoleif (!TextUtil.isNullOrEmpty(consoleRegistration.getId())) {@@ -86,7 +95,23 @@ public class ConsoleResourceImpl extends ManagerWebResource implements ConsoleReif (existingAsset != null && !(existingAsset instanceof ConsoleAsset)) {throw new BadRequestException("Console registration ID is not for a Console asset: " + consoleRegistration.getId());}+ if (existingAsset == null) {+ throw new WebApplicationException("Console registration ID does not exist: " + consoleRegistration.getId(), CONFLICT);+ }consoleAsset = (ConsoleAsset) existingAsset;+ existingConsole = true;+ }++ if (existingConsole) {+ if (!Objects.equals(consoleAsset.getRealm(), getRequestRealmName())) {+ throw new WebApplicationException("Console registration ID is not in the request realm: " + consoleRegistration.getId(), FORBIDDEN);+ }+ if (!isAuthenticated()) {+ throw new WebApplicationException("Anonymous requests cannot update existing console registrations", FORBIDDEN);+ }+ if (assetStorageService.findUserAssetLinks(getAuthenticatedRealmName(), getUserId(), consoleAsset.getId()).isEmpty()) {+ throw new WebApplicationException("User is not linked to this console registration", FORBIDDEN);+ }}boolean mergeConsole = false;@@ -130,13 +155,8 @@ public class ConsoleResourceImpl extends ManagerWebResource implements ConsoleRe}consoleRegistration.setId(consoleAsset.getId());- // If authenticated link the console to this user only- if (isAuthenticated()) {- List<UserAssetLink> userAssetLinks = assetStorageService.findUserAssetLinks(getAuthenticatedRealmName(), null, consoleAsset.getId());- List<UserAssetLink> otherUserAssetLinks = userAssetLinks.stream().filter(link -> !getUserId().equals(link.getId().getUserId())).toList();- if (!otherUserAssetLinks.isEmpty()) {- assetStorageService.deleteUserAssetLinks(otherUserAssetLinks);- }+ // New authenticated legacy registrations are linked to this user. Existing registrations must already be linked.+ if (isAuthenticated() && !existingConsole) {assetStorageService.storeUserAssetLinks(List.of(new UserAssetLink(getAuthenticatedRealmName(), getUserId(), consoleAsset.getId())));}diff --git a/test/src/test/groovy/org/openremote/test/console/ConsoleTest.groovy b/test/src/test/groovy/org/openremote/test/console/ConsoleTest.groovyindex b5b42cdcb..0774b9e5b 100644--- a/test/src/test/groovy/org/openremote/test/console/ConsoleTest.groovy+++ b/test/src/test/groovy/org/openremote/test/console/ConsoleTest.groovy@@ -206,6 +206,110 @@ class ConsoleTest extends Specification implements ManagerContainerTrait {Files.deleteIfExists(customDocRoot)}+ def "Console registration rejects existing console mutation without current ownership"() {+ given: "the container environment is started"+ def container = startContainer(defaultConfig(), defaultServices())+ def assetStorageService = container.getService(AssetStorageService.class)+ def keycloakTestSetup = container.getService(SetupService.class).getTaskOfType(KeycloakTestSetup.class)++ and: "console registration clients for two users and an anonymous caller"+ def testUser3AccessToken = authenticate(+ container,+ keycloakTestSetup.realmBuilding.name,+ KEYCLOAK_CLIENT_ID,+ "testuser3",+ "testuser3"+ )+ def testUser2AccessToken = authenticate(+ container,+ keycloakTestSetup.realmBuilding.name,+ KEYCLOAK_CLIENT_ID,+ "testuser2",+ "testuser2"+ )+ def testUser3ConsoleResource = getClientApiTarget(serverUri(serverPort), keycloakTestSetup.realmBuilding.name, testUser3AccessToken).proxy(ConsoleResource.class)+ def testUser2ConsoleResource = getClientApiTarget(serverUri(serverPort), keycloakTestSetup.realmBuilding.name, testUser2AccessToken).proxy(ConsoleResource.class)+ def anonymousConsoleResource = getClientApiTarget(serverUri(serverPort), keycloakTestSetup.realmBuilding.name).proxy(ConsoleResource.class)++ when: "a console is registered by one authenticated user"+ def originalRegistration = createConsoleRegistration(null, "Owner Console", "owner-token")+ def registeredConsole = testUser3ConsoleResource.register(null, originalRegistration)+ def consoleId = registeredConsole.id+ ConsoleAsset console = assetStorageService.find(consoleId, true)++ then: "the console is linked to the registering user and has the original provider data"+ assert console != null+ assert console.getConsoleName().orElse(null) == "Owner Console"+ assert getPushToken(console) == "owner-token"+ assert assetStorageService.findUserAssetLinks(keycloakTestSetup.realmBuilding.name, keycloakTestSetup.testuser3Id, consoleId).size() == 1+ assert assetStorageService.findUserAssetLinks(keycloakTestSetup.realmBuilding.name, keycloakTestSetup.testuser2Id, consoleId).isEmpty()++ when: "an anonymous caller tries to mutate the existing console by ID"+ anonymousConsoleResource.register(null, createConsoleRegistration(consoleId, "Anonymous Attacker Console", "anonymous-attacker-token"))++ then: "the request should be rejected"+ WebApplicationException ex = thrown()+ ex.response.withCloseable { r ->+ assert r.status == 403 || r.status == 409+ return true+ }++ and: "the console provider data should remain unchanged"+ ConsoleAsset consoleAfterAnonymousAttempt = assetStorageService.find(consoleId, true)+ assert consoleAfterAnonymousAttempt.getConsoleName().orElse(null) == "Owner Console"+ assert getPushToken(consoleAfterAnonymousAttempt) == "owner-token"+ assert assetStorageService.findUserAssetLinks(keycloakTestSetup.realmBuilding.name, keycloakTestSetup.testuser3Id, consoleId).size() == 1+ assert assetStorageService.findUserAssetLinks(keycloakTestSetup.realmBuilding.name, keycloakTestSetup.testuser2Id, consoleId).isEmpty()++ when: "a different authenticated user tries to claim the existing console by ID"+ testUser2ConsoleResource.register(null, createConsoleRegistration(consoleId, "Other User Console", "other-user-token"))++ then: "the request should be rejected"+ ex = thrown()+ ex.response.withCloseable { r ->+ assert r.status == 403 || r.status == 409+ return true+ }++ and: "the original user link and provider data should remain unchanged"+ ConsoleAsset consoleAfterOtherUserAttempt = assetStorageService.find(consoleId, true)+ assert consoleAfterOtherUserAttempt.getConsoleName().orElse(null) == "Owner Console"+ assert getPushToken(consoleAfterOtherUserAttempt) == "owner-token"+ assert assetStorageService.findUserAssetLinks(keycloakTestSetup.realmBuilding.name, keycloakTestSetup.testuser3Id, consoleId).size() == 1+ assert assetStorageService.findUserAssetLinks(keycloakTestSetup.realmBuilding.name, keycloakTestSetup.testuser2Id, consoleId).isEmpty()+ }++ def "Console registration rejects client supplied IDs for new legacy consoles"() {+ given: "the container environment is started"+ def container = startContainer(defaultConfig(), defaultServices())+ def assetStorageService = container.getService(AssetStorageService.class)+ def keycloakTestSetup = container.getService(SetupService.class).getTaskOfType(KeycloakTestSetup.class)++ and: "an authenticated console registration client"+ def accessToken = authenticate(+ container,+ keycloakTestSetup.realmBuilding.name,+ KEYCLOAK_CLIENT_ID,+ "testuser3",+ "testuser3"+ )+ def authenticatedConsoleResource = getClientApiTarget(serverUri(serverPort), keycloakTestSetup.realmBuilding.name, accessToken).proxy(ConsoleResource.class)++ when: "a client tries to create a console with its own unused ID"+ def unusedId = UniqueIdentifierGenerator.generateId("UnusedConsoleIdRejectedByLegacyRegister")+ authenticatedConsoleResource.register(null, createConsoleRegistration(unusedId, "Client Supplied ID Console", "client-token"))++ then: "the request should be rejected"+ WebApplicationException ex = thrown()+ ex.response.withCloseable { r ->+ assert r.status == 400 || r.status == 409+ return true+ }++ and: "no console asset should be created with the supplied ID"+ assert assetStorageService.find(unusedId, true) == null+ }+def "Check full console behaviour"() {def notificationIds = new CopyOnWriteArrayList()def targetTypes = new CopyOnWriteArrayList()@@ -383,13 +487,21 @@ class ConsoleTest extends Specification implements ManagerContainerTrait {when: "the console registration is updated anonymously"returnedConsoleRegistration.providers.get("test").disabled = false- returnedConsoleRegistration = anonymousConsoleResource.register(null, returnedConsoleRegistration)+ anonymousConsoleResource.register(null, returnedConsoleRegistration)++ then: "the result should be forbidden"+ WebApplicationException ex = thrown()+ ex.response.withCloseable { r ->+ assert r.status == 403+ return true+ }++ when: "the console registration is reloaded after the rejected anonymous update"console = assetStorageService.find(consoleId, true)testUser3Console1 = consoleconsoleTestProvider = console.getConsoleProviders().map{it.get("test")}.orElse(null)- then: "the returned console should contain the updated data and have the same id"- assert returnedConsoleRegistration.getId() == consoleId+ then: "the console registration should be unchanged"assert console != nullassert consoleGeofenceProvider != nullassert consoleGeofenceProvider.version == ORConsoleGeofenceAssetAdapter.NAME@@ -407,7 +519,7 @@ class ConsoleTest extends Specification implements ManagerContainerTrait {assert consoleTestProvider.version == "Test 1.0"assert !consoleTestProvider.requiresPermissionassert !consoleTestProvider.hasPermission- assert !consoleTestProvider.disabled+ assert consoleTestProvider.disabledassert consoleTestProvider.data == nullwhen: "a console registers with the id of another existing asset"@@ -415,7 +527,7 @@ class ConsoleTest extends Specification implements ManagerContainerTrait {authenticatedConsoleResource.register(null, consoleRegistration)then: "the result should be bad request"- WebApplicationException ex = thrown()+ ex = thrown()ex.response.withCloseable { r ->assert r.status == 400return true@@ -425,7 +537,19 @@ class ConsoleTest extends Specification implements ManagerContainerTrait {def unusedId = UniqueIdentifierGenerator.generateId("UnusedConsoleId")consoleRegistration.setId(unusedId)authenticatedConsoleResource.register(null, consoleRegistration)- console = assetStorageService.find(unusedId, true)++ then: "the result should be conflict"+ ex = thrown()+ ex.response.withCloseable { r ->+ assert r.status == 409+ return true+ }+ assert assetStorageService.find(unusedId, true) == null++ when: "a second console is registered without a client supplied id"+ consoleRegistration.setId(null)+ returnedConsoleRegistration = authenticatedConsoleResource.register(null, consoleRegistration)+ console = assetStorageService.find(returnedConsoleRegistration.getId(), true)testUser3Console2 = consoleconsoleGeofenceProvider = console.getConsoleProviders().map{it.get("geofence")}.orElse(null)consolePushProvider = console.getConsoleProviders().map{it.get("push")}.orElse(null)@@ -881,4 +1005,35 @@ class ConsoleTest extends Specification implements ManagerContainerTrait {notificationService.notificationHandlerMap.put(pushNotificationHandler.getTypeName(), pushNotificationHandler)}}++ protected static ConsoleRegistration createConsoleRegistration(String id, String name, String pushToken) {+ return new ConsoleRegistration(+ id,+ name,+ "1.0",+ "Android 7.0",+ new HashMap<String, ConsoleProvider>() {+ {+ put("push", new ConsoleProvider(+ "fcm",+ true,+ true,+ true,+ true,+ false,+ [token: pushToken]+ ))+ }+ },+ "",+ ["manager"] as String[]+ )+ }++ protected static String getPushToken(ConsoleAsset console) {+ return console.getConsoleProviders()+ .map { it.get("push") }+ .map { it.data.get("token") as String }+ .orElse(null)+ }}diff --git a/ui/component/core/src/console.ts b/ui/component/core/src/console.tsindex 602c38756..2b7f85290 100644--- a/ui/component/core/src/console.ts+++ b/ui/component/core/src/console.ts@@ -74,7 +74,7 @@ export class Console {// Look for existing console registration in local storage or just create a new onelet consoleReg: ConsoleRegistration = Console._createConsoleRegistration();- let consoleRegStr = window.localStorage.getItem("OpenRemoteConsole:" + realm);+ let consoleRegStr = window.localStorage.getItem(this._storageKey);if (consoleRegStr) {try {let storedRegObj = JSON.parse(consoleRegStr);@@ -237,7 +237,7 @@ export class Console {if (index >= 0) {this._pendingProviderEnables.splice(index, 1);if (this._pendingProviderEnables.length === 0) {- this.sendRegistration();+ this.sendRegistration().catch(() => undefined);this._callCompletedCallback();}}@@ -311,43 +311,73 @@ export class Console {console.debug("Sending registration in: " + delay + "ms");return new Promise((resolve, reject) => {- this._registrationTimer = window.setTimeout(() => {+ this._registrationTimer = window.setTimeout(async () => {this._registrationTimer = null;console.debug("Console: updating registration");try {- // Ensure console name, platform, version and providers are not null- if (!this._registration.name) {- this._registration.name = "Console";- }- if (!this._registration.platform) {- this._registration.platform = "N/A";- }- if (!this._registration.version) {- this._registration.version = "N/A"- }- if (!this._registration.providers) {- this._registration.providers = {};- }- manager.rest.api.ConsoleResource.register(this._registration).then((response: AxiosResponse<ConsoleRegistration>) => {- if (response.status !== 200) {- throw new Error("Failed to register console");- }-- this._registration = response.data;- console.debug("Console: registration successful");- console.debug("Console: updating locally stored registration");- window.localStorage.setItem("OpenRemoteConsole:" + this._realm, JSON.stringify(this._registration));- resolve();- });+ await this._sendRegistration(true);+ resolve();} catch (e) {- console.error("Failed to register console");- reject("Failed to register console");+ console.error("Failed to register console", e);+ reject(e);}- },);+ }, delay);});}+ protected async _sendRegistration(retryOnStaleRegistration: boolean): Promise<void> {+ this._normaliseRegistration();++ const hadRegistrationId = !!this._registration.id;++ try {+ const response: AxiosResponse<ConsoleRegistration> = await manager.rest.api.ConsoleResource.register(this._registration);+ if (response.status !== 200) {+ throw new Error("Failed to register console");+ }++ this._registration = response.data;+ console.debug("Console: registration successful");+ console.debug("Console: updating locally stored registration");+ window.localStorage.setItem(this._storageKey, JSON.stringify(this._registration));+ } catch (e) {+ if (retryOnStaleRegistration && hadRegistrationId && Console._isStaleRegistrationResponse(e)) {+ console.warn("Console registration ID is stale or cannot be claimed; creating a new console registration");+ window.localStorage.removeItem(this._storageKey);+ delete this._registration.id;+ await this._sendRegistration(false);+ return;+ }+ throw e;+ }+ }++ protected _normaliseRegistration() {+ // Ensure console name, platform, version and providers are not null+ if (!this._registration.name) {+ this._registration.name = "Console";+ }+ if (!this._registration.platform) {+ this._registration.platform = "N/A";+ }+ if (!this._registration.version) {+ this._registration.version = "N/A"+ }+ if (!this._registration.providers) {+ this._registration.providers = {};+ }+ }++ protected get _storageKey(): string {+ return "OpenRemoteConsole:" + this._realm;+ }++ protected static _isStaleRegistrationResponse(e: any): boolean {+ const status = e && e.response ? e.response.status : undefined;+ return status === 403 || status === 409;+ }+public storeData(key: string, value: any) {this.sendProviderMessage({provider: "storage",