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
Improved asset datapoints export access control (#2869)
Eric Bariaux06596a9034a6
diff --git a/manager/src/main/java/org/openremote/manager/datapoint/AssetDatapointResourceImpl.java b/manager/src/main/java/org/openremote/manager/datapoint/AssetDatapointResourceImpl.javaindex ec47885e3..4d960f026 100644--- a/manager/src/main/java/org/openremote/manager/datapoint/AssetDatapointResourceImpl.java+++ b/manager/src/main/java/org/openremote/manager/datapoint/AssetDatapointResourceImpl.java@@ -108,14 +108,7 @@ public class AssetDatapointResourceImpl extends ManagerWebResource implements Asnew WebApplicationException(Response.Status.NOT_FOUND));- // If restricted, the attribute should also be restricted- if(isRestrictedUser()) {- attribute.getMeta().getValue(MetaItemType.ACCESS_RESTRICTED_READ).ifPresentOrElse((v) -> {- if(!v) { throw new WebApplicationException(Response.Status.FORBIDDEN); }- }, () -> {- throw new WebApplicationException(Response.Status.FORBIDDEN);- });- }+ checkRestrictedAttributeRead(attribute);// If not logged in, attribute should be PUBLIC READif(!isAuthenticated()) {@@ -160,6 +153,8 @@ public class AssetDatapointResourceImpl extends ManagerWebResource implements Asnew WebApplicationException(Response.Status.NOT_FOUND));+ checkRestrictedAttributeRead(attribute);+return assetDatapointService.getDatapointPeriod(assetId, attributeName);} catch (IllegalStateException ex) {throw new BadRequestException(ex);@@ -196,9 +191,11 @@ public class AssetDatapointResourceImpl extends ManagerWebResource implements Asthrow new WebApplicationException(Response.Status.FORBIDDEN);}- asset.getAttribute(attributeRef.getName()).orElseThrow(() ->+ Attribute<?> attribute = asset.getAttribute(attributeRef.getName()).orElseThrow(() ->new WebApplicationException(Response.Status.NOT_FOUND));++ checkRestrictedAttributeRead(attribute);}DATA_EXPORT_LOG.info("User '" + getUsername() + "' started data export for " + attributeRefsString + " from " + fromTimestamp + " to " + toTimestamp + " in format " + format);@@ -242,4 +239,10 @@ public class AssetDatapointResourceImpl extends ManagerWebResource implements AsDATA_EXPORT_LOG.log(Level.SEVERE, "Failed to create piped output stream: ", ex);}}++ private void checkRestrictedAttributeRead(Attribute<?> attribute) {+ if (isRestrictedUser() && !attribute.getMeta().getValue(MetaItemType.ACCESS_RESTRICTED_READ).orElse(false)) {+ throw new WebApplicationException(Response.Status.FORBIDDEN);+ }+ }}diff --git a/test/src/test/groovy/org/openremote/test/assets/AssetDatapointExportTest.groovy b/test/src/test/groovy/org/openremote/test/assets/AssetDatapointExportTest.groovyindex f5fed168a..c634bb062 100644--- a/test/src/test/groovy/org/openremote/test/assets/AssetDatapointExportTest.groovy+++ b/test/src/test/groovy/org/openremote/test/assets/AssetDatapointExportTest.groovy@@ -5,6 +5,7 @@ import org.openremote.manager.datapoint.AssetDatapointServiceimport org.openremote.manager.setup.SetupServiceimport org.openremote.manager.web.ManagerWebServiceimport org.openremote.model.asset.impl.LightAsset+import org.openremote.model.attribute.Attributeimport org.openremote.model.attribute.AttributeRefimport org.openremote.model.datapoint.DatapointExportFormatimport org.openremote.model.datapoint.DatapointQueryTooLargeException@@ -12,6 +13,7 @@ import org.openremote.model.datapoint.ValueDatapointimport org.openremote.model.query.AssetQueryimport org.openremote.model.query.filter.RealmPredicateimport org.openremote.setup.integration.KeycloakTestSetup+import org.openremote.setup.integration.ManagerTestSetupimport org.openremote.test.ManagerContainerTraitimport spock.lang.Specificationimport spock.util.concurrent.PollingConditions@@ -21,6 +23,7 @@ import java.time.LocalDateTimeimport java.time.ZoneIdimport static org.openremote.model.Constants.KEYCLOAK_CLIENT_ID+import static org.openremote.model.value.ValueType.NUMBERclass AssetDatapointExportTest extends Specification implements ManagerContainerTrait {@@ -257,4 +260,123 @@ class AssetDatapointExportTest extends Specification implements ManagerContainerassetDatapointService.datapointExportLimit = assetDatapointService.OR_DATA_POINTS_EXPORT_LIMIT_DEFAULT}+ def "Restricted users cannot export datapoints for linked non-restricted attributes"() {+ given: "the container is started"+ def container = startContainer(defaultConfig(), defaultServices())+ def keycloakTestSetup = container.getService(SetupService.class).getTaskOfType(KeycloakTestSetup.class)+ def managerTestSetup = container.getService(SetupService.class).getTaskOfType(ManagerTestSetup.class)+ def assetStorageService = container.getService(AssetStorageService.class)+ def assetDatapointService = container.getService(AssetDatapointService.class)+ assetDatapointService.datapointExportLimit = 10000++ and: "a linked asset has historical data for an attribute that is not restricted-readable"+ assetDatapointService.purgeDataPoints()+ def asset = assetStorageService.find(managerTestSetup.apartment1Id, true)+ def attributeName = "nonRestrictedHistory"+ asset.getAttributes().addOrReplace(new Attribute<>(attributeName, NUMBER, 0d))+ assetStorageService.merge(asset)++ def dateTime = LocalDateTime.now()+ assetDatapointService.upsertValues(+ asset.getId(),+ attributeName,+ [new ValueDatapoint<>(dateTime.minusMinutes(1).atZone(ZoneId.systemDefault()).toInstant().toEpochMilli(), 42d)]+ )++ and: "a restricted user is authenticated in the asset realm"+ def accessToken = authenticate(+ container,+ keycloakTestSetup.realmBuilding.name,+ KEYCLOAK_CLIENT_ID,+ "testuser3",+ "testuser3"+ )+ when: "the restricted user exports the historical datapoints"+ def response = null+ def attributeRefsJson = "[{\"id\":\"${asset.id}\",\"name\":\"${attributeName}\"}]"+ def encodedAttributeRefs = URLEncoder.encode(attributeRefsJson, StandardCharsets.UTF_8.toString()).replace("+", "%20")+ def fromTimestamp = dateTime.minusMinutes(5).atZone(ZoneId.systemDefault()).toInstant().toEpochMilli()+ def toTimestamp = dateTime.atZone(ZoneId.systemDefault()).toInstant().toEpochMilli()+ def baseUri = serverUri(serverPort).clone()+ .replacePath(ManagerWebService.API_PATH)+ .path(keycloakTestSetup.realmBuilding.name)+ .path("asset")+ .path("datapoint")+ .path("export")+ .build()+ def url = new URL("${baseUri}?attributeRefs=${encodedAttributeRefs}&fromTimestamp=${fromTimestamp}&toTimestamp=${toTimestamp}")+ response = (HttpURLConnection) url.openConnection()+ response.setRequestMethod("GET")+ response.setRequestProperty("Authorization", "Bearer ${accessToken}")+ response.setRequestProperty("Accept", "application/zip")+ response.connect()++ then: "the export endpoint should apply the same restricted attribute check"+ response.responseCode == 403++ cleanup: "Remove the limit on datapoint exporting"+ if (response != null) {+ response.disconnect()+ }+ assetDatapointService.datapointExportLimit = assetDatapointService.OR_DATA_POINTS_EXPORT_LIMIT_DEFAULT+ }++ def "Restricted users cannot get datapoint periods for linked non-restricted attributes"() {+ given: "the container is started"+ def container = startContainer(defaultConfig(), defaultServices())+ def keycloakTestSetup = container.getService(SetupService.class).getTaskOfType(KeycloakTestSetup.class)+ def managerTestSetup = container.getService(SetupService.class).getTaskOfType(ManagerTestSetup.class)+ def assetStorageService = container.getService(AssetStorageService.class)+ def assetDatapointService = container.getService(AssetDatapointService.class)++ and: "a linked asset has historical data for an attribute that is not restricted-readable"+ assetDatapointService.purgeDataPoints()+ def asset = assetStorageService.find(managerTestSetup.apartment1Id, true)+ def attributeName = "nonRestrictedHistoryPeriod"+ asset.getAttributes().addOrReplace(new Attribute<>(attributeName, NUMBER, 0d))+ assetStorageService.merge(asset)++ def dateTime = LocalDateTime.now()+ assetDatapointService.upsertValues(+ asset.getId(),+ attributeName,+ [new ValueDatapoint<>(dateTime.minusMinutes(1).atZone(ZoneId.systemDefault()).toInstant().toEpochMilli(), 42d)]+ )++ and: "a restricted user is authenticated in the asset realm"+ def accessToken = authenticate(+ container,+ keycloakTestSetup.realmBuilding.name,+ KEYCLOAK_CLIENT_ID,+ "testuser3",+ "testuser3"+ )++ when: "the restricted user requests the historical datapoint period"+ def response = null+ def encodedAssetId = URLEncoder.encode(asset.id, StandardCharsets.UTF_8.toString()).replace("+", "%20")+ def encodedAttributeName = URLEncoder.encode(attributeName, StandardCharsets.UTF_8.toString()).replace("+", "%20")+ def baseUri = serverUri(serverPort).clone()+ .replacePath(ManagerWebService.API_PATH)+ .path(keycloakTestSetup.realmBuilding.name)+ .path("asset")+ .path("datapoint")+ .path("periods")+ .build()+ def url = new URL("${baseUri}?assetId=${encodedAssetId}&attributeName=${encodedAttributeName}")+ response = (HttpURLConnection) url.openConnection()+ response.setRequestMethod("GET")+ response.setRequestProperty("Authorization", "Bearer ${accessToken}")+ response.setRequestProperty("Accept", "application/json")+ response.connect()++ then: "the period endpoint should apply the same restricted attribute check"+ response.responseCode == 403++ cleanup:+ if (response != null) {+ response.disconnect()+ }+ }+}