diff --git a/.github/ISSUE_TEMPLATE/---bug-report.md b/.github/ISSUE_TEMPLATE/---bug-report.md
index 0fcae906b7..710834c877 100644
--- a/.github/ISSUE_TEMPLATE/---bug-report.md
+++ b/.github/ISSUE_TEMPLATE/---bug-report.md
@@ -3,7 +3,7 @@ name: "\U0001F41E Bug report"
about: Create a report to help us improve
title: "Your title here"
labels: ['bug', 'unconfirmed']
-assignees: Ultrazombie
+assignees: mykhailokornieiev
---
diff --git a/.github/ISSUE_TEMPLATE/feature_request.md b/.github/ISSUE_TEMPLATE/feature_request.md
index 9430e961d5..5c147395a7 100644
--- a/.github/ISSUE_TEMPLATE/feature_request.md
+++ b/.github/ISSUE_TEMPLATE/feature_request.md
@@ -3,7 +3,7 @@ name: Feature request
about: Suggest an idea for this project
title: "Your title here"
labels: ['feature']
-assignees: 'Ultrazombie'
+assignees: 'mykhailokornieiev'
---
diff --git a/.github/ISSUE_TEMPLATE/question.md b/.github/ISSUE_TEMPLATE/question.md
index 7f4becfe82..657614c987 100644
--- a/.github/ISSUE_TEMPLATE/question.md
+++ b/.github/ISSUE_TEMPLATE/question.md
@@ -3,7 +3,7 @@ name: Question
about: Describe your questions in detail
title: "Your title here"
labels: ['question']
-assignees: 'Ultrazombie'
+assignees: 'mykhailokornieiev'
---
diff --git a/application/pom.xml b/application/pom.xml
index f76b721bb0..82ab4cd113 100644
--- a/application/pom.xml
+++ b/application/pom.xml
@@ -10,7 +10,7 @@
4.0.0
org.thingsboard
- 4.4.1-SNAPSHOT
+ 4.4.2-SNAPSHOT
thingsboard
application
@@ -31,6 +31,7 @@
thingsboard
${project.build.directory}/windows
true
+ true
ThingsBoard
org.thingsboard.server.ThingsboardServerApplication
@@ -221,12 +222,28 @@
org.springframework.boot
- spring-boot-starter-web
+ spring-boot-starter-webmvc
org.springframework.boot
spring-boot-starter-websocket
+
+ org.springframework.boot
+ spring-boot-jackson2
+
+
+ org.springframework.boot
+ spring-boot-restclient
+
+
+ org.springframework.boot
+ spring-boot-security-oauth2-client
+
+
+ org.springframework.boot
+ spring-boot-validation
+
org.springframework.security
spring-security-oauth2-client
@@ -272,16 +289,16 @@
logback-classic
- com.sun.mail
- jakarta.mail
+ jakarta.mail
+ jakarta.mail-api
- jakarta.xml.bind
- jakarta.xml.bind-api
+ org.eclipse.angus
+ angus-mail
- javax.xml.bind
- jaxb-api
+ jakarta.xml.bind
+ jakarta.xml.bind-api
com.twilio.sdk
@@ -378,40 +395,31 @@
awaitility
test
-
- org.dbunit
- dbunit
- test
-
-
- com.github.springtestdbunit
- spring-test-dbunit
- test
-
org.testcontainers
- cassandra
+ testcontainers-cassandra
test
+
+
+ com.datastax.cassandra
+ cassandra-driver-core
+
+
org.testcontainers
- postgresql
+ testcontainers-postgresql
test
org.testcontainers
- jdbc
+ testcontainers-jdbc
test
org.thingsboard
netty-mqtt
-
- org.fusesource.jansi
- jansi
- 1.8
-
org.passay
passay
@@ -489,6 +497,12 @@
dev.langchain4j
langchain4j-open-ai-official
+
+
+ io.swagger.core.v3
+ swagger-annotations
+
+
dev.langchain4j
diff --git a/application/src/main/conf/logback.xml b/application/src/main/conf/logback.xml
index 3cc228810d..90766ff70a 100644
--- a/application/src/main/conf/logback.xml
+++ b/application/src/main/conf/logback.xml
@@ -52,7 +52,6 @@
System.err
- true
WARN
diff --git a/application/src/main/data/json/demo/dashboards/thermostats.json b/application/src/main/data/json/demo/dashboards/thermostats.json
index 04f8c1cf28..e1dfe54943 100644
--- a/application/src/main/data/json/demo/dashboards/thermostats.json
+++ b/application/src/main/data/json/demo/dashboards/thermostats.json
@@ -1303,17 +1303,6 @@
"label": "{i18n:widgets.maps.layer.roadmap}",
"provider": "openstreet",
"layerType": "OpenStreetMap.Mapnik"
- },
- {
- "label": "{i18n:widgets.maps.layer.satellite}",
- "provider": "openstreet",
- "layerType": "Esri.WorldImagery"
- },
- {
- "label": "{i18n:widgets.maps.layer.hybrid}",
- "provider": "openstreet",
- "layerType": "Esri.WorldImagery",
- "referenceLayer": "openstreetmap_hybrid"
}
],
"imageSource": null,
@@ -1561,17 +1550,6 @@
"label": "{i18n:widgets.maps.layer.roadmap}",
"provider": "openstreet",
"layerType": "OpenStreetMap.Mapnik"
- },
- {
- "label": "{i18n:widgets.maps.layer.satellite}",
- "provider": "openstreet",
- "layerType": "Esri.WorldImagery"
- },
- {
- "label": "{i18n:widgets.maps.layer.hybrid}",
- "provider": "openstreet",
- "layerType": "Esri.WorldImagery",
- "referenceLayer": "openstreetmap_hybrid"
}
],
"imageSource": null,
@@ -1820,17 +1798,6 @@
"label": "{i18n:widgets.maps.layer.roadmap}",
"provider": "openstreet",
"layerType": "OpenStreetMap.Mapnik"
- },
- {
- "label": "{i18n:widgets.maps.layer.satellite}",
- "provider": "openstreet",
- "layerType": "Esri.WorldImagery"
- },
- {
- "label": "{i18n:widgets.maps.layer.hybrid}",
- "provider": "openstreet",
- "layerType": "Esri.WorldImagery",
- "referenceLayer": "openstreetmap_hybrid"
}
],
"imageSource": null,
diff --git a/application/src/main/data/json/solutions/fleet_tracking/dashboards/mine_site_monitoring.json b/application/src/main/data/json/solutions/fleet_tracking/dashboards/mine_site_monitoring.json
index b4d4d923dc..b475a4085e 100644
--- a/application/src/main/data/json/solutions/fleet_tracking/dashboards/mine_site_monitoring.json
+++ b/application/src/main/data/json/solutions/fleet_tracking/dashboards/mine_site_monitoring.json
@@ -20,21 +20,10 @@
"settings": {
"mapType": "geoMap",
"layers": [
- {
- "label": "{i18n:widgets.maps.layer.hybrid}",
- "provider": "openstreet",
- "layerType": "Esri.WorldImagery",
- "referenceLayer": "openstreetmap_hybrid"
- },
{
"label": "{i18n:widgets.maps.layer.roadmap}",
"provider": "openstreet",
"layerType": "OpenStreetMap.Mapnik"
- },
- {
- "label": "{i18n:widgets.maps.layer.satellite}",
- "provider": "openstreet",
- "layerType": "Esri.WorldImagery"
}
],
"imageSource": null,
@@ -1284,21 +1273,10 @@
"settings": {
"mapType": "geoMap",
"layers": [
- {
- "label": "{i18n:widgets.maps.layer.satellite}",
- "provider": "openstreet",
- "layerType": "Esri.WorldImagery"
- },
{
"label": "{i18n:widgets.maps.layer.roadmap}",
"provider": "openstreet",
"layerType": "OpenStreetMap.Mapnik"
- },
- {
- "label": "{i18n:widgets.maps.layer.hybrid}",
- "provider": "openstreet",
- "layerType": "Esri.WorldImagery",
- "referenceLayer": "openstreetmap_hybrid"
}
],
"trips": [
@@ -2764,21 +2742,10 @@
"settings": {
"mapType": "geoMap",
"layers": [
- {
- "label": "{i18n:widgets.maps.layer.satellite}",
- "provider": "openstreet",
- "layerType": "Esri.WorldImagery"
- },
{
"label": "{i18n:widgets.maps.layer.roadmap}",
"provider": "openstreet",
"layerType": "OpenStreetMap.Mapnik"
- },
- {
- "label": "{i18n:widgets.maps.layer.hybrid}",
- "provider": "openstreet",
- "layerType": "Esri.WorldImagery",
- "referenceLayer": "openstreetmap_hybrid"
}
],
"trips": [
@@ -4371,21 +4338,10 @@
"settings": {
"mapType": "geoMap",
"layers": [
- {
- "label": "{i18n:widgets.maps.layer.satellite}",
- "provider": "openstreet",
- "layerType": "Esri.WorldImagery"
- },
{
"label": "{i18n:widgets.maps.layer.roadmap}",
"provider": "openstreet",
"layerType": "OpenStreetMap.Mapnik"
- },
- {
- "label": "{i18n:widgets.maps.layer.hybrid}",
- "provider": "openstreet",
- "layerType": "Esri.WorldImagery",
- "referenceLayer": "openstreetmap_hybrid"
}
],
"imageSource": null,
diff --git a/application/src/main/data/json/system/widget_types/google_map.json b/application/src/main/data/json/system/widget_types/google_map.json
index 26901b56a6..42214d3862 100644
--- a/application/src/main/data/json/system/widget_types/google_map.json
+++ b/application/src/main/data/json/system/widget_types/google_map.json
@@ -13,7 +13,7 @@
"templateCss": ".error {\n color: red;\n}\n.tb-labels {\n color: #222;\n font: 12px/1.5 \"Helvetica Neue\", Arial, Helvetica, sans-serif;\n text-align: center;\n width: 200px;\n white-space: nowrap;\n}",
"controllerScript": "self.onInit = function() {\n self.ctx.map = new TbMapWidgetV2('google-map', false, self.ctx);\n}\n\nself.onDataUpdated = function() {\n self.ctx.map.update();\n}\n\nself.onResize = function() {\n self.ctx.map.resize();\n}\n\nself.actionSources = function() {\n return TbMapWidgetV2.actionSources();\n}\n\nself.onDestroy = function() {\n self.ctx.map.destroy();\n}\n\nself.typeParameters = function() {\n return {\n hasDataPageLink: true\n };\n}",
"settingsDirective": "tb-map-widget-settings-legacy",
- "defaultConfig": "{\"datasources\":[{\"type\":\"function\",\"name\":\"First point\",\"entityAliasId\":null,\"filterId\":null,\"dataKeys\":[{\"name\":\"f(x)\",\"type\":\"function\",\"label\":\"latitude\",\"color\":\"#2196f3\",\"settings\":{},\"_hash\":0.05427416942713381,\"funcBody\":\"var value = prevValue || 15.833293;\\nif (time % 5000 < 500) {\\n value += Math.random() * 0.05 - 0.025;\\n}\\nreturn value;\"},{\"name\":\"f(x)\",\"type\":\"function\",\"label\":\"longitude\",\"color\":\"#4caf50\",\"settings\":{},\"_hash\":0.680594833308841,\"funcBody\":\"var value = prevValue || -90.454350;\\nif (time % 5000 < 500) {\\n value += Math.random() * 0.05 - 0.025;\\n}\\nreturn value;\"},{\"name\":\"f(x)\",\"type\":\"function\",\"label\":\"temperature\",\"color\":\"#9c27b0\",\"settings\":{},\"_hash\":0.9430343126300238,\"funcBody\":\"var value = prevValue + Math.random() * 40 - 20;\\nif (value < -60) {\\n\\tvalue = -60;\\n} else if (value > 60) {\\n\\tvalue = 60;\\n}\\nreturn value;\"},{\"name\":\"f(x)\",\"type\":\"function\",\"label\":\"Type\",\"color\":\"#8bc34a\",\"settings\":{},\"_hash\":0.1784452363910778,\"funcBody\":\"return \\\"colorpin\\\";\",\"units\":null,\"decimals\":null,\"usePostProcessing\":null,\"postFuncBody\":null}]},{\"type\":\"function\",\"name\":\"Second point\",\"entityAliasId\":null,\"filterId\":null,\"dataKeys\":[{\"name\":\"f(x)\",\"type\":\"function\",\"label\":\"latitude\",\"color\":\"#f44336\",\"settings\":{},\"_hash\":0.05012157428742059,\"funcBody\":\"var value = prevValue || 14.450463;\\nif (time % 4000 < 500) {\\n value += Math.random() * 0.05 - 0.025;\\n}\\nreturn value;\"},{\"name\":\"f(x)\",\"type\":\"function\",\"label\":\"longitude\",\"color\":\"#ffc107\",\"settings\":{},\"_hash\":0.6742359401617628,\"funcBody\":\"var value = prevValue || -84.845334;\\nif (time % 4000 < 500) {\\n value += Math.random() * 0.05 - 0.025;\\n}\\nreturn value;\"},{\"name\":\"f(x)\",\"type\":\"function\",\"label\":\"temperature\",\"color\":\"#8bc34a\",\"settings\":{},\"_hash\":0.773875863339494,\"funcBody\":\"var value = prevValue + Math.random() * 40 - 20;\\nif (value < -60) {\\n\\tvalue = -60;\\n} else if (value > 60) {\\n\\tvalue = 60;\\n}\\nreturn value;\"},{\"name\":\"f(x)\",\"type\":\"function\",\"label\":\"Type\",\"color\":\"#3f51b5\",\"settings\":{},\"_hash\":0.405822538899673,\"funcBody\":\"return \\\"thermometer\\\";\",\"units\":null,\"decimals\":null,\"usePostProcessing\":null,\"postFuncBody\":null}]}],\"showTitle\":true,\"backgroundColor\":\"#fff\",\"color\":\"rgba(0, 0, 0, 0.87)\",\"padding\":\"8px\",\"settings\":{\"provider\":\"google-map\",\"gmApiKey\":\"AIzaSyDoEx2kaGz3PxwbI9T7ccTSg5xjdw8Nw8Q\",\"gmDefaultMapType\":\"roadmap\",\"latKeyName\":\"latitude\",\"lngKeyName\":\"longitude\",\"xPosKeyName\":\"xPos\",\"yPosKeyName\":\"yPos\",\"defaultCenterPosition\":\"0,0\",\"disableScrollZooming\":false,\"disableDoubleClickZooming\":false,\"disableZoomControl\":false,\"fitMapBounds\":true,\"useDefaultCenterPosition\":false,\"mapPageSize\":16384,\"markerOffsetX\":0.5,\"markerOffsetY\":1,\"posFunction\":\"return {x: origXPos, y: origYPos};\",\"draggableMarker\":false,\"showLabel\":true,\"useLabelFunction\":false,\"label\":\"${entityName}\",\"showTooltip\":true,\"showTooltipAction\":\"click\",\"autocloseTooltip\":true,\"useTooltipFunction\":false,\"tooltipPattern\":\"${entityName}
Latitude: ${latitude:7}
Longitude: ${longitude:7}
Temperature: ${temperature} °C
See advanced settings for details\",\"tooltipOffsetX\":0,\"tooltipOffsetY\":-1,\"color\":\"#fe7568\",\"useColorFunction\":true,\"colorFunction\":\"var type = dsData[dsIndex]['Type'];\\nif (type == 'colorpin') {\\n\\tvar temperature = dsData[dsIndex]['temperature'];\\n\\tif (typeof temperature !== undefined) {\\n\\t var percent = (temperature + 60)/120 * 100;\\n\\t return tinycolor.mix('blue', 'red', percent).toHexString();\\n\\t}\\n\\treturn 'blue';\\n}\\n\",\"useMarkerImageFunction\":true,\"markerImageSize\":34,\"markerImageFunction\":\"var type = dsData[dsIndex]['Type'];\\nif (type == 'thermometer') {\\n\\tvar res = {\\n\\t url: images[0],\\n\\t size: 40\\n\\t}\\n\\tvar temperature = dsData[dsIndex]['temperature'];\\n\\tif (typeof temperature !== undefined) {\\n\\t var percent = (temperature + 60)/120;\\n\\t var index = Math.min(3, Math.floor(4 * percent));\\n\\t res.url = images[index];\\n\\t}\\n\\treturn res;\\n}\",\"markerImages\":[\"tb-image;/api/images/system/map_marker_image_0.png\",\"tb-image;/api/images/system/map_marker_image_1.png\",\"tb-image;/api/images/system/map_marker_image_2.png\",\"tb-image;/api/images/system/map_marker_image_3.png\"],\"showPolygon\":false,\"polygonKeyName\":\"perimeter\",\"editablePolygon\":false,\"showPolygonLabel\":false,\"usePolygonLabelFunction\":false,\"polygonLabel\":\"${entityName}\",\"showPolygonTooltip\":false,\"showPolygonTooltipAction\":\"click\",\"autoClosePolygonTooltip\":true,\"usePolygonTooltipFunction\":false,\"polygonTooltipPattern\":\"${entityName}
TimeStamp: ${ts:7}\",\"polygonColor\":\"#3388ff\",\"polygonOpacity\":0.2,\"usePolygonColorFunction\":false,\"polygonStrokeColor\":\"#3388ff\",\"polygonStrokeOpacity\":1,\"polygonStrokeWeight\":3,\"usePolygonStrokeColorFunction\":false,\"showCircle\":false,\"circleKeyName\":\"perimeter\",\"editableCircle\":false,\"showCircleLabel\":false,\"useCircleLabelFunction\":false,\"circleLabel\":\"${entityName}\",\"showCircleTooltip\":false,\"showCircleTooltipAction\":\"click\",\"autoCloseCircleTooltip\":true,\"useCircleTooltipFunction\":false,\"circleTooltipPattern\":\"${entityName}
TimeStamp: ${ts:7}\",\"circleFillColor\":\"#3388ff\",\"circleFillColorOpacity\":0.2,\"useCircleFillColorFunction\":false,\"circleStrokeColor\":\"#3388ff\",\"circleStrokeOpacity\":1,\"circleStrokeWeight\":3,\"useCircleStrokeColorFunction\":false,\"useClusterMarkers\":false,\"zoomOnClick\":true,\"maxClusterRadius\":80,\"animate\":true,\"spiderfyOnMaxZoom\":false,\"showCoverageOnHover\":true,\"chunkedLoading\":false,\"removeOutsideVisibleBounds\":true,\"useIconCreateFunction\":false},\"title\":\"Google Map\",\"dropShadow\":true,\"enableFullscreen\":true,\"titleStyle\":{\"fontSize\":\"16px\",\"fontWeight\":400},\"showLegend\":false,\"widgetStyle\":{},\"actions\":{}}"
+ "defaultConfig": "{\"datasources\":[{\"type\":\"function\",\"name\":\"First point\",\"entityAliasId\":null,\"filterId\":null,\"dataKeys\":[{\"name\":\"f(x)\",\"type\":\"function\",\"label\":\"latitude\",\"color\":\"#2196f3\",\"settings\":{},\"_hash\":0.05427416942713381,\"funcBody\":\"var value = prevValue || 15.833293;\\nif (time % 5000 < 500) {\\n value += Math.random() * 0.05 - 0.025;\\n}\\nreturn value;\"},{\"name\":\"f(x)\",\"type\":\"function\",\"label\":\"longitude\",\"color\":\"#4caf50\",\"settings\":{},\"_hash\":0.680594833308841,\"funcBody\":\"var value = prevValue || -90.454350;\\nif (time % 5000 < 500) {\\n value += Math.random() * 0.05 - 0.025;\\n}\\nreturn value;\"},{\"name\":\"f(x)\",\"type\":\"function\",\"label\":\"temperature\",\"color\":\"#9c27b0\",\"settings\":{},\"_hash\":0.9430343126300238,\"funcBody\":\"var value = prevValue + Math.random() * 40 - 20;\\nif (value < -60) {\\n\\tvalue = -60;\\n} else if (value > 60) {\\n\\tvalue = 60;\\n}\\nreturn value;\"},{\"name\":\"f(x)\",\"type\":\"function\",\"label\":\"Type\",\"color\":\"#8bc34a\",\"settings\":{},\"_hash\":0.1784452363910778,\"funcBody\":\"return \\\"colorpin\\\";\",\"units\":null,\"decimals\":null,\"usePostProcessing\":null,\"postFuncBody\":null}]},{\"type\":\"function\",\"name\":\"Second point\",\"entityAliasId\":null,\"filterId\":null,\"dataKeys\":[{\"name\":\"f(x)\",\"type\":\"function\",\"label\":\"latitude\",\"color\":\"#f44336\",\"settings\":{},\"_hash\":0.05012157428742059,\"funcBody\":\"var value = prevValue || 14.450463;\\nif (time % 4000 < 500) {\\n value += Math.random() * 0.05 - 0.025;\\n}\\nreturn value;\"},{\"name\":\"f(x)\",\"type\":\"function\",\"label\":\"longitude\",\"color\":\"#ffc107\",\"settings\":{},\"_hash\":0.6742359401617628,\"funcBody\":\"var value = prevValue || -84.845334;\\nif (time % 4000 < 500) {\\n value += Math.random() * 0.05 - 0.025;\\n}\\nreturn value;\"},{\"name\":\"f(x)\",\"type\":\"function\",\"label\":\"temperature\",\"color\":\"#8bc34a\",\"settings\":{},\"_hash\":0.773875863339494,\"funcBody\":\"var value = prevValue + Math.random() * 40 - 20;\\nif (value < -60) {\\n\\tvalue = -60;\\n} else if (value > 60) {\\n\\tvalue = 60;\\n}\\nreturn value;\"},{\"name\":\"f(x)\",\"type\":\"function\",\"label\":\"Type\",\"color\":\"#3f51b5\",\"settings\":{},\"_hash\":0.405822538899673,\"funcBody\":\"return \\\"thermometer\\\";\",\"units\":null,\"decimals\":null,\"usePostProcessing\":null,\"postFuncBody\":null}]}],\"showTitle\":true,\"backgroundColor\":\"#fff\",\"color\":\"rgba(0, 0, 0, 0.87)\",\"padding\":\"8px\",\"settings\":{\"provider\":\"google-map\",\"gmApiKey\":null,\"gmDefaultMapType\":\"roadmap\",\"latKeyName\":\"latitude\",\"lngKeyName\":\"longitude\",\"xPosKeyName\":\"xPos\",\"yPosKeyName\":\"yPos\",\"defaultCenterPosition\":\"0,0\",\"disableScrollZooming\":false,\"disableDoubleClickZooming\":false,\"disableZoomControl\":false,\"fitMapBounds\":true,\"useDefaultCenterPosition\":false,\"mapPageSize\":16384,\"markerOffsetX\":0.5,\"markerOffsetY\":1,\"posFunction\":\"return {x: origXPos, y: origYPos};\",\"draggableMarker\":false,\"showLabel\":true,\"useLabelFunction\":false,\"label\":\"${entityName}\",\"showTooltip\":true,\"showTooltipAction\":\"click\",\"autocloseTooltip\":true,\"useTooltipFunction\":false,\"tooltipPattern\":\"${entityName}
Latitude: ${latitude:7}
Longitude: ${longitude:7}
Temperature: ${temperature} °C
See advanced settings for details\",\"tooltipOffsetX\":0,\"tooltipOffsetY\":-1,\"color\":\"#fe7568\",\"useColorFunction\":true,\"colorFunction\":\"var type = dsData[dsIndex]['Type'];\\nif (type == 'colorpin') {\\n\\tvar temperature = dsData[dsIndex]['temperature'];\\n\\tif (typeof temperature !== undefined) {\\n\\t var percent = (temperature + 60)/120 * 100;\\n\\t return tinycolor.mix('blue', 'red', percent).toHexString();\\n\\t}\\n\\treturn 'blue';\\n}\\n\",\"useMarkerImageFunction\":true,\"markerImageSize\":34,\"markerImageFunction\":\"var type = dsData[dsIndex]['Type'];\\nif (type == 'thermometer') {\\n\\tvar res = {\\n\\t url: images[0],\\n\\t size: 40\\n\\t}\\n\\tvar temperature = dsData[dsIndex]['temperature'];\\n\\tif (typeof temperature !== undefined) {\\n\\t var percent = (temperature + 60)/120;\\n\\t var index = Math.min(3, Math.floor(4 * percent));\\n\\t res.url = images[index];\\n\\t}\\n\\treturn res;\\n}\",\"markerImages\":[\"tb-image;/api/images/system/map_marker_image_0.png\",\"tb-image;/api/images/system/map_marker_image_1.png\",\"tb-image;/api/images/system/map_marker_image_2.png\",\"tb-image;/api/images/system/map_marker_image_3.png\"],\"showPolygon\":false,\"polygonKeyName\":\"perimeter\",\"editablePolygon\":false,\"showPolygonLabel\":false,\"usePolygonLabelFunction\":false,\"polygonLabel\":\"${entityName}\",\"showPolygonTooltip\":false,\"showPolygonTooltipAction\":\"click\",\"autoClosePolygonTooltip\":true,\"usePolygonTooltipFunction\":false,\"polygonTooltipPattern\":\"${entityName}
TimeStamp: ${ts:7}\",\"polygonColor\":\"#3388ff\",\"polygonOpacity\":0.2,\"usePolygonColorFunction\":false,\"polygonStrokeColor\":\"#3388ff\",\"polygonStrokeOpacity\":1,\"polygonStrokeWeight\":3,\"usePolygonStrokeColorFunction\":false,\"showCircle\":false,\"circleKeyName\":\"perimeter\",\"editableCircle\":false,\"showCircleLabel\":false,\"useCircleLabelFunction\":false,\"circleLabel\":\"${entityName}\",\"showCircleTooltip\":false,\"showCircleTooltipAction\":\"click\",\"autoCloseCircleTooltip\":true,\"useCircleTooltipFunction\":false,\"circleTooltipPattern\":\"${entityName}
TimeStamp: ${ts:7}\",\"circleFillColor\":\"#3388ff\",\"circleFillColorOpacity\":0.2,\"useCircleFillColorFunction\":false,\"circleStrokeColor\":\"#3388ff\",\"circleStrokeOpacity\":1,\"circleStrokeWeight\":3,\"useCircleStrokeColorFunction\":false,\"useClusterMarkers\":false,\"zoomOnClick\":true,\"maxClusterRadius\":80,\"animate\":true,\"spiderfyOnMaxZoom\":false,\"showCoverageOnHover\":true,\"chunkedLoading\":false,\"removeOutsideVisibleBounds\":true,\"useIconCreateFunction\":false},\"title\":\"Google Map\",\"dropShadow\":true,\"enableFullscreen\":true,\"titleStyle\":{\"fontSize\":\"16px\",\"fontWeight\":400},\"showLegend\":false,\"widgetStyle\":{},\"actions\":{}}"
},
"tags": [
"mapping",
diff --git a/application/src/main/data/json/system/widget_types/here_map.json b/application/src/main/data/json/system/widget_types/here_map.json
index c57fff50c3..718d571a57 100644
--- a/application/src/main/data/json/system/widget_types/here_map.json
+++ b/application/src/main/data/json/system/widget_types/here_map.json
@@ -13,7 +13,7 @@
"templateCss": ".leaflet-zoom-box {\n\tz-index: 9;\n}\n\n.leaflet-pane { z-index: 4; }\n\n.leaflet-tile-pane { z-index: 2; }\n.leaflet-overlay-pane { z-index: 4; }\n.leaflet-shadow-pane { z-index: 5; }\n.leaflet-marker-pane { z-index: 6; }\n.leaflet-tooltip-pane { z-index: 7; }\n.leaflet-popup-pane { z-index: 8; }\n\n.leaflet-map-pane canvas { z-index: 1; }\n.leaflet-map-pane svg { z-index: 2; }\n\n.leaflet-control {\n\tz-index: 9;\n}\n.leaflet-top,\n.leaflet-bottom {\n\tz-index: 11;\n}\n\n.tb-marker-label {\n border: none;\n background: none;\n box-shadow: none;\n}\n\n.tb-marker-label:before {\n border: none;\n background: none;\n}\n",
"controllerScript": "self.onInit = function() {\n self.ctx.map = new TbMapWidgetV2('here', false, self.ctx);\n}\n\nself.onDataUpdated = function() {\n self.ctx.map.update();\n}\n\nself.onResize = function() {\n self.ctx.map.resize();\n}\n\nself.actionSources = function() {\n return TbMapWidgetV2.actionSources();\n}\n\nself.onDestroy = function() {\n self.ctx.map.destroy();\n}\n\nself.typeParameters = function() {\n return {\n hasDataPageLink: true\n };\n}",
"settingsDirective": "tb-map-widget-settings-legacy",
- "defaultConfig": "{\"datasources\":[{\"type\":\"function\",\"name\":\"First point\",\"entityAliasId\":null,\"filterId\":null,\"dataKeys\":[{\"name\":\"f(x)\",\"type\":\"function\",\"label\":\"latitude\",\"color\":\"#2196f3\",\"settings\":{},\"_hash\":0.05427416942713381,\"funcBody\":\"var value = prevValue || 15.833293;\\nif (time % 5000 < 500) {\\n value += Math.random() * 0.05 - 0.025;\\n}\\nreturn value;\"},{\"name\":\"f(x)\",\"type\":\"function\",\"label\":\"longitude\",\"color\":\"#4caf50\",\"settings\":{},\"_hash\":0.680594833308841,\"funcBody\":\"var value = prevValue || -90.454350;\\nif (time % 5000 < 500) {\\n value += Math.random() * 0.05 - 0.025;\\n}\\nreturn value;\"},{\"name\":\"f(x)\",\"type\":\"function\",\"label\":\"temperature\",\"color\":\"#9c27b0\",\"settings\":{},\"_hash\":0.9430343126300238,\"funcBody\":\"var value = prevValue + Math.random() * 40 - 20;\\nif (value < -60) {\\n\\tvalue = -60;\\n} else if (value > 60) {\\n\\tvalue = 60;\\n}\\nreturn value;\"},{\"name\":\"f(x)\",\"type\":\"function\",\"label\":\"Type\",\"color\":\"#8bc34a\",\"settings\":{},\"_hash\":0.1784452363910778,\"funcBody\":\"return \\\"colorpin\\\";\",\"units\":null,\"decimals\":null,\"usePostProcessing\":null,\"postFuncBody\":null}]},{\"type\":\"function\",\"name\":\"Second point\",\"entityAliasId\":null,\"filterId\":null,\"dataKeys\":[{\"name\":\"f(x)\",\"type\":\"function\",\"label\":\"latitude\",\"color\":\"#f44336\",\"settings\":{},\"_hash\":0.05012157428742059,\"funcBody\":\"var value = prevValue || 14.450463;\\nif (time % 4000 < 500) {\\n value += Math.random() * 0.05 - 0.025;\\n}\\nreturn value;\"},{\"name\":\"f(x)\",\"type\":\"function\",\"label\":\"longitude\",\"color\":\"#ffc107\",\"settings\":{},\"_hash\":0.6742359401617628,\"funcBody\":\"var value = prevValue || -84.845334;\\nif (time % 4000 < 500) {\\n value += Math.random() * 0.05 - 0.025;\\n}\\nreturn value;\"},{\"name\":\"f(x)\",\"type\":\"function\",\"label\":\"temperature\",\"color\":\"#8bc34a\",\"settings\":{},\"_hash\":0.773875863339494,\"funcBody\":\"var value = prevValue + Math.random() * 40 - 20;\\nif (value < -60) {\\n\\tvalue = -60;\\n} else if (value > 60) {\\n\\tvalue = 60;\\n}\\nreturn value;\"},{\"name\":\"f(x)\",\"type\":\"function\",\"label\":\"Type\",\"color\":\"#3f51b5\",\"settings\":{},\"_hash\":0.405822538899673,\"funcBody\":\"return \\\"thermometer\\\";\",\"units\":null,\"decimals\":null,\"usePostProcessing\":null,\"postFuncBody\":null}]}],\"showTitle\":true,\"backgroundColor\":\"#fff\",\"color\":\"rgba(0, 0, 0, 0.87)\",\"padding\":\"8px\",\"settings\":{\"provider\":\"here\",\"gmApiKey\":\"AIzaSyDoEx2kaGz3PxwbI9T7ccTSg5xjdw8Nw8Q\",\"gmDefaultMapType\":\"roadmap\",\"mapProvider\":\"HERE.normalDay\",\"useCustomProvider\":false,\"customProviderTileUrl\":\"https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png\",\"mapProviderHere\":\"HERE.normalDay\",\"credentials\":{\"useV3\":true,\"apiKey\":\"kVXykxAfZ6LS4EbCTO02soFVfjA7HoBzNVVH9u7nzoE\"},\"mapImageUrl\":\"tb-image;/api/images/system/air_quality_monitoring_dashboard_widget_new_openstreetmap_map_image.svg\",\"tmApiKey\":\"84d6d83e0e51e481e50454ccbe8986b\",\"tmDefaultMapType\":\"roadmap\",\"latKeyName\":\"latitude\",\"lngKeyName\":\"longitude\",\"xPosKeyName\":\"xPos\",\"yPosKeyName\":\"yPos\",\"defaultCenterPosition\":\"0,0\",\"disableScrollZooming\":false,\"disableDoubleClickZooming\":false,\"disableZoomControl\":false,\"fitMapBounds\":true,\"useDefaultCenterPosition\":false,\"mapPageSize\":16384,\"markerOffsetX\":0.5,\"markerOffsetY\":1,\"posFunction\":\"return {x: origXPos, y: origYPos};\",\"draggableMarker\":false,\"showLabel\":true,\"useLabelFunction\":false,\"label\":\"${entityName}\",\"showTooltip\":true,\"showTooltipAction\":\"click\",\"autocloseTooltip\":true,\"useTooltipFunction\":false,\"tooltipPattern\":\"${entityName}
Latitude: ${latitude:7}
Longitude: ${longitude:7}
Temperature: ${temperature} °C
See advanced settings for details\",\"tooltipOffsetX\":0,\"tooltipOffsetY\":-1,\"color\":\"#fe7569\",\"useColorFunction\":true,\"colorFunction\":\"var type = dsData[dsIndex]['Type'];\\nif (type == 'colorpin') {\\n\\tvar temperature = dsData[dsIndex]['temperature'];\\n\\tif (typeof temperature !== undefined) {\\n\\t var percent = (temperature + 60)/120 * 100;\\n\\t return tinycolor.mix('blue', 'red', percent).toHexString();\\n\\t}\\n\\treturn 'blue';\\n}\\n\",\"useMarkerImageFunction\":true,\"markerImageSize\":34,\"markerImageFunction\":\"var type = dsData[dsIndex]['Type'];\\nif (type == 'thermometer') {\\n\\tvar res = {\\n\\t url: images[0],\\n\\t size: 40\\n\\t}\\n\\tvar temperature = dsData[dsIndex]['temperature'];\\n\\tif (typeof temperature !== undefined) {\\n\\t var percent = (temperature + 60)/120;\\n\\t var index = Math.min(3, Math.floor(4 * percent));\\n\\t res.url = images[index];\\n\\t}\\n\\treturn res;\\n}\",\"markerImages\":[\"tb-image;/api/images/system/map_marker_image_0.png\",\"tb-image;/api/images/system/map_marker_image_1.png\",\"tb-image;/api/images/system/map_marker_image_2.png\",\"tb-image;/api/images/system/map_marker_image_3.png\"],\"showPolygon\":false,\"polygonKeyName\":\"coordinates\",\"editablePolygon\":false,\"showPolygonLabel\":false,\"usePolygonLabelFunction\":false,\"polygonLabel\":\"${entityName}\",\"showPolygonTooltip\":false,\"showPolygonTooltipAction\":\"click\",\"autoClosePolygonTooltip\":true,\"usePolygonTooltipFunction\":false,\"polygonTooltipPattern\":\"${entityName}
TimeStamp: ${ts:7}\",\"polygonColor\":\"#3388ff\",\"polygonOpacity\":0.5,\"usePolygonColorFunction\":false,\"polygonStrokeColor\":\"#3388ff\",\"polygonStrokeOpacity\":1,\"polygonStrokeWeight\":1,\"usePolygonStrokeColorFunction\":false,\"showCircle\":false,\"circleKeyName\":\"perimeter\",\"editableCircle\":false,\"showCircleLabel\":false,\"useCircleLabelFunction\":false,\"circleLabel\":\"${entityName}\",\"showCircleTooltip\":false,\"showCircleTooltipAction\":\"click\",\"autoCloseCircleTooltip\":true,\"useCircleTooltipFunction\":false,\"circleTooltipPattern\":\"${entityName}
TimeStamp: ${ts:7}\",\"circleFillColor\":\"#3388ff\",\"circleFillColorOpacity\":0.2,\"useCircleFillColorFunction\":false,\"circleStrokeColor\":\"#3388ff\",\"circleStrokeOpacity\":1,\"circleStrokeWeight\":3,\"useCircleStrokeColorFunction\":false,\"useClusterMarkers\":false,\"zoomOnClick\":true,\"maxClusterRadius\":80,\"animate\":true,\"spiderfyOnMaxZoom\":false,\"showCoverageOnHover\":true,\"chunkedLoading\":false,\"removeOutsideVisibleBounds\":true,\"useIconCreateFunction\":false},\"title\":\"HERE Map\",\"dropShadow\":true,\"enableFullscreen\":true,\"titleStyle\":{\"fontSize\":\"16px\",\"fontWeight\":400},\"showLegend\":false,\"widgetStyle\":{},\"actions\":{}}"
+ "defaultConfig": "{\"datasources\":[{\"type\":\"function\",\"name\":\"First point\",\"entityAliasId\":null,\"filterId\":null,\"dataKeys\":[{\"name\":\"f(x)\",\"type\":\"function\",\"label\":\"latitude\",\"color\":\"#2196f3\",\"settings\":{},\"_hash\":0.05427416942713381,\"funcBody\":\"var value = prevValue || 15.833293;\\nif (time % 5000 < 500) {\\n value += Math.random() * 0.05 - 0.025;\\n}\\nreturn value;\"},{\"name\":\"f(x)\",\"type\":\"function\",\"label\":\"longitude\",\"color\":\"#4caf50\",\"settings\":{},\"_hash\":0.680594833308841,\"funcBody\":\"var value = prevValue || -90.454350;\\nif (time % 5000 < 500) {\\n value += Math.random() * 0.05 - 0.025;\\n}\\nreturn value;\"},{\"name\":\"f(x)\",\"type\":\"function\",\"label\":\"temperature\",\"color\":\"#9c27b0\",\"settings\":{},\"_hash\":0.9430343126300238,\"funcBody\":\"var value = prevValue + Math.random() * 40 - 20;\\nif (value < -60) {\\n\\tvalue = -60;\\n} else if (value > 60) {\\n\\tvalue = 60;\\n}\\nreturn value;\"},{\"name\":\"f(x)\",\"type\":\"function\",\"label\":\"Type\",\"color\":\"#8bc34a\",\"settings\":{},\"_hash\":0.1784452363910778,\"funcBody\":\"return \\\"colorpin\\\";\",\"units\":null,\"decimals\":null,\"usePostProcessing\":null,\"postFuncBody\":null}]},{\"type\":\"function\",\"name\":\"Second point\",\"entityAliasId\":null,\"filterId\":null,\"dataKeys\":[{\"name\":\"f(x)\",\"type\":\"function\",\"label\":\"latitude\",\"color\":\"#f44336\",\"settings\":{},\"_hash\":0.05012157428742059,\"funcBody\":\"var value = prevValue || 14.450463;\\nif (time % 4000 < 500) {\\n value += Math.random() * 0.05 - 0.025;\\n}\\nreturn value;\"},{\"name\":\"f(x)\",\"type\":\"function\",\"label\":\"longitude\",\"color\":\"#ffc107\",\"settings\":{},\"_hash\":0.6742359401617628,\"funcBody\":\"var value = prevValue || -84.845334;\\nif (time % 4000 < 500) {\\n value += Math.random() * 0.05 - 0.025;\\n}\\nreturn value;\"},{\"name\":\"f(x)\",\"type\":\"function\",\"label\":\"temperature\",\"color\":\"#8bc34a\",\"settings\":{},\"_hash\":0.773875863339494,\"funcBody\":\"var value = prevValue + Math.random() * 40 - 20;\\nif (value < -60) {\\n\\tvalue = -60;\\n} else if (value > 60) {\\n\\tvalue = 60;\\n}\\nreturn value;\"},{\"name\":\"f(x)\",\"type\":\"function\",\"label\":\"Type\",\"color\":\"#3f51b5\",\"settings\":{},\"_hash\":0.405822538899673,\"funcBody\":\"return \\\"thermometer\\\";\",\"units\":null,\"decimals\":null,\"usePostProcessing\":null,\"postFuncBody\":null}]}],\"showTitle\":true,\"backgroundColor\":\"#fff\",\"color\":\"rgba(0, 0, 0, 0.87)\",\"padding\":\"8px\",\"settings\":{\"provider\":\"here\",\"gmApiKey\":null,\"gmDefaultMapType\":\"roadmap\",\"mapProvider\":\"HERE.normalDay\",\"useCustomProvider\":false,\"customProviderTileUrl\":\"https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png\",\"mapProviderHere\":\"HERE.normalDay\",\"credentials\":{\"useV3\":true,\"apiKey\":null},\"mapImageUrl\":\"tb-image;/api/images/system/air_quality_monitoring_dashboard_widget_new_openstreetmap_map_image.svg\",\"tmApiKey\":\"84d6d83e0e51e481e50454ccbe8986b\",\"tmDefaultMapType\":\"roadmap\",\"latKeyName\":\"latitude\",\"lngKeyName\":\"longitude\",\"xPosKeyName\":\"xPos\",\"yPosKeyName\":\"yPos\",\"defaultCenterPosition\":\"0,0\",\"disableScrollZooming\":false,\"disableDoubleClickZooming\":false,\"disableZoomControl\":false,\"fitMapBounds\":true,\"useDefaultCenterPosition\":false,\"mapPageSize\":16384,\"markerOffsetX\":0.5,\"markerOffsetY\":1,\"posFunction\":\"return {x: origXPos, y: origYPos};\",\"draggableMarker\":false,\"showLabel\":true,\"useLabelFunction\":false,\"label\":\"${entityName}\",\"showTooltip\":true,\"showTooltipAction\":\"click\",\"autocloseTooltip\":true,\"useTooltipFunction\":false,\"tooltipPattern\":\"${entityName}
Latitude: ${latitude:7}
Longitude: ${longitude:7}
Temperature: ${temperature} °C
See advanced settings for details\",\"tooltipOffsetX\":0,\"tooltipOffsetY\":-1,\"color\":\"#fe7569\",\"useColorFunction\":true,\"colorFunction\":\"var type = dsData[dsIndex]['Type'];\\nif (type == 'colorpin') {\\n\\tvar temperature = dsData[dsIndex]['temperature'];\\n\\tif (typeof temperature !== undefined) {\\n\\t var percent = (temperature + 60)/120 * 100;\\n\\t return tinycolor.mix('blue', 'red', percent).toHexString();\\n\\t}\\n\\treturn 'blue';\\n}\\n\",\"useMarkerImageFunction\":true,\"markerImageSize\":34,\"markerImageFunction\":\"var type = dsData[dsIndex]['Type'];\\nif (type == 'thermometer') {\\n\\tvar res = {\\n\\t url: images[0],\\n\\t size: 40\\n\\t}\\n\\tvar temperature = dsData[dsIndex]['temperature'];\\n\\tif (typeof temperature !== undefined) {\\n\\t var percent = (temperature + 60)/120;\\n\\t var index = Math.min(3, Math.floor(4 * percent));\\n\\t res.url = images[index];\\n\\t}\\n\\treturn res;\\n}\",\"markerImages\":[\"tb-image;/api/images/system/map_marker_image_0.png\",\"tb-image;/api/images/system/map_marker_image_1.png\",\"tb-image;/api/images/system/map_marker_image_2.png\",\"tb-image;/api/images/system/map_marker_image_3.png\"],\"showPolygon\":false,\"polygonKeyName\":\"coordinates\",\"editablePolygon\":false,\"showPolygonLabel\":false,\"usePolygonLabelFunction\":false,\"polygonLabel\":\"${entityName}\",\"showPolygonTooltip\":false,\"showPolygonTooltipAction\":\"click\",\"autoClosePolygonTooltip\":true,\"usePolygonTooltipFunction\":false,\"polygonTooltipPattern\":\"${entityName}
TimeStamp: ${ts:7}\",\"polygonColor\":\"#3388ff\",\"polygonOpacity\":0.5,\"usePolygonColorFunction\":false,\"polygonStrokeColor\":\"#3388ff\",\"polygonStrokeOpacity\":1,\"polygonStrokeWeight\":1,\"usePolygonStrokeColorFunction\":false,\"showCircle\":false,\"circleKeyName\":\"perimeter\",\"editableCircle\":false,\"showCircleLabel\":false,\"useCircleLabelFunction\":false,\"circleLabel\":\"${entityName}\",\"showCircleTooltip\":false,\"showCircleTooltipAction\":\"click\",\"autoCloseCircleTooltip\":true,\"useCircleTooltipFunction\":false,\"circleTooltipPattern\":\"${entityName}
TimeStamp: ${ts:7}\",\"circleFillColor\":\"#3388ff\",\"circleFillColorOpacity\":0.2,\"useCircleFillColorFunction\":false,\"circleStrokeColor\":\"#3388ff\",\"circleStrokeOpacity\":1,\"circleStrokeWeight\":3,\"useCircleStrokeColorFunction\":false,\"useClusterMarkers\":false,\"zoomOnClick\":true,\"maxClusterRadius\":80,\"animate\":true,\"spiderfyOnMaxZoom\":false,\"showCoverageOnHover\":true,\"chunkedLoading\":false,\"removeOutsideVisibleBounds\":true,\"useIconCreateFunction\":false},\"title\":\"HERE Map\",\"dropShadow\":true,\"enableFullscreen\":true,\"titleStyle\":{\"fontSize\":\"16px\",\"fontWeight\":400},\"showLegend\":false,\"widgetStyle\":{},\"actions\":{}}"
},
"tags": [
"mapping",
diff --git a/application/src/main/data/json/system/widget_types/markers_placement___google_maps.json b/application/src/main/data/json/system/widget_types/markers_placement___google_maps.json
index 674cd6e06e..d4d416a471 100644
--- a/application/src/main/data/json/system/widget_types/markers_placement___google_maps.json
+++ b/application/src/main/data/json/system/widget_types/markers_placement___google_maps.json
@@ -13,7 +13,7 @@
"templateCss": ".error {\n color: red;\n}\n.tb-labels {\n color: #222;\n font: 12px/1.5 \"Helvetica Neue\", Arial, Helvetica, sans-serif;\n text-align: center;\n width: 200px;\n white-space: nowrap;\n}",
"controllerScript": "self.onInit = function() {\n self.ctx.map = new TbMapWidgetV2('google-map', false, self.ctx, null, true);\n}\n\nself.onDataUpdated = function() {\n self.ctx.map.update();\n}\n\nself.onResize = function() {\n self.ctx.map.resize();\n}\n\nself.actionSources = function() {\n return TbMapWidgetV2.actionSources();\n}\n\nself.onDestroy = function() {\n self.ctx.map.destroy();\n}\n\nself.typeParameters = function() {\n return {\n hasDataPageLink: true\n };\n}",
"settingsDirective": "tb-map-widget-settings-legacy",
- "defaultConfig": "{\"datasources\":[{\"type\":\"function\",\"name\":\"First point\",\"dataKeys\":[{\"name\":\"f(x)\",\"type\":\"function\",\"label\":\"latitude\",\"color\":\"#2196f3\",\"settings\":{},\"_hash\":0.05427416942713381,\"funcBody\":\"var value = prevValue || 15.833293;\\nif (time % 5000 < 500) {\\n value += Math.random() * 0.05 - 0.025;\\n}\\nreturn value;\"},{\"name\":\"f(x)\",\"type\":\"function\",\"label\":\"longitude\",\"color\":\"#4caf50\",\"settings\":{},\"_hash\":0.680594833308841,\"funcBody\":\"var value = prevValue || -90.454350;\\nif (time % 5000 < 500) {\\n value += Math.random() * 0.05 - 0.025;\\n}\\nreturn value;\"}]},{\"type\":\"function\",\"name\":\"Second point\",\"dataKeys\":[{\"name\":\"f(x)\",\"type\":\"function\",\"label\":\"latitude\",\"color\":\"#f44336\",\"settings\":{},\"_hash\":0.05012157428742059,\"funcBody\":\"var value = prevValue || 14.450463;\\nif (time % 4000 < 500) {\\n value += Math.random() * 0.05 - 0.025;\\n}\\nreturn value;\"},{\"name\":\"f(x)\",\"type\":\"function\",\"label\":\"longitude\",\"color\":\"#ffc107\",\"settings\":{},\"_hash\":0.6742359401617628,\"funcBody\":\"var value = prevValue || -84.845334;\\nif (time % 4000 < 500) {\\n value += Math.random() * 0.05 - 0.025;\\n}\\nreturn value;\"}]}],\"showTitle\":true,\"backgroundColor\":\"#fff\",\"color\":\"rgba(0, 0, 0, 0.87)\",\"padding\":\"8px\",\"settings\":{\"fitMapBounds\":true,\"latKeyName\":\"latitude\",\"lngKeyName\":\"longitude\",\"showLabel\":true,\"label\":\"${entityName}\",\"tooltipPattern\":\"${entityName}
Latitude: ${latitude:7}
Longitude: ${longitude:7}
Delete\",\"markerImageSize\":34,\"gmDefaultMapType\":\"roadmap\",\"gmApiKey\":\"AIzaSyDoEx2kaGz3PxwbI9T7ccTSg5xjdw8Nw8Q\",\"useColorFunction\":false,\"markerImages\":[],\"useMarkerImageFunction\":false,\"colorFunction\":\"\\n\",\"color\":\"#fe7569\",\"showTooltip\":true,\"autocloseTooltip\":true,\"defaultCenterPosition\":\"0,0\",\"showTooltipAction\":\"click\",\"polygonKeyName\":\"coordinates\",\"polygonOpacity\":0.5,\"polygonStrokeOpacity\":1,\"polygonStrokeWeight\":1,\"zoomOnClick\":true,\"defaultZoomLevel\":5,\"provider\":\"google-map\",\"showCoverageOnHover\":true,\"animate\":true,\"maxClusterRadius\":80,\"removeOutsideVisibleBounds\":true,\"mapProvider\":\"HERE.normalDay\",\"draggableMarker\":true,\"editablePolygon\":true,\"mapPageSize\":16384,\"showPolygon\":false,\"polygonTooltipPattern\":\"${entityName}
TimeStamp: ${coordinates|ts:7}
Delete\",\"showPolygonTooltip\":false},\"title\":\"Markers Placement - Google Maps\",\"dropShadow\":true,\"enableFullscreen\":true,\"titleStyle\":{\"fontSize\":\"16px\",\"fontWeight\":400},\"showLegend\":false,\"widgetStyle\":{},\"actions\":{\"tooltipAction\":[{\"name\":\"delete\",\"icon\":\"more_horiz\",\"type\":\"custom\",\"customFunction\":\"var entityDatasource = widgetContext.map.map.datasources.filter(\\n function(entity) {\\n return entity.entityId === entityId.id;\\n });\\n\\nwidgetContext.map.setMarkerLocation(entityDatasource[0], null, null).subscribe(() => widgetContext.updateAliases());\",\"id\":\"8d3c0156-0a14-7a6f-0ddd-0ec16b9ffc91\"},{\"name\":\"delete_polygon\",\"icon\":\"more_horiz\",\"type\":\"custom\",\"customFunction\":\"var entityDatasource = widgetContext.map.map.datasources.filter(\\n function(entity) {\\n return entity.entityId === entityId.id\\n });\\n\\nwidgetContext.map.savePolygonLocation(entityDatasource[0], null).subscribe(() => widgetContext.updateAliases());\",\"id\":\"46bf69cd-8906-234c-a879-e2e4c92f5b67\"}]},\"showTitleIcon\":false,\"titleIcon\":\"more_horiz\",\"iconColor\":\"rgba(0, 0, 0, 0.87)\",\"iconSize\":\"24px\",\"titleTooltip\":\"\"}"
+ "defaultConfig": "{\"datasources\":[{\"type\":\"function\",\"name\":\"First point\",\"dataKeys\":[{\"name\":\"f(x)\",\"type\":\"function\",\"label\":\"latitude\",\"color\":\"#2196f3\",\"settings\":{},\"_hash\":0.05427416942713381,\"funcBody\":\"var value = prevValue || 15.833293;\\nif (time % 5000 < 500) {\\n value += Math.random() * 0.05 - 0.025;\\n}\\nreturn value;\"},{\"name\":\"f(x)\",\"type\":\"function\",\"label\":\"longitude\",\"color\":\"#4caf50\",\"settings\":{},\"_hash\":0.680594833308841,\"funcBody\":\"var value = prevValue || -90.454350;\\nif (time % 5000 < 500) {\\n value += Math.random() * 0.05 - 0.025;\\n}\\nreturn value;\"}]},{\"type\":\"function\",\"name\":\"Second point\",\"dataKeys\":[{\"name\":\"f(x)\",\"type\":\"function\",\"label\":\"latitude\",\"color\":\"#f44336\",\"settings\":{},\"_hash\":0.05012157428742059,\"funcBody\":\"var value = prevValue || 14.450463;\\nif (time % 4000 < 500) {\\n value += Math.random() * 0.05 - 0.025;\\n}\\nreturn value;\"},{\"name\":\"f(x)\",\"type\":\"function\",\"label\":\"longitude\",\"color\":\"#ffc107\",\"settings\":{},\"_hash\":0.6742359401617628,\"funcBody\":\"var value = prevValue || -84.845334;\\nif (time % 4000 < 500) {\\n value += Math.random() * 0.05 - 0.025;\\n}\\nreturn value;\"}]}],\"showTitle\":true,\"backgroundColor\":\"#fff\",\"color\":\"rgba(0, 0, 0, 0.87)\",\"padding\":\"8px\",\"settings\":{\"fitMapBounds\":true,\"latKeyName\":\"latitude\",\"lngKeyName\":\"longitude\",\"showLabel\":true,\"label\":\"${entityName}\",\"tooltipPattern\":\"${entityName}
Latitude: ${latitude:7}
Longitude: ${longitude:7}
Delete\",\"markerImageSize\":34,\"gmDefaultMapType\":\"roadmap\",\"gmApiKey\":null,\"useColorFunction\":false,\"markerImages\":[],\"useMarkerImageFunction\":false,\"colorFunction\":\"\\n\",\"color\":\"#fe7569\",\"showTooltip\":true,\"autocloseTooltip\":true,\"defaultCenterPosition\":\"0,0\",\"showTooltipAction\":\"click\",\"polygonKeyName\":\"coordinates\",\"polygonOpacity\":0.5,\"polygonStrokeOpacity\":1,\"polygonStrokeWeight\":1,\"zoomOnClick\":true,\"defaultZoomLevel\":5,\"provider\":\"google-map\",\"showCoverageOnHover\":true,\"animate\":true,\"maxClusterRadius\":80,\"removeOutsideVisibleBounds\":true,\"mapProvider\":\"HERE.normalDay\",\"draggableMarker\":true,\"editablePolygon\":true,\"mapPageSize\":16384,\"showPolygon\":false,\"polygonTooltipPattern\":\"${entityName}
TimeStamp: ${coordinates|ts:7}
Delete\",\"showPolygonTooltip\":false},\"title\":\"Markers Placement - Google Maps\",\"dropShadow\":true,\"enableFullscreen\":true,\"titleStyle\":{\"fontSize\":\"16px\",\"fontWeight\":400},\"showLegend\":false,\"widgetStyle\":{},\"actions\":{\"tooltipAction\":[{\"name\":\"delete\",\"icon\":\"more_horiz\",\"type\":\"custom\",\"customFunction\":\"var entityDatasource = widgetContext.map.map.datasources.filter(\\n function(entity) {\\n return entity.entityId === entityId.id;\\n });\\n\\nwidgetContext.map.setMarkerLocation(entityDatasource[0], null, null).subscribe(() => widgetContext.updateAliases());\",\"id\":\"8d3c0156-0a14-7a6f-0ddd-0ec16b9ffc91\"},{\"name\":\"delete_polygon\",\"icon\":\"more_horiz\",\"type\":\"custom\",\"customFunction\":\"var entityDatasource = widgetContext.map.map.datasources.filter(\\n function(entity) {\\n return entity.entityId === entityId.id\\n });\\n\\nwidgetContext.map.savePolygonLocation(entityDatasource[0], null).subscribe(() => widgetContext.updateAliases());\",\"id\":\"46bf69cd-8906-234c-a879-e2e4c92f5b67\"}]},\"showTitleIcon\":false,\"titleIcon\":\"more_horiz\",\"iconColor\":\"rgba(0, 0, 0, 0.87)\",\"iconSize\":\"24px\",\"titleTooltip\":\"\"}"
},
"tags": [
"mapping",
diff --git a/application/src/main/data/json/system/widget_types/route_map.json b/application/src/main/data/json/system/widget_types/route_map.json
index 710756a58a..ff6a10e133 100644
--- a/application/src/main/data/json/system/widget_types/route_map.json
+++ b/application/src/main/data/json/system/widget_types/route_map.json
@@ -20,7 +20,7 @@
"latestDataKeySettingsDirective": "",
"hasBasicMode": true,
"basicModeDirective": "tb-map-basic-config",
- "defaultConfig": "{\"datasources\":[],\"timewindow\":{\"selectedTab\":0,\"realtime\":{\"realtimeType\":0,\"timewindowMs\":86400000},\"aggregation\":{\"type\":\"NONE\",\"limit\":5000}},\"showTitle\":true,\"backgroundColor\":\"rgba(0, 0, 0, 0)\",\"color\":\"rgba(0, 0, 0, 0.87)\",\"padding\":\"0px\",\"settings\":{\"mapType\":\"geoMap\",\"layers\":[{\"label\":\"{i18n:widgets.maps.layer.roadmap}\",\"provider\":\"openstreet\",\"layerType\":\"OpenStreetMap.Mapnik\"},{\"label\":\"{i18n:widgets.maps.layer.satellite}\",\"provider\":\"openstreet\",\"layerType\":\"Esri.WorldImagery\"},{\"label\":\"{i18n:widgets.maps.layer.hybrid}\",\"provider\":\"openstreet\",\"layerType\":\"Esri.WorldImagery\",\"referenceLayer\":\"openstreetmap_hybrid\"}],\"trips\":[{\"dsType\":\"function\",\"dsLabel\":\"First route\",\"dsDeviceId\":null,\"dsEntityAliasId\":null,\"dsFilterId\":null,\"additionalDataKeys\":[{\"name\":\"f(x)\",\"type\":\"function\",\"label\":\"Speed\",\"color\":\"#2196f3\",\"settings\":{},\"_hash\":0.17490048149347315,\"funcBody\":\"var value = prevValue;\\nif (!value) {\\n value = 45;\\n}\\nif (time % 500 < 500) {\\n value = value + Math.random() * 40 - 20;\\n if (value < 45) {\\n \\tvalue = 45;\\n } else if (value > 130) {\\n \\tvalue = 130;\\n }\\n}\\nreturn value;\",\"aggregationType\":null,\"units\":null,\"decimals\":null,\"usePostProcessing\":null,\"postFuncBody\":null}],\"label\":{\"show\":true,\"type\":\"pattern\",\"pattern\":\"${entityName}\"},\"tooltip\":{\"show\":true,\"trigger\":\"click\",\"autoclose\":true,\"type\":\"pattern\",\"pattern\":\"${entityName}
Latitude: ${latitude:7}
Longitude: ${longitude:7}
Speed: ${Speed} MPH\",\"offsetX\":0,\"offsetY\":-1,\"patternFunction\":null,\"tagActions\":null},\"click\":{\"type\":\"doNothing\"},\"groups\":null,\"xKey\":{\"name\":\"f(x)\",\"label\":\"latitude\",\"type\":\"function\",\"funcBody\":\"var lats = [37.7696499,\\n37.7699074,\\n37.7699536,\\n37.7697242,\\n37.7695189,\\n37.7696889,\\n37.7697153,\\n37.7701244,\\n37.7700604,\\n37.7705491,\\n37.7715705,\\n37.771752,\\n37.7707533,\\n37.769866];\\n\\nvar i = Math.floor((time/3 % 14000) / 1000);\\n\\nreturn lats[i];\",\"settings\":{},\"color\":\"#2196f3\",\"aggregationType\":null,\"units\":null,\"decimals\":null,\"usePostProcessing\":null,\"postFuncBody\":null},\"yKey\":{\"name\":\"f(x)\",\"label\":\"longitude\",\"type\":\"function\",\"funcBody\":\"var lons = [-122.4261215,\\n-122.4219157,\\n-122.4199623,\\n-122.4179074,\\n-122.4155876,\\n-122.4155521,\\n-122.4163203,\\n-122.4193876,\\n-122.4210496,\\n-122.422284,\\n-122.4232717,\\n-122.4235138,\\n-122.4247605,\\n-122.4258812];\\n\\nvar i = Math.floor((time/3 % 14000) / 1000);\\n\\nreturn lons[i];\",\"settings\":{},\"color\":\"#2196f3\",\"aggregationType\":null,\"units\":null,\"decimals\":null,\"usePostProcessing\":null,\"postFuncBody\":null},\"markerType\":\"image\",\"markerShape\":{\"shape\":\"tripMarkerShape1\",\"size\":34,\"color\":{\"type\":\"constant\",\"color\":\"#307FE5\"}},\"markerIcon\":{\"icon\":\"arrow_forward\",\"size\":48,\"color\":{\"type\":\"constant\",\"color\":\"#307FE5\"}},\"markerImage\":{\"type\":\"function\",\"image\":\"/assets/markers/tripShape1.svg\",\"imageSize\":34,\"imageFunction\":\"var speed = data.Speed;\\nvar res = {\\n url: images[0],\\n size: 55\\n};\\nif (typeof speed !== undefined) {\\n var percent = (speed - 45)/85;\\n var index = Math.min(2, Math.floor(3 * percent));\\n res.url = images[index];\\n}\\nreturn res;\",\"images\":[\"tb-image;/api/images/system/map_marker_image_0.png\",\"tb-image;/api/images/system/map_marker_image_1.png\",\"tb-image;/api/images/system/map_marker_image_2.png\"]},\"markerOffsetX\":0.5,\"markerOffsetY\":1,\"rotateMarker\":true,\"offsetAngle\":0,\"showPath\":true,\"pathStrokeWeight\":4,\"pathStrokeColor\":{\"type\":\"function\",\"color\":\"#307FE5\",\"colorFunction\":\"var speed = data.Speed;\\nif (typeof speed !== undefined) {\\n var percent = (speed - 45)/85;\\n if (percent < 0.5) {\\n percent *=2*100; \\n return tinycolor.mix('green', 'yellow', percent).setAlpha(0.65).toRgbString();\\n } else {\\n percent = (percent - 0.5)*2*100;\\n return tinycolor.mix('yellow', 'red', percent).setAlpha(0.65).toRgbString();\\n }\\n}\"},\"usePathDecorator\":false,\"pathDecoratorSymbol\":\"arrowHead\",\"pathDecoratorSymbolSize\":10,\"pathDecoratorSymbolColor\":\"#307FE5\",\"pathDecoratorOffset\":20,\"pathEndDecoratorOffset\":20,\"pathDecoratorRepeat\":20,\"showPoints\":false,\"pointSize\":10,\"pointColor\":{\"type\":\"constant\",\"color\":\"#307FE5\"},\"pointTooltip\":{\"show\":true,\"trigger\":\"click\",\"autoclose\":true,\"type\":\"pattern\",\"pattern\":\"${entityName}
Latitude: ${latitude:7}
Longitude: ${longitude:7}
End Time: ${maxTime}
Start Time: ${minTime}\",\"offsetX\":0,\"offsetY\":-1}}],\"markers\":[],\"polygons\":[],\"circles\":[],\"polylines\":[],\"additionalDataSources\":[],\"controlsPosition\":\"topleft\",\"zoomActions\":[\"scroll\",\"doubleClick\",\"controlButtons\"],\"scales\":[],\"dragModeButton\":false,\"fitMapBounds\":true,\"useDefaultCenterPosition\":false,\"defaultCenterPosition\":\"0,0\",\"defaultZoomLevel\":null,\"minZoomLevel\":16,\"mapPageSize\":16384,\"mapActionButtons\":[],\"tripTimeline\":{\"showTimelineControl\":false,\"timeStep\":1000,\"speedOptions\":[1,5,10,15,25],\"showTimestamp\":true,\"timestampFormat\":{\"format\":\"yyyy-MM-dd HH:mm:ss\",\"lastUpdateAgo\":false,\"custom\":false,\"auto\":false},\"snapToRealLocation\":false,\"locationSnapFilter\":\"return true;\"},\"background\":{\"type\":\"color\",\"color\":\"#fff\",\"overlay\":{\"enabled\":false,\"color\":\"rgba(255,255,255,0.72)\",\"blur\":3}},\"padding\":\"8px\"},\"title\":\"Route Map\",\"dropShadow\":true,\"enableFullscreen\":true,\"titleStyle\":null,\"mobileHeight\":null,\"configMode\":\"basic\",\"actions\":{},\"showTitleIcon\":false,\"titleIcon\":\"assistant_navigation\",\"iconColor\":\"#1F6BDD\",\"useDashboardTimewindow\":false,\"displayTimewindow\":true,\"titleFont\":{\"size\":null,\"sizeUnit\":\"px\",\"family\":null,\"weight\":null,\"style\":null,\"lineHeight\":null},\"titleColor\":null,\"titleTooltip\":\"\",\"widgetStyle\":{},\"widgetCss\":\"\",\"pageSize\":1024,\"units\":\"\",\"decimals\":null,\"noDataDisplayMessage\":\"\",\"timewindowStyle\":{\"showIcon\":false,\"iconSize\":\"24px\",\"icon\":null,\"iconPosition\":\"left\",\"font\":{\"size\":12,\"sizeUnit\":\"px\",\"family\":\"Roboto\",\"weight\":\"400\",\"style\":\"normal\",\"lineHeight\":\"16px\"},\"color\":\"rgba(0, 0, 0, 0.38)\",\"displayTypePrefix\":true},\"margin\":\"0px\",\"borderRadius\":\"0px\",\"iconSize\":\"24px\",\"enableDataExport\":false}"
+ "defaultConfig": "{\"datasources\":[],\"timewindow\":{\"selectedTab\":0,\"realtime\":{\"realtimeType\":0,\"timewindowMs\":86400000},\"aggregation\":{\"type\":\"NONE\",\"limit\":5000}},\"showTitle\":true,\"backgroundColor\":\"rgba(0, 0, 0, 0)\",\"color\":\"rgba(0, 0, 0, 0.87)\",\"padding\":\"0px\",\"settings\":{\"mapType\":\"geoMap\",\"layers\":[{\"label\":\"{i18n:widgets.maps.layer.roadmap}\",\"provider\":\"openstreet\",\"layerType\":\"OpenStreetMap.Mapnik\"}],\"trips\":[{\"dsType\":\"function\",\"dsLabel\":\"First route\",\"dsDeviceId\":null,\"dsEntityAliasId\":null,\"dsFilterId\":null,\"additionalDataKeys\":[{\"name\":\"f(x)\",\"type\":\"function\",\"label\":\"Speed\",\"color\":\"#2196f3\",\"settings\":{},\"_hash\":0.17490048149347315,\"funcBody\":\"var value = prevValue;\\nif (!value) {\\n value = 45;\\n}\\nif (time % 500 < 500) {\\n value = value + Math.random() * 40 - 20;\\n if (value < 45) {\\n \\tvalue = 45;\\n } else if (value > 130) {\\n \\tvalue = 130;\\n }\\n}\\nreturn value;\",\"aggregationType\":null,\"units\":null,\"decimals\":null,\"usePostProcessing\":null,\"postFuncBody\":null}],\"label\":{\"show\":true,\"type\":\"pattern\",\"pattern\":\"${entityName}\"},\"tooltip\":{\"show\":true,\"trigger\":\"click\",\"autoclose\":true,\"type\":\"pattern\",\"pattern\":\"${entityName}
Latitude: ${latitude:7}
Longitude: ${longitude:7}
Speed: ${Speed} MPH\",\"offsetX\":0,\"offsetY\":-1,\"patternFunction\":null,\"tagActions\":null},\"click\":{\"type\":\"doNothing\"},\"groups\":null,\"xKey\":{\"name\":\"f(x)\",\"label\":\"latitude\",\"type\":\"function\",\"funcBody\":\"var lats = [37.7696499,\\n37.7699074,\\n37.7699536,\\n37.7697242,\\n37.7695189,\\n37.7696889,\\n37.7697153,\\n37.7701244,\\n37.7700604,\\n37.7705491,\\n37.7715705,\\n37.771752,\\n37.7707533,\\n37.769866];\\n\\nvar i = Math.floor((time/3 % 14000) / 1000);\\n\\nreturn lats[i];\",\"settings\":{},\"color\":\"#2196f3\",\"aggregationType\":null,\"units\":null,\"decimals\":null,\"usePostProcessing\":null,\"postFuncBody\":null},\"yKey\":{\"name\":\"f(x)\",\"label\":\"longitude\",\"type\":\"function\",\"funcBody\":\"var lons = [-122.4261215,\\n-122.4219157,\\n-122.4199623,\\n-122.4179074,\\n-122.4155876,\\n-122.4155521,\\n-122.4163203,\\n-122.4193876,\\n-122.4210496,\\n-122.422284,\\n-122.4232717,\\n-122.4235138,\\n-122.4247605,\\n-122.4258812];\\n\\nvar i = Math.floor((time/3 % 14000) / 1000);\\n\\nreturn lons[i];\",\"settings\":{},\"color\":\"#2196f3\",\"aggregationType\":null,\"units\":null,\"decimals\":null,\"usePostProcessing\":null,\"postFuncBody\":null},\"markerType\":\"image\",\"markerShape\":{\"shape\":\"tripMarkerShape1\",\"size\":34,\"color\":{\"type\":\"constant\",\"color\":\"#307FE5\"}},\"markerIcon\":{\"icon\":\"arrow_forward\",\"size\":48,\"color\":{\"type\":\"constant\",\"color\":\"#307FE5\"}},\"markerImage\":{\"type\":\"function\",\"image\":\"/assets/markers/tripShape1.svg\",\"imageSize\":34,\"imageFunction\":\"var speed = data.Speed;\\nvar res = {\\n url: images[0],\\n size: 55\\n};\\nif (typeof speed !== undefined) {\\n var percent = (speed - 45)/85;\\n var index = Math.min(2, Math.floor(3 * percent));\\n res.url = images[index];\\n}\\nreturn res;\",\"images\":[\"tb-image;/api/images/system/map_marker_image_0.png\",\"tb-image;/api/images/system/map_marker_image_1.png\",\"tb-image;/api/images/system/map_marker_image_2.png\"]},\"markerOffsetX\":0.5,\"markerOffsetY\":1,\"rotateMarker\":true,\"offsetAngle\":0,\"showPath\":true,\"pathStrokeWeight\":4,\"pathStrokeColor\":{\"type\":\"function\",\"color\":\"#307FE5\",\"colorFunction\":\"var speed = data.Speed;\\nif (typeof speed !== undefined) {\\n var percent = (speed - 45)/85;\\n if (percent < 0.5) {\\n percent *=2*100; \\n return tinycolor.mix('green', 'yellow', percent).setAlpha(0.65).toRgbString();\\n } else {\\n percent = (percent - 0.5)*2*100;\\n return tinycolor.mix('yellow', 'red', percent).setAlpha(0.65).toRgbString();\\n }\\n}\"},\"usePathDecorator\":false,\"pathDecoratorSymbol\":\"arrowHead\",\"pathDecoratorSymbolSize\":10,\"pathDecoratorSymbolColor\":\"#307FE5\",\"pathDecoratorOffset\":20,\"pathEndDecoratorOffset\":20,\"pathDecoratorRepeat\":20,\"showPoints\":false,\"pointSize\":10,\"pointColor\":{\"type\":\"constant\",\"color\":\"#307FE5\"},\"pointTooltip\":{\"show\":true,\"trigger\":\"click\",\"autoclose\":true,\"type\":\"pattern\",\"pattern\":\"${entityName}
Latitude: ${latitude:7}
Longitude: ${longitude:7}
End Time: ${maxTime}
Start Time: ${minTime}\",\"offsetX\":0,\"offsetY\":-1}}],\"markers\":[],\"polygons\":[],\"circles\":[],\"polylines\":[],\"additionalDataSources\":[],\"controlsPosition\":\"topleft\",\"zoomActions\":[\"scroll\",\"doubleClick\",\"controlButtons\"],\"scales\":[],\"dragModeButton\":false,\"fitMapBounds\":true,\"useDefaultCenterPosition\":false,\"defaultCenterPosition\":\"0,0\",\"defaultZoomLevel\":null,\"minZoomLevel\":16,\"mapPageSize\":16384,\"mapActionButtons\":[],\"tripTimeline\":{\"showTimelineControl\":false,\"timeStep\":1000,\"speedOptions\":[1,5,10,15,25],\"showTimestamp\":true,\"timestampFormat\":{\"format\":\"yyyy-MM-dd HH:mm:ss\",\"lastUpdateAgo\":false,\"custom\":false,\"auto\":false},\"snapToRealLocation\":false,\"locationSnapFilter\":\"return true;\"},\"background\":{\"type\":\"color\",\"color\":\"#fff\",\"overlay\":{\"enabled\":false,\"color\":\"rgba(255,255,255,0.72)\",\"blur\":3}},\"padding\":\"8px\"},\"title\":\"Route Map\",\"dropShadow\":true,\"enableFullscreen\":true,\"titleStyle\":null,\"mobileHeight\":null,\"configMode\":\"basic\",\"actions\":{},\"showTitleIcon\":false,\"titleIcon\":\"assistant_navigation\",\"iconColor\":\"#1F6BDD\",\"useDashboardTimewindow\":false,\"displayTimewindow\":true,\"titleFont\":{\"size\":null,\"sizeUnit\":\"px\",\"family\":null,\"weight\":null,\"style\":null,\"lineHeight\":null},\"titleColor\":null,\"titleTooltip\":\"\",\"widgetStyle\":{},\"widgetCss\":\"\",\"pageSize\":1024,\"units\":\"\",\"decimals\":null,\"noDataDisplayMessage\":\"\",\"timewindowStyle\":{\"showIcon\":false,\"iconSize\":\"24px\",\"icon\":null,\"iconPosition\":\"left\",\"font\":{\"size\":12,\"sizeUnit\":\"px\",\"family\":\"Roboto\",\"weight\":\"400\",\"style\":\"normal\",\"lineHeight\":\"16px\"},\"color\":\"rgba(0, 0, 0, 0.38)\",\"displayTypePrefix\":true},\"margin\":\"0px\",\"borderRadius\":\"0px\",\"iconSize\":\"24px\",\"enableDataExport\":false}"
},
"resources": [
{
diff --git a/application/src/main/data/json/system/widget_types/route_map___google.json b/application/src/main/data/json/system/widget_types/route_map___google.json
index 5d3bd865a0..620834b9c7 100644
--- a/application/src/main/data/json/system/widget_types/route_map___google.json
+++ b/application/src/main/data/json/system/widget_types/route_map___google.json
@@ -13,7 +13,7 @@
"templateCss": ".error {\n color: red;\n}\n.tb-labels {\n color: #222;\n font: 12px/1.5 \"Helvetica Neue\", Arial, Helvetica, sans-serif;\n text-align: center;\n width: 200px;\n white-space: nowrap;\n}",
"controllerScript": "self.onInit = function() {\n self.ctx.map = new TbMapWidgetV2('google-map', true, self.ctx);\n}\n\nself.onDataUpdated = function() {\n self.ctx.map.update();\n}\n\nself.onLatestDataUpdated = function() {\n self.ctx.map.latestDataUpdate();\n}\n\nself.onResize = function() {\n self.ctx.map.resize();\n}\n\nself.actionSources = function() {\n return TbMapWidgetV2.actionSources();\n}\n\nself.onDestroy = function() {\n self.ctx.map.destroy();\n}\n\nself.typeParameters = function() {\n return {\n hasDataPageLink: true,\n ignoreDataUpdateOnIntervalTick: true,\n hasAdditionalLatestDataKeys: true\n };\n}",
"settingsDirective": "tb-route-map-widget-settings",
- "defaultConfig": "{\"datasources\":[{\"type\":\"function\",\"name\":\"First route\",\"dataKeys\":[{\"name\":\"f(x)\",\"type\":\"function\",\"label\":\"latitude\",\"color\":\"#2196f3\",\"settings\":{},\"_hash\":0.5851719234007373,\"funcBody\":\"var lats = [37.7696499,\\n37.7699074,\\n37.7699536,\\n37.7697242,\\n37.7695189,\\n37.7696889,\\n37.7697153,\\n37.7701244,\\n37.7700604,\\n37.7705491,\\n37.7715705,\\n37.771752,\\n37.7707533,\\n37.769866];\\n\\nvar i = Math.floor((time/3 % 14000) / 1000);\\n\\nreturn lats[i];\"},{\"name\":\"f(x)\",\"type\":\"function\",\"label\":\"longitude\",\"color\":\"#4caf50\",\"settings\":{},\"_hash\":0.9015113051937396,\"funcBody\":\"var lons = [-122.4261215,\\n-122.4219157,\\n-122.4199623,\\n-122.4179074,\\n-122.4155876,\\n-122.4155521,\\n-122.4163203,\\n-122.4193876,\\n-122.4210496,\\n-122.422284,\\n-122.4232717,\\n-122.4235138,\\n-122.4247605,\\n-122.4258812];\\n\\nvar i = Math.floor((time/3 % 14000) / 1000);\\n\\nreturn lons[i];\"},{\"name\":\"f(x)\",\"type\":\"function\",\"label\":\"Speed\",\"color\":\"#f44336\",\"settings\":{},\"_hash\":0.7253460349565717,\"funcBody\":\"var value = prevValue;\\nif (time % 500 < 100) {\\n value = value + Math.random() * 40 - 20;\\n if (value < 45) {\\n \\tvalue = 45;\\n } else if (value > 130) {\\n \\tvalue = 130;\\n }\\n}\\nreturn value;\"}]}],\"showTitle\":true,\"backgroundColor\":\"#fff\",\"color\":\"rgba(0, 0, 0, 0.87)\",\"padding\":\"8px\",\"settings\":{\"provider\":\"google-map\",\"gmApiKey\":\"AIzaSyDoEx2kaGz3PxwbI9T7ccTSg5xjdw8Nw8Q\",\"gmDefaultMapType\":\"roadmap\",\"latKeyName\":\"latitude\",\"lngKeyName\":\"longitude\",\"xPosKeyName\":\"xPos\",\"yPosKeyName\":\"yPos\",\"defaultCenterPosition\":\"0,0\",\"disableScrollZooming\":false,\"disableDoubleClickZooming\":false,\"disableZoomControl\":false,\"fitMapBounds\":true,\"useDefaultCenterPosition\":false,\"mapPageSize\":16384,\"markerOffsetX\":0.5,\"markerOffsetY\":1,\"posFunction\":\"return {x: origXPos, y: origYPos};\",\"draggableMarker\":false,\"showLabel\":true,\"useLabelFunction\":false,\"label\":\"${entityName}\",\"showTooltip\":true,\"showTooltipAction\":\"click\",\"autocloseTooltip\":true,\"useTooltipFunction\":false,\"tooltipPattern\":\"${entityName}
Latitude: ${latitude:7}
Longitude: ${longitude:7}
Speed: ${Speed} MPH
See advanced settings for details\",\"tooltipOffsetX\":0,\"tooltipOffsetY\":-1,\"color\":\"#1976d2\",\"useColorFunction\":true,\"colorFunction\":\"var speed = dsData[dsIndex]['Speed'];\\nif (typeof speed !== undefined) {\\n var percent = (speed - 45)/85;\\n if (percent < 0.5) {\\n percent *=2*100; \\n return tinycolor.mix('green', 'yellow', percent).toHexString();\\n } else {\\n percent = (percent - 0.5)*2*100;\\n return tinycolor.mix('yellow', 'red', percent).toHexString();\\n }\\n}\",\"useMarkerImageFunction\":true,\"markerImageSize\":34,\"markerImageFunction\":\"var speed = dsData[dsIndex]['Speed'];\\nvar res = {\\n url: images[0],\\n size: 55\\n};\\nif (typeof speed !== undefined) {\\n var percent = (speed - 45)/85;\\n var index = Math.min(2, Math.floor(3 * percent));\\n res.url = images[index];\\n}\\nreturn res;\",\"markerImages\":[\"tb-image;/api/images/system/fleet_tracking_dashboard_widget_buses_location_marker_image_0.png\",\"tb-image;/api/images/system/fleet_tracking_dashboard_widget_buses_location_marker_image_1.png\",\"tb-image;/api/images/system/fleet_tracking_dashboard_widget_buses_location_marker_image_2.png\"],\"showPolygon\":false,\"polygonKeyName\":\"perimeter\",\"editablePolygon\":false,\"showPolygonLabel\":false,\"usePolygonLabelFunction\":false,\"polygonLabel\":\"${entityName}\",\"showPolygonTooltip\":false,\"showPolygonTooltipAction\":\"click\",\"autoClosePolygonTooltip\":true,\"usePolygonTooltipFunction\":false,\"polygonTooltipPattern\":\"${entityName}
TimeStamp: ${ts:7}\",\"polygonColor\":\"#3388ff\",\"polygonOpacity\":0.2,\"usePolygonColorFunction\":false,\"polygonStrokeColor\":\"#3388ff\",\"polygonStrokeOpacity\":1,\"polygonStrokeWeight\":3,\"usePolygonStrokeColorFunction\":false,\"showCircle\":false,\"circleKeyName\":\"perimeter\",\"editableCircle\":false,\"showCircleLabel\":false,\"useCircleLabelFunction\":false,\"circleLabel\":\"${entityName}\",\"showCircleTooltip\":false,\"showCircleTooltipAction\":\"click\",\"autoCloseCircleTooltip\":true,\"useCircleTooltipFunction\":false,\"circleTooltipPattern\":\"${entityName}
TimeStamp: ${ts:7}\",\"circleFillColor\":\"#3388ff\",\"circleFillColorOpacity\":0.2,\"useCircleFillColorFunction\":false,\"circleStrokeColor\":\"#3388ff\",\"circleStrokeOpacity\":1,\"circleStrokeWeight\":3,\"useCircleStrokeColorFunction\":false,\"strokeWeight\":4,\"strokeOpacity\":0.65},\"title\":\"Route Map - Google\",\"dropShadow\":true,\"enableFullscreen\":true,\"titleStyle\":{\"fontSize\":\"16px\",\"fontWeight\":400},\"useDashboardTimewindow\":true,\"showLegend\":false,\"widgetStyle\":{},\"actions\":{}}"
+ "defaultConfig": "{\"datasources\":[{\"type\":\"function\",\"name\":\"First route\",\"dataKeys\":[{\"name\":\"f(x)\",\"type\":\"function\",\"label\":\"latitude\",\"color\":\"#2196f3\",\"settings\":{},\"_hash\":0.5851719234007373,\"funcBody\":\"var lats = [37.7696499,\\n37.7699074,\\n37.7699536,\\n37.7697242,\\n37.7695189,\\n37.7696889,\\n37.7697153,\\n37.7701244,\\n37.7700604,\\n37.7705491,\\n37.7715705,\\n37.771752,\\n37.7707533,\\n37.769866];\\n\\nvar i = Math.floor((time/3 % 14000) / 1000);\\n\\nreturn lats[i];\"},{\"name\":\"f(x)\",\"type\":\"function\",\"label\":\"longitude\",\"color\":\"#4caf50\",\"settings\":{},\"_hash\":0.9015113051937396,\"funcBody\":\"var lons = [-122.4261215,\\n-122.4219157,\\n-122.4199623,\\n-122.4179074,\\n-122.4155876,\\n-122.4155521,\\n-122.4163203,\\n-122.4193876,\\n-122.4210496,\\n-122.422284,\\n-122.4232717,\\n-122.4235138,\\n-122.4247605,\\n-122.4258812];\\n\\nvar i = Math.floor((time/3 % 14000) / 1000);\\n\\nreturn lons[i];\"},{\"name\":\"f(x)\",\"type\":\"function\",\"label\":\"Speed\",\"color\":\"#f44336\",\"settings\":{},\"_hash\":0.7253460349565717,\"funcBody\":\"var value = prevValue;\\nif (time % 500 < 100) {\\n value = value + Math.random() * 40 - 20;\\n if (value < 45) {\\n \\tvalue = 45;\\n } else if (value > 130) {\\n \\tvalue = 130;\\n }\\n}\\nreturn value;\"}]}],\"showTitle\":true,\"backgroundColor\":\"#fff\",\"color\":\"rgba(0, 0, 0, 0.87)\",\"padding\":\"8px\",\"settings\":{\"provider\":\"google-map\",\"gmApiKey\":null,\"gmDefaultMapType\":\"roadmap\",\"latKeyName\":\"latitude\",\"lngKeyName\":\"longitude\",\"xPosKeyName\":\"xPos\",\"yPosKeyName\":\"yPos\",\"defaultCenterPosition\":\"0,0\",\"disableScrollZooming\":false,\"disableDoubleClickZooming\":false,\"disableZoomControl\":false,\"fitMapBounds\":true,\"useDefaultCenterPosition\":false,\"mapPageSize\":16384,\"markerOffsetX\":0.5,\"markerOffsetY\":1,\"posFunction\":\"return {x: origXPos, y: origYPos};\",\"draggableMarker\":false,\"showLabel\":true,\"useLabelFunction\":false,\"label\":\"${entityName}\",\"showTooltip\":true,\"showTooltipAction\":\"click\",\"autocloseTooltip\":true,\"useTooltipFunction\":false,\"tooltipPattern\":\"${entityName}
Latitude: ${latitude:7}
Longitude: ${longitude:7}
Speed: ${Speed} MPH
See advanced settings for details\",\"tooltipOffsetX\":0,\"tooltipOffsetY\":-1,\"color\":\"#1976d2\",\"useColorFunction\":true,\"colorFunction\":\"var speed = dsData[dsIndex]['Speed'];\\nif (typeof speed !== undefined) {\\n var percent = (speed - 45)/85;\\n if (percent < 0.5) {\\n percent *=2*100; \\n return tinycolor.mix('green', 'yellow', percent).toHexString();\\n } else {\\n percent = (percent - 0.5)*2*100;\\n return tinycolor.mix('yellow', 'red', percent).toHexString();\\n }\\n}\",\"useMarkerImageFunction\":true,\"markerImageSize\":34,\"markerImageFunction\":\"var speed = dsData[dsIndex]['Speed'];\\nvar res = {\\n url: images[0],\\n size: 55\\n};\\nif (typeof speed !== undefined) {\\n var percent = (speed - 45)/85;\\n var index = Math.min(2, Math.floor(3 * percent));\\n res.url = images[index];\\n}\\nreturn res;\",\"markerImages\":[\"tb-image;/api/images/system/fleet_tracking_dashboard_widget_buses_location_marker_image_0.png\",\"tb-image;/api/images/system/fleet_tracking_dashboard_widget_buses_location_marker_image_1.png\",\"tb-image;/api/images/system/fleet_tracking_dashboard_widget_buses_location_marker_image_2.png\"],\"showPolygon\":false,\"polygonKeyName\":\"perimeter\",\"editablePolygon\":false,\"showPolygonLabel\":false,\"usePolygonLabelFunction\":false,\"polygonLabel\":\"${entityName}\",\"showPolygonTooltip\":false,\"showPolygonTooltipAction\":\"click\",\"autoClosePolygonTooltip\":true,\"usePolygonTooltipFunction\":false,\"polygonTooltipPattern\":\"${entityName}
TimeStamp: ${ts:7}\",\"polygonColor\":\"#3388ff\",\"polygonOpacity\":0.2,\"usePolygonColorFunction\":false,\"polygonStrokeColor\":\"#3388ff\",\"polygonStrokeOpacity\":1,\"polygonStrokeWeight\":3,\"usePolygonStrokeColorFunction\":false,\"showCircle\":false,\"circleKeyName\":\"perimeter\",\"editableCircle\":false,\"showCircleLabel\":false,\"useCircleLabelFunction\":false,\"circleLabel\":\"${entityName}\",\"showCircleTooltip\":false,\"showCircleTooltipAction\":\"click\",\"autoCloseCircleTooltip\":true,\"useCircleTooltipFunction\":false,\"circleTooltipPattern\":\"${entityName}
TimeStamp: ${ts:7}\",\"circleFillColor\":\"#3388ff\",\"circleFillColorOpacity\":0.2,\"useCircleFillColorFunction\":false,\"circleStrokeColor\":\"#3388ff\",\"circleStrokeOpacity\":1,\"circleStrokeWeight\":3,\"useCircleStrokeColorFunction\":false,\"strokeWeight\":4,\"strokeOpacity\":0.65},\"title\":\"Route Map - Google\",\"dropShadow\":true,\"enableFullscreen\":true,\"titleStyle\":{\"fontSize\":\"16px\",\"fontWeight\":400},\"useDashboardTimewindow\":true,\"showLegend\":false,\"widgetStyle\":{},\"actions\":{}}"
},
"tags": [
"mapping",
diff --git a/application/src/main/data/json/system/widget_types/trip_map.json b/application/src/main/data/json/system/widget_types/trip_map.json
index 9293209f8a..031f1bac3e 100644
--- a/application/src/main/data/json/system/widget_types/trip_map.json
+++ b/application/src/main/data/json/system/widget_types/trip_map.json
@@ -20,7 +20,7 @@
"latestDataKeySettingsDirective": "",
"hasBasicMode": true,
"basicModeDirective": "tb-map-basic-config",
- "defaultConfig": "{\"datasources\":[],\"timewindow\":{\"selectedTab\":1,\"history\":{\"historyType\":0,\"timewindowMs\":86400000},\"aggregation\":{\"type\":\"NONE\",\"limit\":5000}},\"showTitle\":true,\"backgroundColor\":\"rgba(0, 0, 0, 0)\",\"color\":\"rgba(0, 0, 0, 0.87)\",\"padding\":\"0px\",\"settings\":{\"mapType\":\"geoMap\",\"layers\":[{\"label\":\"{i18n:widgets.maps.layer.roadmap}\",\"provider\":\"openstreet\",\"layerType\":\"OpenStreetMap.Mapnik\"},{\"label\":\"{i18n:widgets.maps.layer.satellite}\",\"provider\":\"openstreet\",\"layerType\":\"Esri.WorldImagery\"},{\"label\":\"{i18n:widgets.maps.layer.hybrid}\",\"provider\":\"openstreet\",\"layerType\":\"Esri.WorldImagery\",\"referenceLayer\":\"openstreetmap_hybrid\"}],\"trips\":[{\"dsType\":\"function\",\"dsLabel\":\"First point\",\"xKey\":{\"name\":\"f(x)\",\"label\":\"latitude\",\"type\":\"function\",\"funcBody\":\"var gpsData = [\\n37.771210000, -122.510960000,\\n 37.771990000, -122.497070000,\\n 37.772730000, -122.480740000,\\n 37.773360000, -122.466870000,\\n 37.774270000, -122.458520000,\\n 37.771980000, -122.454110000,\\n 37.768250000, -122.453380000,\\n 37.765920000, -122.456810000,\\n 37.765930000, -122.467680000,\\n 37.765500000, -122.477180000,\\n 37.765300000, -122.481660000,\\n 37.764780000, -122.493350000,\\n 37.764120000, -122.508360000,\\n 37.766410000, -122.510260000,\\n 37.770010000, -122.510830000,\\n 37.770980000, -122.510930000\\n];\\n let value = gpsData.indexOf(prevValue); \\nreturn gpsData[(value == -1 ? 0 : (value + 2) % gpsData.length)];\",\"settings\":{},\"color\":\"#2196f3\",\"aggregationType\":null,\"units\":null,\"decimals\":null,\"usePostProcessing\":null,\"postFuncBody\":null},\"yKey\":{\"name\":\"f(x)\",\"label\":\"longitude\",\"type\":\"function\",\"funcBody\":\"var gpsData = [\\n37.771210000, -122.510960000,\\n 37.771990000, -122.497070000,\\n 37.772730000, -122.480740000,\\n 37.773360000, -122.466870000,\\n 37.774270000, -122.458520000,\\n 37.771980000, -122.454110000,\\n 37.768250000, -122.453380000,\\n 37.765920000, -122.456810000,\\n 37.765930000, -122.467680000,\\n 37.765500000, -122.477180000,\\n 37.765300000, -122.481660000,\\n 37.764780000, -122.493350000,\\n 37.764120000, -122.508360000,\\n 37.766410000, -122.510260000,\\n 37.770010000, -122.510830000,\\n 37.770980000, -122.510930000\\n];\\n let value = gpsData.indexOf(prevValue); \\nreturn gpsData[(value == -1 ? 1 : (value + 2) % gpsData.length)];\",\"settings\":{},\"color\":\"#2196f3\",\"aggregationType\":null,\"units\":null,\"decimals\":null,\"usePostProcessing\":null,\"postFuncBody\":null},\"markerType\":\"shape\",\"markerShape\":{\"shape\":\"tripMarkerShape1\",\"size\":34,\"color\":{\"type\":\"constant\",\"color\":\"#307FE5\"}},\"markerIcon\":{\"icon\":\"arrow_forward\",\"size\":48,\"color\":{\"type\":\"constant\",\"color\":\"#307FE5\"}},\"markerImage\":{\"type\":\"image\",\"image\":\"/assets/markers/tripShape1.svg\",\"imageSize\":34},\"markerOffsetX\":0.5,\"markerOffsetY\":0.5,\"positionFunction\":\"return {x: origXPos, y: origYPos};\",\"markerClustering\":{\"enable\":false,\"zoomOnClick\":true,\"maxZoom\":null,\"maxClusterRadius\":80,\"zoomAnimation\":true,\"showCoverageOnHover\":true,\"spiderfyOnMaxZoom\":false,\"chunkedLoad\":false,\"lazyLoad\":true,\"useClusterMarkerColorFunction\":false,\"clusterMarkerColorFunction\":null},\"label\":{\"show\":true,\"type\":\"pattern\",\"pattern\":\"${entityName}\"},\"tooltip\":{\"show\":true,\"trigger\":\"click\",\"autoclose\":true,\"type\":\"pattern\",\"pattern\":\"${entityName}
Latitude: ${latitude:7}
Longitude: ${longitude:7}
End Time: ${maxTime}
Start Time: ${minTime}\",\"offsetX\":0,\"offsetY\":-0.5},\"click\":{\"type\":\"doNothing\"},\"edit\":{\"enabledActions\":[],\"snappable\":false},\"rotateMarker\":true,\"offsetAngle\":0,\"showPath\":true,\"pathStrokeWeight\":2,\"pathStrokeColor\":{\"type\":\"constant\",\"color\":\"#307FE5\"},\"usePathDecorator\":false,\"pathDecoratorSymbol\":\"arrowHead\",\"pathDecoratorSymbolSize\":10,\"pathDecoratorSymbolColor\":\"#307FE5\",\"pathDecoratorOffset\":20,\"pathEndDecoratorOffset\":20,\"pathDecoratorRepeat\":20,\"showPoints\":false,\"pointSize\":10,\"pointColor\":{\"type\":\"constant\",\"color\":\"#307FE5\"},\"pointTooltip\":{\"show\":true,\"trigger\":\"click\",\"autoclose\":true,\"type\":\"pattern\",\"pattern\":\"${entityName}
Latitude: ${latitude:7}
Longitude: ${longitude:7}
End Time: ${maxTime}
Start Time: ${minTime}\",\"offsetX\":0,\"offsetY\":-1}}],\"markers\":[],\"polygons\":[],\"circles\":[],\"polylines\":[],\"additionalDataSources\":[],\"controlsPosition\":\"topleft\",\"zoomActions\":[\"scroll\",\"doubleClick\",\"controlButtons\"],\"scales\":[],\"dragModeButton\":false,\"fitMapBounds\":true,\"useDefaultCenterPosition\":false,\"defaultCenterPosition\":\"0,0\",\"defaultZoomLevel\":null,\"minZoomLevel\":16,\"mapPageSize\":16384,\"mapActionButtons\":[],\"tripTimeline\":{\"showTimelineControl\":true,\"timeStep\":1000,\"speedOptions\":[1,5,10,15,25],\"showTimestamp\":true,\"timestampFormat\":{\"format\":\"yyyy-MM-dd HH:mm:ss\",\"lastUpdateAgo\":false,\"custom\":false,\"auto\":false},\"snapToRealLocation\":false,\"locationSnapFilter\":\"return true;\"},\"background\":{\"type\":\"color\",\"color\":\"#fff\",\"overlay\":{\"enabled\":false,\"color\":\"rgba(255,255,255,0.72)\",\"blur\":3}},\"padding\":\"8px\"},\"title\":\"Trip Map\",\"dropShadow\":true,\"enableFullscreen\":true,\"titleStyle\":null,\"mobileHeight\":null,\"configMode\":\"basic\",\"actions\":{},\"showTitleIcon\":false,\"titleIcon\":\"assistant_navigation\",\"iconColor\":\"#1F6BDD\",\"useDashboardTimewindow\":false,\"displayTimewindow\":true,\"titleFont\":{\"size\":null,\"sizeUnit\":\"px\",\"family\":null,\"weight\":null,\"style\":null,\"lineHeight\":null},\"titleColor\":null,\"titleTooltip\":\"\",\"widgetStyle\":{},\"widgetCss\":\"\",\"pageSize\":1024,\"units\":\"\",\"decimals\":null,\"noDataDisplayMessage\":\"\",\"timewindowStyle\":{\"showIcon\":false,\"iconSize\":\"24px\",\"icon\":null,\"iconPosition\":\"left\",\"font\":{\"size\":12,\"sizeUnit\":\"px\",\"family\":\"Roboto\",\"weight\":\"400\",\"style\":\"normal\",\"lineHeight\":\"16px\"},\"color\":\"rgba(0, 0, 0, 0.38)\",\"displayTypePrefix\":true},\"margin\":\"0px\",\"borderRadius\":\"0px\",\"iconSize\":\"24px\",\"enableDataExport\":false}"
+ "defaultConfig": "{\"datasources\":[],\"timewindow\":{\"selectedTab\":1,\"history\":{\"historyType\":0,\"timewindowMs\":86400000},\"aggregation\":{\"type\":\"NONE\",\"limit\":5000}},\"showTitle\":true,\"backgroundColor\":\"rgba(0, 0, 0, 0)\",\"color\":\"rgba(0, 0, 0, 0.87)\",\"padding\":\"0px\",\"settings\":{\"mapType\":\"geoMap\",\"layers\":[{\"label\":\"{i18n:widgets.maps.layer.roadmap}\",\"provider\":\"openstreet\",\"layerType\":\"OpenStreetMap.Mapnik\"}],\"trips\":[{\"dsType\":\"function\",\"dsLabel\":\"First point\",\"xKey\":{\"name\":\"f(x)\",\"label\":\"latitude\",\"type\":\"function\",\"funcBody\":\"var gpsData = [\\n37.771210000, -122.510960000,\\n 37.771990000, -122.497070000,\\n 37.772730000, -122.480740000,\\n 37.773360000, -122.466870000,\\n 37.774270000, -122.458520000,\\n 37.771980000, -122.454110000,\\n 37.768250000, -122.453380000,\\n 37.765920000, -122.456810000,\\n 37.765930000, -122.467680000,\\n 37.765500000, -122.477180000,\\n 37.765300000, -122.481660000,\\n 37.764780000, -122.493350000,\\n 37.764120000, -122.508360000,\\n 37.766410000, -122.510260000,\\n 37.770010000, -122.510830000,\\n 37.770980000, -122.510930000\\n];\\n let value = gpsData.indexOf(prevValue); \\nreturn gpsData[(value == -1 ? 0 : (value + 2) % gpsData.length)];\",\"settings\":{},\"color\":\"#2196f3\",\"aggregationType\":null,\"units\":null,\"decimals\":null,\"usePostProcessing\":null,\"postFuncBody\":null},\"yKey\":{\"name\":\"f(x)\",\"label\":\"longitude\",\"type\":\"function\",\"funcBody\":\"var gpsData = [\\n37.771210000, -122.510960000,\\n 37.771990000, -122.497070000,\\n 37.772730000, -122.480740000,\\n 37.773360000, -122.466870000,\\n 37.774270000, -122.458520000,\\n 37.771980000, -122.454110000,\\n 37.768250000, -122.453380000,\\n 37.765920000, -122.456810000,\\n 37.765930000, -122.467680000,\\n 37.765500000, -122.477180000,\\n 37.765300000, -122.481660000,\\n 37.764780000, -122.493350000,\\n 37.764120000, -122.508360000,\\n 37.766410000, -122.510260000,\\n 37.770010000, -122.510830000,\\n 37.770980000, -122.510930000\\n];\\n let value = gpsData.indexOf(prevValue); \\nreturn gpsData[(value == -1 ? 1 : (value + 2) % gpsData.length)];\",\"settings\":{},\"color\":\"#2196f3\",\"aggregationType\":null,\"units\":null,\"decimals\":null,\"usePostProcessing\":null,\"postFuncBody\":null},\"markerType\":\"shape\",\"markerShape\":{\"shape\":\"tripMarkerShape1\",\"size\":34,\"color\":{\"type\":\"constant\",\"color\":\"#307FE5\"}},\"markerIcon\":{\"icon\":\"arrow_forward\",\"size\":48,\"color\":{\"type\":\"constant\",\"color\":\"#307FE5\"}},\"markerImage\":{\"type\":\"image\",\"image\":\"/assets/markers/tripShape1.svg\",\"imageSize\":34},\"markerOffsetX\":0.5,\"markerOffsetY\":0.5,\"positionFunction\":\"return {x: origXPos, y: origYPos};\",\"markerClustering\":{\"enable\":false,\"zoomOnClick\":true,\"maxZoom\":null,\"maxClusterRadius\":80,\"zoomAnimation\":true,\"showCoverageOnHover\":true,\"spiderfyOnMaxZoom\":false,\"chunkedLoad\":false,\"lazyLoad\":true,\"useClusterMarkerColorFunction\":false,\"clusterMarkerColorFunction\":null},\"label\":{\"show\":true,\"type\":\"pattern\",\"pattern\":\"${entityName}\"},\"tooltip\":{\"show\":true,\"trigger\":\"click\",\"autoclose\":true,\"type\":\"pattern\",\"pattern\":\"${entityName}
Latitude: ${latitude:7}
Longitude: ${longitude:7}
End Time: ${maxTime}
Start Time: ${minTime}\",\"offsetX\":0,\"offsetY\":-0.5},\"click\":{\"type\":\"doNothing\"},\"edit\":{\"enabledActions\":[],\"snappable\":false},\"rotateMarker\":true,\"offsetAngle\":0,\"showPath\":true,\"pathStrokeWeight\":2,\"pathStrokeColor\":{\"type\":\"constant\",\"color\":\"#307FE5\"},\"usePathDecorator\":false,\"pathDecoratorSymbol\":\"arrowHead\",\"pathDecoratorSymbolSize\":10,\"pathDecoratorSymbolColor\":\"#307FE5\",\"pathDecoratorOffset\":20,\"pathEndDecoratorOffset\":20,\"pathDecoratorRepeat\":20,\"showPoints\":false,\"pointSize\":10,\"pointColor\":{\"type\":\"constant\",\"color\":\"#307FE5\"},\"pointTooltip\":{\"show\":true,\"trigger\":\"click\",\"autoclose\":true,\"type\":\"pattern\",\"pattern\":\"${entityName}
Latitude: ${latitude:7}
Longitude: ${longitude:7}
End Time: ${maxTime}
Start Time: ${minTime}\",\"offsetX\":0,\"offsetY\":-1}}],\"markers\":[],\"polygons\":[],\"circles\":[],\"polylines\":[],\"additionalDataSources\":[],\"controlsPosition\":\"topleft\",\"zoomActions\":[\"scroll\",\"doubleClick\",\"controlButtons\"],\"scales\":[],\"dragModeButton\":false,\"fitMapBounds\":true,\"useDefaultCenterPosition\":false,\"defaultCenterPosition\":\"0,0\",\"defaultZoomLevel\":null,\"minZoomLevel\":16,\"mapPageSize\":16384,\"mapActionButtons\":[],\"tripTimeline\":{\"showTimelineControl\":true,\"timeStep\":1000,\"speedOptions\":[1,5,10,15,25],\"showTimestamp\":true,\"timestampFormat\":{\"format\":\"yyyy-MM-dd HH:mm:ss\",\"lastUpdateAgo\":false,\"custom\":false,\"auto\":false},\"snapToRealLocation\":false,\"locationSnapFilter\":\"return true;\"},\"background\":{\"type\":\"color\",\"color\":\"#fff\",\"overlay\":{\"enabled\":false,\"color\":\"rgba(255,255,255,0.72)\",\"blur\":3}},\"padding\":\"8px\"},\"title\":\"Trip Map\",\"dropShadow\":true,\"enableFullscreen\":true,\"titleStyle\":null,\"mobileHeight\":null,\"configMode\":\"basic\",\"actions\":{},\"showTitleIcon\":false,\"titleIcon\":\"assistant_navigation\",\"iconColor\":\"#1F6BDD\",\"useDashboardTimewindow\":false,\"displayTimewindow\":true,\"titleFont\":{\"size\":null,\"sizeUnit\":\"px\",\"family\":null,\"weight\":null,\"style\":null,\"lineHeight\":null},\"titleColor\":null,\"titleTooltip\":\"\",\"widgetStyle\":{},\"widgetCss\":\"\",\"pageSize\":1024,\"units\":\"\",\"decimals\":null,\"noDataDisplayMessage\":\"\",\"timewindowStyle\":{\"showIcon\":false,\"iconSize\":\"24px\",\"icon\":null,\"iconPosition\":\"left\",\"font\":{\"size\":12,\"sizeUnit\":\"px\",\"family\":\"Roboto\",\"weight\":\"400\",\"style\":\"normal\",\"lineHeight\":\"16px\"},\"color\":\"rgba(0, 0, 0, 0.38)\",\"displayTypePrefix\":true},\"margin\":\"0px\",\"borderRadius\":\"0px\",\"iconSize\":\"24px\",\"enableDataExport\":false}"
},
"resources": [
{
diff --git a/application/src/main/java/org/thingsboard/server/actors/ruleChain/DefaultTbContext.java b/application/src/main/java/org/thingsboard/server/actors/ruleChain/DefaultTbContext.java
index 59f0caacc5..7428df1e58 100644
--- a/application/src/main/java/org/thingsboard/server/actors/ruleChain/DefaultTbContext.java
+++ b/application/src/main/java/org/thingsboard/server/actors/ruleChain/DefaultTbContext.java
@@ -38,6 +38,7 @@ import org.thingsboard.rule.engine.util.TenantIdLoader;
import org.thingsboard.script.api.ScriptType;
import org.thingsboard.server.actors.ActorSystemContext;
import org.thingsboard.server.cluster.TbClusterService;
+import org.thingsboard.server.common.adaptor.JsonConverter;
import org.thingsboard.server.common.data.Customer;
import org.thingsboard.server.common.data.Dashboard;
import org.thingsboard.server.common.data.Device;
@@ -527,7 +528,11 @@ public class DefaultTbContext implements TbContext, TbPeContext {
if (attributes != null) {
attributes.forEach(attributeKvEntry -> JacksonUtil.addKvEntry(entityNode, attributeKvEntry));
}
- return attributesActionMsg(originator, ruleNodeId, scope, ATTRIBUTES_UPDATED, JacksonUtil.toString(entityNode));
+ TbMsgMetaData tbMsgMetaData = getActionMetaData(ruleNodeId);
+ // The saved string values that read back as numbers stay strings for the nodes that parse the notification.
+ List typeCastDisabledKeys = JsonConverter.numericStringKeys(attributes);
+ tbMsgMetaData.putTypeCastDisabledKeys(typeCastDisabledKeys);
+ return attributesActionMsg(originator, tbMsgMetaData, scope, ATTRIBUTES_UPDATED, JacksonUtil.toString(entityNode));
}
@Override
@@ -537,11 +542,10 @@ public class DefaultTbContext implements TbContext, TbPeContext {
if (keys != null) {
keys.forEach(attrsArrayNode::add);
}
- return attributesActionMsg(originator, ruleNodeId, scope, ATTRIBUTES_DELETED, JacksonUtil.toString(entityNode));
+ return attributesActionMsg(originator, getActionMetaData(ruleNodeId), scope, ATTRIBUTES_DELETED, JacksonUtil.toString(entityNode));
}
- private TbMsg attributesActionMsg(EntityId originator, RuleNodeId ruleNodeId, String scope, TbMsgType actionMsgType, String msgData) {
- TbMsgMetaData tbMsgMetaData = getActionMetaData(ruleNodeId);
+ private TbMsg attributesActionMsg(EntityId originator, TbMsgMetaData tbMsgMetaData, String scope, TbMsgType actionMsgType, String msgData) {
tbMsgMetaData.putValue("scope", scope);
HasRuleEngineProfile profile = getRuleEngineProfile(originator);
return entityActionMsg(originator, tbMsgMetaData, msgData, actionMsgType, profile);
diff --git a/application/src/main/java/org/thingsboard/server/config/CustomOAuth2AuthorizationRequestResolver.java b/application/src/main/java/org/thingsboard/server/config/CustomOAuth2AuthorizationRequestResolver.java
index 029abec8f2..60ab8f3649 100644
--- a/application/src/main/java/org/thingsboard/server/config/CustomOAuth2AuthorizationRequestResolver.java
+++ b/application/src/main/java/org/thingsboard/server/config/CustomOAuth2AuthorizationRequestResolver.java
@@ -1,5 +1,6 @@
// SPDX-FileCopyrightText: Copyright The ThingsBoard Authors
-// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Modifications Copyright ThingsBoard, Inc.
+// SPDX-License-Identifier: Apache-2.0 AND BUSL-1.1
package org.thingsboard.server.config;
import jakarta.servlet.http.HttpServletRequest;
@@ -17,8 +18,8 @@ import org.springframework.security.oauth2.core.endpoint.OAuth2ParameterNames;
import org.springframework.security.oauth2.core.endpoint.PkceParameterNames;
import org.springframework.security.oauth2.core.oidc.OidcScopes;
import org.springframework.security.oauth2.core.oidc.endpoint.OidcParameterNames;
+import org.springframework.security.web.servlet.util.matcher.PathPatternRequestMatcher;
import org.springframework.security.web.util.UrlUtils;
-import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.web.util.UriComponents;
@@ -50,7 +51,7 @@ public class CustomOAuth2AuthorizationRequestResolver implements OAuth2Authoriza
private static final String REGISTRATION_ID_URI_VARIABLE_NAME = "registrationId";
private static final char PATH_DELIMITER = '/';
- private final AntPathRequestMatcher authorizationRequestMatcher = new AntPathRequestMatcher(
+ private final PathPatternRequestMatcher authorizationRequestMatcher = PathPatternRequestMatcher.withDefaults().matcher(
DEFAULT_AUTHORIZATION_REQUEST_BASE_URI + "/{" + REGISTRATION_ID_URI_VARIABLE_NAME + "}");
private final StringKeyGenerator stateGenerator = new Base64StringKeyGenerator(Base64.getUrlEncoder());
private final StringKeyGenerator secureKeyGenerator = new Base64StringKeyGenerator(Base64.getUrlEncoder().withoutPadding(), 96);
@@ -212,7 +213,7 @@ public class CustomOAuth2AuthorizationRequestResolver implements OAuth2Authoriza
Map uriVariables = new HashMap<>();
uriVariables.put("registrationId", clientRegistration.getRegistrationId());
- UriComponents uriComponents = UriComponentsBuilder.fromHttpUrl(UrlUtils.buildFullRequestUrl(request))
+ UriComponents uriComponents = UriComponentsBuilder.fromUriString(UrlUtils.buildFullRequestUrl(request))
.replacePath(request.getContextPath())
.replaceQuery(null)
.fragment(null)
diff --git a/application/src/main/java/org/thingsboard/server/config/TbRuleEngineSecurityConfiguration.java b/application/src/main/java/org/thingsboard/server/config/TbRuleEngineSecurityConfiguration.java
index c57cd26470..a0a9ebe038 100644
--- a/application/src/main/java/org/thingsboard/server/config/TbRuleEngineSecurityConfiguration.java
+++ b/application/src/main/java/org/thingsboard/server/config/TbRuleEngineSecurityConfiguration.java
@@ -1,10 +1,11 @@
// SPDX-FileCopyrightText: Copyright The ThingsBoard Authors
-// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Modifications Copyright ThingsBoard, Inc.
+// SPDX-License-Identifier: Apache-2.0 AND BUSL-1.1
package org.thingsboard.server.config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnExpression;
-import org.springframework.boot.autoconfigure.security.SecurityProperties;
+import org.springframework.boot.security.autoconfigure.web.servlet.SecurityFilterProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
@@ -17,7 +18,7 @@ import org.springframework.security.web.SecurityFilterChain;
@Configuration
@EnableWebSecurity
@EnableMethodSecurity
-@Order(SecurityProperties.BASIC_AUTH_ORDER)
+@Order(SecurityFilterProperties.BASIC_AUTH_ORDER)
@ConditionalOnExpression("'${service.type:null}'=='tb-rule-engine'")
public class TbRuleEngineSecurityConfiguration {
diff --git a/application/src/main/java/org/thingsboard/server/config/ThingsboardSecurityConfiguration.java b/application/src/main/java/org/thingsboard/server/config/ThingsboardSecurityConfiguration.java
index a064a5bbaf..7cddb8fc56 100644
--- a/application/src/main/java/org/thingsboard/server/config/ThingsboardSecurityConfiguration.java
+++ b/application/src/main/java/org/thingsboard/server/config/ThingsboardSecurityConfiguration.java
@@ -7,7 +7,7 @@ import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
-import org.springframework.boot.autoconfigure.security.SecurityProperties;
+import org.springframework.boot.security.autoconfigure.web.servlet.SecurityFilterProperties;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@@ -61,7 +61,7 @@ import java.util.stream.Stream;
@Configuration
@EnableWebSecurity
@EnableMethodSecurity
-@Order(SecurityProperties.BASIC_AUTH_ORDER)
+@Order(SecurityFilterProperties.BASIC_AUTH_ORDER)
@TbCoreComponent
public class ThingsboardSecurityConfiguration {
diff --git a/application/src/main/java/org/thingsboard/server/controller/AdminController.java b/application/src/main/java/org/thingsboard/server/controller/AdminController.java
index 8f6ff14d60..7b33cf7308 100644
--- a/application/src/main/java/org/thingsboard/server/controller/AdminController.java
+++ b/application/src/main/java/org/thingsboard/server/controller/AdminController.java
@@ -75,7 +75,9 @@ import org.thingsboard.server.service.security.model.SecurityUser;
import org.thingsboard.server.service.security.model.token.JwtTokenFactory;
import org.thingsboard.server.service.security.system.SystemSecurityService;
import org.thingsboard.server.service.sync.vc.EntitiesVersionControlService;
+import org.thingsboard.server.service.sync.vc.autocommit.DefaultTbAutoCommitSettingsService;
import org.thingsboard.server.service.sync.vc.autocommit.TbAutoCommitSettingsService;
+import org.thingsboard.server.service.sync.vc.repository.DefaultTbRepositorySettingsService;
import org.thingsboard.server.service.system.SystemInfoService;
import org.thingsboard.server.service.update.UpdateService;
@@ -166,6 +168,10 @@ public class AdminController extends BaseController {
} else {
accessControlService.checkPermission(getCurrentUser(), Resource.WHITE_LABELING, Operation.WRITE);
}
+ String key = adminSettings.getKey();
+ if (DefaultTbRepositorySettingsService.SETTINGS_KEY.equals(key) || DefaultTbAutoCommitSettingsService.SETTINGS_KEY.equals(key)) {
+ throw new ThingsboardException("Settings with key '" + key + "' can be saved only through the version control API", ThingsboardErrorCode.BAD_REQUEST_PARAMS);
+ }
adminSettings = checkNotNull(adminSettingsService.saveAdminSettings(tenantId, adminSettings));
if (adminSettings.getKey().equals(MAIL_SETTINGS_KEY)) {
((ObjectNode) adminSettings.getJsonValue()).remove("refreshToken");
diff --git a/application/src/main/java/org/thingsboard/server/controller/AiChatController.java b/application/src/main/java/org/thingsboard/server/controller/AiChatController.java
index bbd9366776..6c05737fb3 100644
--- a/application/src/main/java/org/thingsboard/server/controller/AiChatController.java
+++ b/application/src/main/java/org/thingsboard/server/controller/AiChatController.java
@@ -65,6 +65,15 @@ class AiChatController extends BaseController {
aiChatService.updateChat(chatId, request, user);
}
+ @PreAuthorize("hasAuthority('TENANT_ADMIN')")
+ @PostMapping("/{chatId}/stop")
+ @ResponseStatus(HttpStatus.NO_CONTENT)
+ public void stopChat(@PathVariable UUID chatId) throws ThingsboardException {
+ SecurityUser user = getCurrentUser();
+ accessControlService.checkPermission(user, Resource.AI, Operation.WRITE);
+ aiChatService.stopChat(chatId, user);
+ }
+
@PreAuthorize("hasAuthority('TENANT_ADMIN')")
@GetMapping
public JsonNode listChats() throws ThingsboardException {
@@ -73,6 +82,14 @@ class AiChatController extends BaseController {
return aiChatService.listChats(user);
}
+ @PreAuthorize("hasAuthority('TENANT_ADMIN')")
+ @GetMapping("/status")
+ public JsonNode listChatStatuses() throws ThingsboardException {
+ SecurityUser user = getCurrentUser();
+ accessControlService.checkPermission(user, Resource.AI, Operation.READ);
+ return aiChatService.listChatStatuses(user);
+ }
+
@PreAuthorize("hasAuthority('TENANT_ADMIN')")
@GetMapping("/{chatId}/messages")
public JsonNode getChatMessages(@PathVariable UUID chatId) throws ThingsboardException {
diff --git a/application/src/main/java/org/thingsboard/server/controller/AiSolutionController.java b/application/src/main/java/org/thingsboard/server/controller/AiSolutionController.java
index 3bc73f3428..14fc76ee3a 100644
--- a/application/src/main/java/org/thingsboard/server/controller/AiSolutionController.java
+++ b/application/src/main/java/org/thingsboard/server/controller/AiSolutionController.java
@@ -92,6 +92,14 @@ public class AiSolutionController extends BaseController {
return aiSolutionService.createSolution(solutionId, user);
}
+ @PreAuthorize("hasAuthority('TENANT_ADMIN')")
+ @PostMapping("/{solutionId}/stop")
+ public JsonNode stopSolution(@PathVariable UUID solutionId) throws ThingsboardException {
+ SecurityUser user = getCurrentUser();
+ accessControlService.checkPermission(user, Resource.AI, Operation.WRITE);
+ return aiSolutionService.stopSolution(solutionId, user);
+ }
+
@PreAuthorize("hasAuthority('TENANT_ADMIN')")
@PutMapping("/{solutionId}/{dataKey}")
public JsonNode updateData(@PathVariable UUID solutionId,
@@ -110,6 +118,22 @@ public class AiSolutionController extends BaseController {
aiSolutionService.clearStep(solutionId, step, user);
}
+ @PreAuthorize("hasAuthority('TENANT_ADMIN')")
+ @PostMapping(value = "/{solutionId}/update", consumes = MediaType.APPLICATION_JSON_VALUE)
+ public void updateSolution(@PathVariable UUID solutionId, @RequestBody JsonNode request) throws ThingsboardException {
+ SecurityUser user = getCurrentUser();
+ accessControlService.checkPermission(user, Resource.AI, Operation.WRITE);
+ aiSolutionService.updateSolution(solutionId, request, user);
+ }
+
+ @PreAuthorize("hasAuthority('TENANT_ADMIN')")
+ @GetMapping("/{solutionId}/progress")
+ public JsonNode getInstallProgress(@PathVariable UUID solutionId) throws ThingsboardException {
+ SecurityUser user = getCurrentUser();
+ accessControlService.checkPermission(user, Resource.AI, Operation.READ);
+ return aiSolutionService.getInstallProgress(solutionId, user);
+ }
+
@PreAuthorize("hasAuthority('TENANT_ADMIN')")
@PostMapping("/{solutionId}/install")
public JsonNode installSolution(@PathVariable UUID solutionId,
diff --git a/application/src/main/java/org/thingsboard/server/controller/ApiKeyController.java b/application/src/main/java/org/thingsboard/server/controller/ApiKeyController.java
index 6bc50d1253..77d91794fe 100644
--- a/application/src/main/java/org/thingsboard/server/controller/ApiKeyController.java
+++ b/application/src/main/java/org/thingsboard/server/controller/ApiKeyController.java
@@ -116,6 +116,10 @@ public class ApiKeyController extends BaseController {
UserId userId = new UserId(toUUID(userIdStr));
accessControlService.checkPermission(securityUser, Resource.API_KEY, Operation.READ);
User user = checkUserId(userId, Operation.READ);
+ ApiKeyInfo keyOwner = new ApiKeyInfo();
+ keyOwner.setTenantId(user.getTenantId());
+ keyOwner.setUserId(userId);
+ accessControlService.checkPermission(securityUser, Resource.API_KEY, Operation.READ, null, keyOwner);
return apiKeyService.findApiKeysByUserId(user.getTenantId(), userId, pageLink);
}
diff --git a/application/src/main/java/org/thingsboard/server/controller/BaseController.java b/application/src/main/java/org/thingsboard/server/controller/BaseController.java
index e597cd192f..ac2750ee56 100644
--- a/application/src/main/java/org/thingsboard/server/controller/BaseController.java
+++ b/application/src/main/java/org/thingsboard/server/controller/BaseController.java
@@ -148,6 +148,8 @@ import org.thingsboard.server.common.data.menu.CustomMenuInfo;
import org.thingsboard.server.common.data.mobile.app.MobileApp;
import org.thingsboard.server.common.data.mobile.bundle.MobileAppBundle;
import org.thingsboard.server.common.data.notification.targets.NotificationTarget;
+import org.thingsboard.server.common.data.notification.template.NotificationTemplate;
+import org.thingsboard.server.common.data.notification.template.NotificationTemplateConfig;
import org.thingsboard.server.common.data.oauth2.OAuth2Client;
import org.thingsboard.server.common.data.page.PageData;
import org.thingsboard.server.common.data.page.PageLink;
@@ -894,6 +896,49 @@ public abstract class BaseController {
}
}
+ protected void checkReportUser(UserId userId) throws ThingsboardException {
+ if (!getCurrentUser().getId().equals(userId)) {
+ checkUserId(userId, Operation.IMPERSONATE);
+ }
+ }
+
+ protected UserId resolveReportUser(UserId userId, boolean useCurrentUserCredentials) throws ThingsboardException {
+ SecurityUser currentUser = getCurrentUser();
+ if (useCurrentUserCredentials && !currentUser.getId().equals(userId) && !canImpersonate(userId)) {
+ return currentUser.getId();
+ }
+ checkReportUser(userId);
+ return userId;
+ }
+
+ private boolean canImpersonate(UserId userId) throws ThingsboardException {
+ SecurityUser currentUser = getCurrentUser();
+ User user = userService.findUserById(currentUser.getTenantId(), userId);
+ return user != null && currentUser.getTenantId().equals(user.getTenantId()) &&
+ accessControlService.hasPermission(currentUser, Resource.USER, Operation.IMPERSONATE, userId, user);
+ }
+
+ protected void checkTemplateReportUser(NotificationTemplate notificationTemplate) throws ThingsboardException {
+ NotificationTemplateConfig configuration = notificationTemplate != null ? notificationTemplate.getConfiguration() : null;
+ if (configuration != null && configuration.isAttachReport() && configuration.getUserId() != null) {
+ checkReportUser(configuration.getUserId());
+ }
+ }
+
+ protected void checkMsgReportUser(JsonNode msg) throws ThingsboardException {
+ if (msg == null) {
+ return;
+ }
+ checkReportUserIfPresent(msg.path("reportConfig").path("userId"));
+ checkReportUserIfPresent(msg.path("userId").path("id"));
+ }
+
+ private void checkReportUserIfPresent(JsonNode reportUserId) throws ThingsboardException {
+ if (reportUserId.isTextual() && StringUtils.isNotBlank(reportUserId.asText())) {
+ checkReportUser(new UserId(toUUID(reportUserId.asText())));
+ }
+ }
+
UserInfo checkUserInfoId(UserId userId, Operation operation) throws ThingsboardException {
try {
validateId(userId, id -> "Incorrect userId " + id);
@@ -1097,7 +1142,11 @@ public abstract class BaseController {
for (EntityId referencedEntityId : calculatedFieldConfig.getReferencedEntities()) {
EntityType refEntityType = referencedEntityId.getEntityType();
switch (refEntityType) {
- case TENANT -> {}
+ case TENANT -> {
+ if (!getTenantId().equals(referencedEntityId)) {
+ throw permissionDenied();
+ }
+ }
case CUSTOMER, ASSET, DEVICE -> checkEntityId(referencedEntityId, Operation.READ);
default -> throw new IllegalArgumentException("Unsupported referenced entity type: '" + refEntityType + "'.");
}
@@ -1246,7 +1295,7 @@ public abstract class BaseController {
protected EntityGroupInfo checkEntityGroupId(EntityGroupId entityGroupId, Operation operation) throws ThingsboardException {
try {
validateId(entityGroupId, id -> "Incorrect entityGroupId " + id);
- EntityGroupInfo entityGroup = entityGroupService.findEntityGroupInfoById(getTenantId(), entityGroupId);
+ EntityGroupInfo entityGroup = entityGroupService.findEntityGroupInfoByTenantIdAndId(getTenantId(), entityGroupId);
checkNotNull(entityGroup, "Entity group with id [" + entityGroupId + "] is not found");
accessControlService.checkEntityGroupInfoPermission(getCurrentUser(), operation, entityGroup);
return entityGroup;
diff --git a/application/src/main/java/org/thingsboard/server/controller/DashboardReportController.java b/application/src/main/java/org/thingsboard/server/controller/DashboardReportController.java
index 918c5dd8db..0aeae3a97d 100644
--- a/application/src/main/java/org/thingsboard/server/controller/DashboardReportController.java
+++ b/application/src/main/java/org/thingsboard/server/controller/DashboardReportController.java
@@ -29,6 +29,7 @@ import org.thingsboard.server.common.data.id.DashboardId;
import org.thingsboard.server.common.data.id.TenantId;
import org.thingsboard.server.common.data.id.UserId;
import org.thingsboard.server.common.data.permission.Operation;
+import org.thingsboard.server.common.data.security.Authority;
import org.thingsboard.server.config.annotations.ApiOperation;
import org.thingsboard.server.dao.subscription.PlatformFeature;
import org.thingsboard.server.queue.util.TbCoreComponent;
@@ -61,6 +62,7 @@ public class DashboardReportController extends BaseController {
private final SystemSecurityService systemSecurityService;
public static final String DASHBOARD_ID = "dashboardId";
+ public static final String USER_ID = "userId";
@ApiOperation(value = "Download dashboard report (downloadDashboardReport)",
notes = "Generate and download a report from the specified dashboard. " +
@@ -125,6 +127,14 @@ public class DashboardReportController extends BaseController {
DashboardId dashboardId = new DashboardId(toUUID(strDashboardId));
checkDashboardInfoId(dashboardId, Operation.READ);
+ String strUserId = reportConfig.getUserId();
+ checkParameter(USER_ID, strUserId);
+ UserId reportUserId = resolveReportUser(new UserId(toUUID(strUserId)), reportConfig.isUseCurrentUserCredentials());
+ reportConfig.setUserId(reportUserId.toString());
+
+ if (Authority.CUSTOMER_USER.equals(getCurrentUser().getAuthority())) {
+ reportsServerEndpointUrl = null;
+ }
dashboardReportService.generateReport(getTenantId(), reportConfig, reportsServerEndpointUrl, onSuccess(result), result::setErrorResult);
} catch (Exception e) {
result.setErrorResult(e);
diff --git a/application/src/main/java/org/thingsboard/server/controller/EntityGroupController.java b/application/src/main/java/org/thingsboard/server/controller/EntityGroupController.java
index cdf2f171c8..40499b2d2f 100644
--- a/application/src/main/java/org/thingsboard/server/controller/EntityGroupController.java
+++ b/application/src/main/java/org/thingsboard/server/controller/EntityGroupController.java
@@ -57,6 +57,7 @@ import org.thingsboard.server.common.data.permission.Operation;
import org.thingsboard.server.common.data.permission.Resource;
import org.thingsboard.server.common.data.permission.ShareGroupRequest;
import org.thingsboard.server.common.data.role.Role;
+import org.thingsboard.server.common.data.role.RoleType;
import org.thingsboard.server.common.data.security.Authority;
import org.thingsboard.server.config.annotations.ApiOperation;
import org.thingsboard.server.dao.owner.OwnerService;
@@ -210,9 +211,8 @@ public class EntityGroupController extends AutoCommitController {
@RequestBody EntityGroup entityGroup) throws Exception {
SecurityUser currentUser = getCurrentUser();
checkEntityGroupType(entityGroup.getType());
- Operation operation = entityGroup.getId() == null ? Operation.CREATE : Operation.WRITE;
EntityId parentEntityId = entityGroup.getOwnerId();
- if (operation == Operation.CREATE) {
+ if (entityGroup.getId() == null) {
if (parentEntityId == null || parentEntityId.isNullUid()) {
parentEntityId = currentUser.getOwnerId();
} else {
@@ -221,14 +221,12 @@ public class EntityGroupController extends AutoCommitController {
"Invalid entity group ownerId!", ThingsboardErrorCode.PERMISSION_DENIED);
}
}
+ EntityGroupInfo entityGroupInfo = new EntityGroupInfo(entityGroup, ownersCacheService.fetchOwnersHierarchy(getTenantId(), parentEntityId));
+ accessControlService.checkEntityGroupInfoPermission(currentUser, Operation.CREATE, entityGroupInfo);
} else {
- validateEntityId(parentEntityId, id -> "Incorrect entity group ownerId " + id);
+ parentEntityId = checkEntityGroupId(entityGroup.getId(), Operation.WRITE).getOwnerId();
}
- EntityGroupInfo entityGroupInfo = new EntityGroupInfo(entityGroup, ownersCacheService.fetchOwnersHierarchy(getTenantId(), parentEntityId));
-
- accessControlService.checkEntityGroupInfoPermission(currentUser, operation, entityGroupInfo);
-
return tbEntityGroupService.save(getTenantId(), parentEntityId, entityGroup, getCurrentUser());
}
@@ -967,7 +965,11 @@ public class EntityGroupController extends AutoCommitController {
for (String strEntityGroupId : strEntityGroupIds) {
entityGroupIds.add(new EntityGroupId(toUUID(strEntityGroupId)));
}
- return checkNotNull(entityGroupService.findEntityGroupEntityInfosByIds(tenantId, entityGroupIds, new PageLink(Integer.MAX_VALUE)).getData());
+ List entityGroups = checkNotNull(
+ entityGroupService.findEntityGroupInfosByIds(tenantId, entityGroupIds, new PageLink(Integer.MAX_VALUE)).getData());
+ return filterEntityGroupsByReadPermission(entityGroups).stream()
+ .map(entityGroup -> new EntityInfo(entityGroup.getId(), entityGroup.getName()))
+ .toList();
}
@ApiOperation(value = "Get Owners (getOwners)",
@@ -1145,7 +1147,8 @@ public class EntityGroupController extends AutoCommitController {
@ApiOperation(value = "Share the Entity Group (shareEntityGroup)",
notes = "Share the entity group with certain user group based on the provided Share Group Request. " +
- "The request is quite flexible and processing of the request involves multiple security checks using platform RBAC feature."
+ "The request is quite flexible and processing of the request involves multiple security checks using platform RBAC feature. " +
+ "Each role in 'roleIds' must be a group role readable by the current user, and each of its operations must be granted to the current user for the entity group or its entities."
+ TENANT_OR_CUSTOMER_AUTHORITY_PARAGRAPH + RBAC_GROUP_WRITE_CHECK)
@PreAuthorize("hasAnyAuthority('TENANT_ADMIN', 'CUSTOMER_USER')")
@PostMapping(value = "/entityGroup/{entityGroupId}/share")
@@ -1165,21 +1168,25 @@ public class EntityGroupController extends AutoCommitController {
EntityGroupInfo userGroup;
if (shareGroupRequest.isAllUserGroup()) {
- Optional userGroupOptional = entityGroupService.findEntityGroupInfoByTypeAndName(getTenantId(), shareGroupRequest.getOwnerId(),
- EntityType.USER, EntityGroup.GROUP_ALL_NAME);
+ Optional userGroupOptional = findAllUserGroup(shareGroupRequest.getOwnerId());
if (userGroupOptional.isPresent()) {
userGroup = userGroupOptional.get();
} else {
throw new ThingsboardException("Requested item wasn't found!", ThingsboardErrorCode.ITEM_NOT_FOUND);
}
} else {
- userGroup = entityGroupService.findEntityGroupInfoById(getTenantId(), shareGroupRequest.getUserGroupId());
+ userGroup = checkNotNull(entityGroupService.findEntityGroupInfoByTenantIdAndId(getTenantId(), shareGroupRequest.getUserGroupId()));
}
accessControlService.checkEntityGroupInfoPermission(getCurrentUser(), Operation.WRITE, userGroup);
- List roleIds;
+ List roles;
if (shareGroupRequest.getRoleIds() != null && !shareGroupRequest.getRoleIds().isEmpty()) {
- roleIds = shareGroupRequest.getRoleIds();
+ roles = new ArrayList<>();
+ for (RoleId roleId : shareGroupRequest.getRoleIds()) {
+ Role role = checkRoleId(roleId, Operation.READ);
+ checkGroupRoleAllowedForShare(role, entityGroup);
+ roles.add(role);
+ }
} else {
Role role;
if (shareGroupRequest.isReadElseWrite()) {
@@ -1187,15 +1194,15 @@ public class EntityGroupController extends AutoCommitController {
} else {
role = roleService.findOrCreateWriteEntityGroupRole(getTenantId(), getCurrentUser().getCustomerId());
}
- roleIds = Collections.singletonList(role.getId());
+ roles = Collections.singletonList(role);
}
- for (RoleId roleId : roleIds) {
+ for (Role role : roles) {
GroupPermission groupPermission = new GroupPermission();
groupPermission.setTenantId(getTenantId());
groupPermission.setEntityGroupId(entityGroup.getId());
groupPermission.setEntityGroupType(entityGroup.getType());
- groupPermission.setRoleId(roleId);
+ groupPermission.setRoleId(role.getId());
groupPermission.setUserGroupId(userGroup.getId());
GroupPermission savedGroupPermission = checkNotNull(groupPermissionService.saveGroupPermission(getTenantId(), groupPermission));
@@ -1246,7 +1253,7 @@ public class EntityGroupController extends AutoCommitController {
checkParameter("userGroupId", strUserGroupId);
checkParameter("roleId", strRoleId);
EntityGroupId userGroupId = new EntityGroupId(toUUID(strUserGroupId));
- EntityGroup userGroup = entityGroupService.findEntityGroupById(getTenantId(), userGroupId);
+ EntityGroup userGroup = entityGroupService.findEntityGroupInfoByTenantIdAndId(getTenantId(), userGroupId);
if (userGroup == null) {
throw new ThingsboardException("User group with requested id: " + userGroupId + " wasn't found!", ThingsboardErrorCode.ITEM_NOT_FOUND);
}
@@ -1299,7 +1306,7 @@ public class EntityGroupController extends AutoCommitController {
private EntityGroup resolveEntityGroup(UUID entityGroupUuid) throws ThingsboardException {
EntityGroupId entityGroupId = new EntityGroupId(entityGroupUuid);
- EntityGroup entityGroup = entityGroupService.findEntityGroupById(getTenantId(), entityGroupId);
+ EntityGroup entityGroup = entityGroupService.findEntityGroupInfoByTenantIdAndId(getTenantId(), entityGroupId);
if (entityGroup == null) {
throw new ThingsboardException("Entity group with requested id: " + entityGroupId + " wasn't found!", ThingsboardErrorCode.ITEM_NOT_FOUND);
}
@@ -1309,15 +1316,14 @@ public class EntityGroupController extends AutoCommitController {
private EntityGroupInfo resolveUserGroup(ShareGroupRequest shareGroupRequest) throws ThingsboardException {
EntityGroupInfo userGroup;
if (shareGroupRequest.isAllUserGroup()) {
- Optional userGroupOptional = entityGroupService.findEntityGroupInfoByTypeAndName(getTenantId(), shareGroupRequest.getOwnerId(),
- EntityType.USER, EntityGroup.GROUP_ALL_NAME);
+ Optional userGroupOptional = findAllUserGroup(shareGroupRequest.getOwnerId());
if (userGroupOptional.isPresent()) {
userGroup = userGroupOptional.get();
} else {
throw new ThingsboardException("Requested item wasn't found!", ThingsboardErrorCode.ITEM_NOT_FOUND);
}
} else {
- userGroup = entityGroupService.findEntityGroupInfoById(getTenantId(), shareGroupRequest.getUserGroupId());
+ userGroup = entityGroupService.findEntityGroupInfoByTenantIdAndId(getTenantId(), shareGroupRequest.getUserGroupId());
}
if (userGroup == null) {
throw new ThingsboardException("Specified user group wasn't found!", ThingsboardErrorCode.ITEM_NOT_FOUND);
@@ -1325,6 +1331,12 @@ public class EntityGroupController extends AutoCommitController {
return userGroup;
}
+ private Optional findAllUserGroup(EntityId ownerId) throws ThingsboardException {
+ TenantId tenantId = getTenantId();
+ return entityGroupService.findEntityGroupInfoByTypeAndName(tenantId, ownerId, EntityType.USER, EntityGroup.GROUP_ALL_NAME)
+ .map(group -> entityGroupService.findEntityGroupInfoByTenantIdAndId(tenantId, group.getId()));
+ }
+
private List resolveRoles(ShareGroupRequest shareGroupRequest) throws ThingsboardException {
List roles = new ArrayList<>(1);
if (shareGroupRequest.getRoleIds() != null && !shareGroupRequest.getRoleIds().isEmpty()) {
@@ -1504,9 +1516,29 @@ public class EntityGroupController extends AutoCommitController {
}
}
- private void shareGroup(Role role, EntityGroup userGroup, EntityGroup entityGroup, Set mergedOperations) throws ThingsboardException {
+ private void checkGroupRoleAllowedForShare(Role role, EntityGroup entityGroup) throws ThingsboardException {
+ if (role.getType() == RoleType.GENERIC) {
+ throw new ThingsboardException("Can't assign Generic Role to entity group!", ThingsboardErrorCode.BAD_REQUEST_PARAMS);
+ }
+ MergedUserPermissions userPermissions = getCurrentUser().getUserPermissions();
+ Resource groupResource = Resource.groupResourceFromGroupType(entityGroup.getType());
+ Resource entityResource = Resource.resourceFromEntityType(entityGroup.getType());
+ for (Operation operation : toRoleOperations(role)) {
+ if (!userPermissions.hasGenericPermission(groupResource, operation)
+ && !userPermissions.hasGenericPermission(entityResource, operation)
+ && !userPermissions.hasGroupPermissions(entityGroup.getId(), operation)) {
+ throw permissionDenied();
+ }
+ }
+ }
+
+ private List toRoleOperations(Role role) {
CollectionType collectionType = TypeFactory.defaultInstance().constructCollectionType(List.class, Operation.class);
- List roleOperations = JacksonUtil.readValue(role.getPermissions().toString(), collectionType);
+ return JacksonUtil.readValue(role.getPermissions().toString(), collectionType);
+ }
+
+ private void shareGroup(Role role, EntityGroup userGroup, EntityGroup entityGroup, Set mergedOperations) throws ThingsboardException {
+ List roleOperations = toRoleOperations(role);
if (!mergedOperations.isEmpty() && (mergedOperations.contains(Operation.ALL) || mergedOperations.containsAll(roleOperations))) {
GroupPermission savedGroupPermission = groupPermissionService.saveGroupPermission(getTenantId(), new GroupPermission(getTenantId(), userGroup.getId(), role.getId(), entityGroup.getId(), entityGroup.getId().getEntityType(), false));
userPermissionsService.onGroupPermissionUpdated(savedGroupPermission);
diff --git a/application/src/main/java/org/thingsboard/server/controller/EntityViewController.java b/application/src/main/java/org/thingsboard/server/controller/EntityViewController.java
index 4fe1ff0eb7..583afbaaa8 100644
--- a/application/src/main/java/org/thingsboard/server/controller/EntityViewController.java
+++ b/application/src/main/java/org/thingsboard/server/controller/EntityViewController.java
@@ -48,6 +48,7 @@ import org.thingsboard.server.service.security.model.SecurityUser;
import java.util.ArrayList;
import java.util.List;
+import java.util.Objects;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.ExecutionException;
@@ -132,6 +133,11 @@ public class EntityViewController extends BaseController {
SecurityUser user = getCurrentUser();
return saveGroupEntity(entityView, strEntityGroupId, strEntityGroupIds, (entityView1, entityGroups) -> {
try {
+ EntityView existingEntityView = entityView1.getId() == null ? null :
+ entityViewService.findEntityViewById(user.getTenantId(), entityView1.getId());
+ if (existingEntityView == null || !hasSameSourceData(existingEntityView, entityView1)) {
+ checkEntityId(entityView1.getEntityId(), Operation.READ);
+ }
return tbEntityViewService.save(entityView1, entityGroups, new NameConflictStrategy(nameConflictPolicy, uniquifySeparator, uniquifyStrategy), user);
} catch (Exception e) {
throw handleException(e);
@@ -451,4 +457,11 @@ public class EntityViewController extends BaseController {
return checkNotNull(entityViewTypes.get());
}
+ private static boolean hasSameSourceData(EntityView existing, EntityView entityView) {
+ return Objects.equals(existing.getEntityId(), entityView.getEntityId())
+ && Objects.equals(existing.getKeys(), entityView.getKeys())
+ && existing.getStartTimeMs() == entityView.getStartTimeMs()
+ && existing.getEndTimeMs() == entityView.getEndTimeMs();
+ }
+
}
diff --git a/application/src/main/java/org/thingsboard/server/controller/GroupPermissionController.java b/application/src/main/java/org/thingsboard/server/controller/GroupPermissionController.java
index 9d26820989..71d2097da7 100644
--- a/application/src/main/java/org/thingsboard/server/controller/GroupPermissionController.java
+++ b/application/src/main/java/org/thingsboard/server/controller/GroupPermissionController.java
@@ -19,6 +19,7 @@ import org.thingsboard.server.common.data.EntityType;
import org.thingsboard.server.common.data.audit.ActionType;
import org.thingsboard.server.common.data.exception.ThingsboardErrorCode;
import org.thingsboard.server.common.data.exception.ThingsboardException;
+import org.thingsboard.server.common.data.group.EntityGroupInfo;
import org.thingsboard.server.common.data.id.EntityGroupId;
import org.thingsboard.server.common.data.id.EntityId;
import org.thingsboard.server.common.data.id.GroupPermissionId;
@@ -116,6 +117,7 @@ public class GroupPermissionController extends BaseController {
.checkPermission(getCurrentUser(), Resource.GROUP_PERMISSION, Operation.CREATE, null, groupPermission);
} else {
oldGroupPermission = checkGroupPermissionId(groupPermission.getId(), Operation.WRITE);
+ checkGroupPermissionManageable(oldGroupPermission);
}
if (groupPermission.isPublic()) {
@@ -168,17 +170,7 @@ public class GroupPermissionController extends BaseController {
try {
GroupPermissionId groupPermissionId = new GroupPermissionId(toUUID(strGroupPermissionId));
GroupPermission groupPermission = checkGroupPermissionId(groupPermissionId, Operation.DELETE);
- if (groupPermission.isPublic()) {
- throw permissionDenied();
- }
-
- checkRoleId(groupPermission.getRoleId(), Operation.READ);
- if (groupPermission.getUserGroupId() != null && !groupPermission.getUserGroupId().isNullUid()) {
- checkEntityGroupId(groupPermission.getUserGroupId(), Operation.WRITE);
- }
- if (groupPermission.getEntityGroupId() != null && !groupPermission.getEntityGroupId().isNullUid()) {
- checkEntityGroupId(groupPermission.getEntityGroupId(), Operation.WRITE);
- }
+ checkGroupPermissionManageable(groupPermission);
groupPermissionService.deleteGroupPermission(getTenantId(), groupPermissionId);
userPermissionsService.onGroupPermissionDeleted(groupPermission);
@@ -218,7 +210,8 @@ public class GroupPermissionController extends BaseController {
@RequestBody List permissions) throws ThingsboardException, ExecutionException, InterruptedException {
TenantId tenantId = getCurrentUser().getTenantId();
accessControlService.checkPermission(getCurrentUser(), Resource.GROUP_PERMISSION, Operation.READ);
- List permissionInfoList = groupPermissionService.loadUserGroupPermissionInfoListAsync(tenantId, permissions).get();
+ List readablePermissions = permissions.stream().filter(this::isReadableEntityGroup).toList();
+ List permissionInfoList = groupPermissionService.loadUserGroupPermissionInfoListAsync(tenantId, readablePermissions).get();
return applyPermissionInfo(permissionInfoList);
}
@@ -255,6 +248,32 @@ public class GroupPermissionController extends BaseController {
return groupPermissions;
}
+ private void checkGroupPermissionManageable(GroupPermission groupPermission) throws ThingsboardException {
+ if (groupPermission.isPublic()) {
+ throw permissionDenied();
+ }
+ checkRoleId(groupPermission.getRoleId(), Operation.READ);
+ if (groupPermission.getUserGroupId() != null && !groupPermission.getUserGroupId().isNullUid()) {
+ checkEntityGroupId(groupPermission.getUserGroupId(), Operation.WRITE);
+ }
+ if (groupPermission.getEntityGroupId() != null && !groupPermission.getEntityGroupId().isNullUid()) {
+ checkEntityGroupId(groupPermission.getEntityGroupId(), Operation.WRITE);
+ }
+ }
+
+ private boolean isReadableEntityGroup(GroupPermission groupPermission) {
+ EntityGroupId entityGroupId = groupPermission.getEntityGroupId();
+ if (entityGroupId == null || entityGroupId.isNullUid()) {
+ return true;
+ }
+ try {
+ EntityGroupInfo entityGroup = entityGroupService.findEntityGroupInfoByTenantIdAndId(getTenantId(), entityGroupId);
+ return entityGroup != null && accessControlService.hasEntityGroupInfoPermission(getCurrentUser(), Operation.READ, entityGroup);
+ } catch (ThingsboardException e) {
+ return false;
+ }
+ }
+
private boolean isAlreadyAssigned(TenantId tenantId, GroupPermission groupPermission) {
if (groupPermission.getEntityGroupId() != null) {
return groupPermissionService.findGroupPermissionByTenantIdAndEntityGroupIdAndUserGroupIdAndRoleId(tenantId,
diff --git a/application/src/main/java/org/thingsboard/server/controller/IotHubController.java b/application/src/main/java/org/thingsboard/server/controller/IotHubController.java
index b6d01d3342..5dc2a0ba9c 100644
--- a/application/src/main/java/org/thingsboard/server/controller/IotHubController.java
+++ b/application/src/main/java/org/thingsboard/server/controller/IotHubController.java
@@ -31,7 +31,6 @@ import java.util.Map;
import java.util.UUID;
import org.thingsboard.server.common.data.id.IotHubInstalledItemId;
import org.thingsboard.server.common.data.permission.Operation;
-import org.thingsboard.server.common.data.permission.Resource;
import org.thingsboard.server.dao.device.DeviceConnectivityHostSource;
import org.thingsboard.server.dao.device.DeviceConnectivityService;
import org.thingsboard.server.dao.iot_hub.IotHubInstalledItemService;
@@ -39,9 +38,9 @@ import org.thingsboard.server.queue.util.TbCoreComponent;
import org.thingsboard.server.service.security.system.ResolvedBaseUrl;
import org.thingsboard.server.service.security.system.SystemSecurityService;
import org.thingsboard.server.service.iot_hub.DevicePackageEntityState;
-import org.thingsboard.server.service.iot_hub.DevicePackageUpdateService;
-import org.thingsboard.server.service.iot_hub.DeviceUpdateRequest;
-import org.thingsboard.server.service.iot_hub.DeviceUpdateResult;
+import org.thingsboard.server.service.iot_hub.DevicePackageService;
+import org.thingsboard.server.service.iot_hub.DevicePackageRequest;
+import org.thingsboard.server.service.iot_hub.DevicePackageResult;
import org.thingsboard.server.service.iot_hub.InstalledItemKeptEntities;
import org.thingsboard.server.service.iot_hub.InstallItemVersionResult;
import org.thingsboard.server.service.iot_hub.InstallPlan;
@@ -58,7 +57,7 @@ import org.thingsboard.server.service.iot_hub.IotHubService;
public class IotHubController extends BaseController {
private final IotHubService iotHubService;
- private final DevicePackageUpdateService devicePackageUpdateService;
+ private final DevicePackageService devicePackageService;
private final IotHubInstalledItemService iotHubInstalledItemService;
private final DeviceConnectivityService deviceConnectivityService;
private final SystemSecurityService systemSecurityService;
@@ -103,21 +102,29 @@ public class IotHubController extends BaseController {
return iotHubService.registerDeviceInstall(getCurrentUser(), versionId, descriptor);
}
+ @PreAuthorize("hasAuthority('TENANT_ADMIN')")
+ @PostMapping("/device/install")
+ @ResponseBody
+ public DevicePackageResult installDevicePackage(@RequestBody DevicePackageRequest request) throws ThingsboardException {
+ checkAllPermissions();
+ return devicePackageService.install(getCurrentUser(), request);
+ }
+
@PreAuthorize("hasAuthority('TENANT_ADMIN')")
@GetMapping("/installedItems/{installedItemId}/deviceUpdate/check")
@ResponseBody
public List checkDeviceUpdate(@PathVariable UUID installedItemId) throws ThingsboardException {
checkAllPermissions();
- return devicePackageUpdateService.check(getCurrentUser(), new IotHubInstalledItemId(installedItemId));
+ return devicePackageService.check(getCurrentUser(), new IotHubInstalledItemId(installedItemId));
}
@PreAuthorize("hasAuthority('TENANT_ADMIN')")
@PostMapping("/installedItems/{installedItemId}/deviceUpdate")
@ResponseBody
- public DeviceUpdateResult updateDevicePackage(@PathVariable UUID installedItemId,
- @RequestBody DeviceUpdateRequest request) throws ThingsboardException {
+ public DevicePackageResult updateDevicePackage(@PathVariable UUID installedItemId,
+ @RequestBody DevicePackageRequest request) throws ThingsboardException {
checkAllPermissions();
- return devicePackageUpdateService.apply(getCurrentUser(), new IotHubInstalledItemId(installedItemId), request);
+ return devicePackageService.update(getCurrentUser(), new IotHubInstalledItemId(installedItemId), request);
}
@PreAuthorize("hasAuthority('TENANT_ADMIN')")
@@ -146,6 +153,25 @@ public class IotHubController extends BaseController {
return iotHubInstalledItemService.findByTenantId(getTenantId(), itemTypes, itemId, pageLink);
}
+ /**
+ * The installed items with an update in IoT Hub. The body is what the browser got from IoT Hub on Check for updates:
+ * the published version id by item id. A POST, as the map of a tenant with many items doesn't fit in a URL.
+ */
+ @PreAuthorize("hasAuthority('TENANT_ADMIN')")
+ @PostMapping("/installedItems/withUpdates")
+ @ResponseBody
+ public PageData getInstalledItemsWithUpdates(@RequestParam int pageSize,
+ @RequestParam int page,
+ @RequestParam(required = false) String textSearch,
+ @RequestParam(required = false) String sortProperty,
+ @RequestParam(required = false) String sortOrder,
+ @RequestParam(required = false) List itemTypes,
+ @RequestBody Map publishedVersionIds) throws ThingsboardException {
+ checkAllPermissions();
+ PageLink pageLink = createPageLink(pageSize, page, textSearch, sortProperty, sortOrder);
+ return iotHubInstalledItemService.findByTenantIdWithUpdates(getTenantId(), itemTypes, publishedVersionIds, pageLink);
+ }
+
@PreAuthorize("hasAuthority('TENANT_ADMIN')")
@GetMapping("/installedItems/count")
@ResponseBody
@@ -197,7 +223,7 @@ public class IotHubController extends BaseController {
}
private void checkAllPermissions() throws ThingsboardException {
- if (!getCurrentUser().getUserPermissions().hasGenericPermission(Resource.ALL, Operation.ALL)) {
+ if (!getCurrentUser().getUserPermissions().hasGenericPermissionExceptAi(Operation.ALL)) {
throw new ThingsboardException("You don't have permissions to use solution templates!",
ThingsboardErrorCode.PERMISSION_DENIED);
}
diff --git a/application/src/main/java/org/thingsboard/server/controller/NotificationController.java b/application/src/main/java/org/thingsboard/server/controller/NotificationController.java
index 75533b0e79..9d2781c3bc 100644
--- a/application/src/main/java/org/thingsboard/server/controller/NotificationController.java
+++ b/application/src/main/java/org/thingsboard/server/controller/NotificationController.java
@@ -22,6 +22,7 @@ import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.thingsboard.rule.engine.api.NotificationCenter;
import org.thingsboard.server.common.data.EntityType;
+import org.thingsboard.server.common.data.Tenant;
import org.thingsboard.server.common.data.User;
import org.thingsboard.server.common.data.exception.ThingsboardException;
import org.thingsboard.server.common.data.id.CustomerId;
@@ -38,6 +39,7 @@ import org.thingsboard.server.common.data.notification.NotificationRequestPrevie
import org.thingsboard.server.common.data.notification.NotificationType;
import org.thingsboard.server.common.data.notification.info.AddonAccessErrorNotificationInfo;
import org.thingsboard.server.common.data.notification.info.AddonAccessRequestNotificationInfo;
+import org.thingsboard.server.common.data.notification.info.AiCreditsLimitIncreaseRequestNotificationInfo;
import org.thingsboard.server.common.data.notification.info.EntitiesLimitIncreaseRequestNotificationInfo;
import org.thingsboard.server.common.data.notification.info.NotificationInfo;
import org.thingsboard.server.common.data.notification.info.PlanUpgradeRequestNotificationInfo;
@@ -72,15 +74,20 @@ import org.thingsboard.server.service.security.model.SecurityUser;
import org.thingsboard.server.service.security.system.SystemSecurityService;
import org.thingsboard.server.service.translation.TranslationService;
+import java.time.ZoneOffset;
+import java.time.ZonedDateTime;
+import java.time.temporal.ChronoUnit;
import java.util.Comparator;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
+import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.UUID;
+import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;
import static org.thingsboard.server.common.data.permission.Resource.NOTIFICATION;
@@ -114,6 +121,8 @@ public class NotificationController extends BaseController {
private final SystemSecurityService systemSecurityService;
private final SubscriptionService subscriptionService;
+ private final Map aiCreditsRequests = new ConcurrentHashMap<>();
+
@ApiOperation(value = "Get notifications (getNotifications)",
notes = "Returns the page of notifications for current user." + NEW_LINE +
PAGE_DATA_PARAMETERS +
@@ -274,6 +283,9 @@ public class NotificationController extends BaseController {
}
notificationRequest.setTenantId(user.getTenantId());
checkEntity(notificationRequest.getId(), notificationRequest, NOTIFICATION);
+ checkTemplateReportUser(notificationRequest.getTemplateId() != null ?
+ notificationTemplateService.findNotificationTemplateById(user.getTenantId(), notificationRequest.getTemplateId()) :
+ notificationRequest.getTemplate());
List targets = notificationRequest.getTargets().stream()
.map(NotificationTargetId::new)
.toList();
@@ -496,6 +508,53 @@ public class NotificationController extends BaseController {
}
}
+ @ApiOperation(value = "Send AI credits limit increase request notification to System administrators (sendAiCreditsLimitIncreaseRequest)",
+ notes = "Send AI credits limit increase request notification by Tenant Administrator to System administrators. " +
+ "TENANT asks for a higher monthly limit of the tenant, POOL for more AI credits for the whole installation. " +
+ "A request for the same limit is sent once a month." + TENANT_AUTHORITY_PARAGRAPH)
+ @PostMapping("/notification/aiCreditsLimitIncreaseRequest")
+ @PreAuthorize("hasAnyAuthority('TENANT_ADMIN')")
+ public void sendAiCreditsLimitIncreaseRequest(@Parameter(description = "Limit to increase", schema = @Schema(allowableValues = {"TENANT", "POOL"}))
+ @RequestParam(defaultValue = "TENANT") String limitType,
+ @AuthenticationPrincipal SecurityUser user,
+ HttpServletRequest request) throws Exception {
+ boolean pool = "POOL".equals(limitType);
+ if (!pool && !"TENANT".equals(limitType)) {
+ throw new IllegalArgumentException("Unsupported limit type: " + limitType);
+ }
+ long month = ZonedDateTime.now(ZoneOffset.UTC).truncatedTo(ChronoUnit.DAYS).withDayOfMonth(1).toInstant().toEpochMilli();
+ String requestKey = user.getTenantId().getId() + ":" + limitType;
+ if (Objects.equals(aiCreditsRequests.put(requestKey, month), month)) {
+ return;
+ }
+ try {
+ NotificationTarget sysAdmins = notificationTargetService.findNotificationTargetsByTenantIdAndUsersFilterType(TenantId.SYS_TENANT_ID, UsersFilterType.SYSTEM_ADMINISTRATORS)
+ .stream().findFirst()
+ .orElseThrow(() -> new IllegalArgumentException("Notification target for 'System administrators' not found"));
+ String baseUrl = systemSecurityService.getBaseUrl(TenantId.SYS_TENANT_ID, new CustomerId(EntityId.NULL_UUID), request);
+ Tenant tenant = tenantService.findTenantById(user.getTenantId());
+ String limitDescription;
+ if (pool) {
+ limitDescription = "all AI credits of this installation's license";
+ } else {
+ long limit = tenantProfileCache.get(user.getTenantId()).getDefaultProfileConfiguration().getMaxAiCredits();
+ limitDescription = String.format("its monthly limit of %,d AI credits", limit);
+ }
+ NotificationInfo info = AiCreditsLimitIncreaseRequestNotificationInfo.builder()
+ .userEmail(user.getEmail())
+ .tenantName(tenant != null ? tenant.getName() : user.getTenantId().toString())
+ .limitDescription(limitDescription)
+ .increaseLimitActionLabel(pool ? "Add credits" : "Set new limit")
+ .increaseLimitLink(pool ? "/license" : "/tenants/" + user.getTenantId())
+ .baseUrl(baseUrl)
+ .build();
+ notificationCenter.sendSystemNotification(TenantId.SYS_TENANT_ID, sysAdmins.getId(), NotificationType.AI_CREDITS_LIMIT_INCREASE_REQUEST, info);
+ } catch (Exception e) {
+ aiCreditsRequests.remove(requestKey, month);
+ throw e;
+ }
+ }
+
@ApiOperation(value = "Get notification request preview (getNotificationRequestPreview)",
notes = "Returns preview for notification request." + NEW_LINE +
"`processedTemplates` shows how the notifications for each delivery method will look like " +
diff --git a/application/src/main/java/org/thingsboard/server/controller/NotificationRuleController.java b/application/src/main/java/org/thingsboard/server/controller/NotificationRuleController.java
index 81194b517b..ae4f824aa2 100644
--- a/application/src/main/java/org/thingsboard/server/controller/NotificationRuleController.java
+++ b/application/src/main/java/org/thingsboard/server/controller/NotificationRuleController.java
@@ -20,17 +20,21 @@ import org.springframework.web.bind.annotation.RestController;
import org.thingsboard.server.common.data.EntityType;
import org.thingsboard.server.common.data.exception.ThingsboardException;
import org.thingsboard.server.common.data.id.NotificationRuleId;
+import org.thingsboard.server.common.data.id.NotificationTargetId;
import org.thingsboard.server.common.data.notification.rule.NotificationRule;
import org.thingsboard.server.common.data.notification.rule.NotificationRuleInfo;
import org.thingsboard.server.common.data.notification.rule.trigger.config.NotificationRuleTriggerType;
+import org.thingsboard.server.common.data.notification.template.NotificationTemplate;
import org.thingsboard.server.common.data.page.PageData;
import org.thingsboard.server.common.data.page.PageLink;
import org.thingsboard.server.common.data.permission.Operation;
import org.thingsboard.server.config.annotations.ApiOperation;
import org.thingsboard.server.dao.notification.NotificationRuleService;
+import org.thingsboard.server.dao.notification.NotificationTemplateService;
import org.thingsboard.server.queue.util.TbCoreComponent;
import org.thingsboard.server.service.security.model.SecurityUser;
+import java.util.List;
import java.util.UUID;
import static org.thingsboard.server.common.data.permission.Resource.NOTIFICATION;
@@ -52,6 +56,7 @@ import static org.thingsboard.server.controller.ControllerConstants.SYSTEM_OR_TE
public class NotificationRuleController extends BaseController {
private final NotificationRuleService notificationRuleService;
+ private final NotificationTemplateService notificationTemplateService;
@ApiOperation(value = "Save notification rule (saveNotificationRule)",
notes = "Creates or updates notification rule. " + NEW_LINE +
@@ -106,11 +111,23 @@ public class NotificationRuleController extends BaseController {
@AuthenticationPrincipal SecurityUser user) throws Exception {
notificationRule.setTenantId(user.getTenantId());
checkEntity(notificationRule.getId(), notificationRule, NOTIFICATION);
+ if (notificationRule.getTemplateId() != null) {
+ checkTemplateReportUser(notificationTemplateService.findNotificationTemplateById(user.getTenantId(), notificationRule.getTemplateId()));
+ }
NotificationRuleTriggerType triggerType = notificationRule.getTriggerType();
if ((user.isTenantAdmin() && !triggerType.isTenantLevel()) || (user.isSystemAdmin() && triggerType.isTenantLevel())) {
throw new IllegalArgumentException("Trigger type " + triggerType + " is not available");
}
+ NotificationTemplate template = notificationTemplateService.findNotificationTemplateById(user.getTenantId(), notificationRule.getTemplateId());
+ if (template == null || !(template.getTenantId().equals(user.getTenantId()) || template.getTenantId().isSysTenantId())) {
+ throw new IllegalArgumentException("Notification template not found");
+ }
+ for (List targets : notificationRule.getRecipientsConfig().getTargetsTable().values()) {
+ for (UUID targetId : targets) {
+ checkNotificationTargetId(new NotificationTargetId(targetId), Operation.READ);
+ }
+ }
return doSaveAndLog(EntityType.NOTIFICATION_RULE, notificationRule, notificationRuleService::saveNotificationRule);
}
diff --git a/application/src/main/java/org/thingsboard/server/controller/NotificationTemplateController.java b/application/src/main/java/org/thingsboard/server/controller/NotificationTemplateController.java
index 8f1ead6449..309fe60cb5 100644
--- a/application/src/main/java/org/thingsboard/server/controller/NotificationTemplateController.java
+++ b/application/src/main/java/org/thingsboard/server/controller/NotificationTemplateController.java
@@ -106,6 +106,7 @@ public class NotificationTemplateController extends BaseController {
public NotificationTemplate saveNotificationTemplate(@RequestBody @Valid NotificationTemplate notificationTemplate) throws Exception {
notificationTemplate.setTenantId(getTenantId());
checkEntity(notificationTemplate.getId(), notificationTemplate, NOTIFICATION);
+ checkTemplateReportUser(notificationTemplate);
return doSaveAndLog(EntityType.NOTIFICATION_TEMPLATE, notificationTemplate, notificationTemplateService::saveNotificationTemplate);
}
diff --git a/application/src/main/java/org/thingsboard/server/controller/ReportController.java b/application/src/main/java/org/thingsboard/server/controller/ReportController.java
index 12278a78d0..f7c9d4c3a3 100644
--- a/application/src/main/java/org/thingsboard/server/controller/ReportController.java
+++ b/application/src/main/java/org/thingsboard/server/controller/ReportController.java
@@ -248,9 +248,10 @@ public class ReportController extends BaseController {
public ResponseEntity testReportAndDownload(@RequestBody ReportRequest reportRequest) throws Exception {
checkFeatureAllowed(PlatformFeature.REPORTING);
SecurityUser currentUser = getCurrentUser();
- UserId userId = StringUtils.isNotEmpty(reportRequest.getUserId()) ? new UserId(UUID.fromString(reportRequest.getUserId())) : getCurrentUser().getId();
- EntityId userOwnerId = ownersCacheService.getOwner(currentUser.getTenantId(), userId);
+ UserId userId = StringUtils.isNotEmpty(reportRequest.getUserId()) ? new UserId(toUUID(reportRequest.getUserId())) : currentUser.getId();
+ checkReportUser(userId);
checkUserOwnerPermission(currentUser, userId);
+ EntityId userOwnerId = ownersCacheService.getOwner(currentUser.getTenantId(), userId);
AccessJwtToken accessToken = systemSecurityService.createUserAccessToken(currentUser.getTenantId(), userId);
ReportTemplateConfig configuration = reportRequest.getReportTemplateConfig();
if (configuration == null) {
@@ -301,7 +302,8 @@ public class ReportController extends BaseController {
SecurityUser currentUser = getCurrentUser();
UserId userId;
if (StringUtils.isNotEmpty(reportRequest.getUserId())) {
- userId = new UserId(UUID.fromString(reportRequest.getUserId()));
+ userId = new UserId(toUUID(reportRequest.getUserId()));
+ checkReportUser(userId);
checkUserOwnerPermission(currentUser, userId);
} else {
userId = currentUser.getId();
diff --git a/application/src/main/java/org/thingsboard/server/controller/RuleEngineController.java b/application/src/main/java/org/thingsboard/server/controller/RuleEngineController.java
index 2c662da1cb..e8608d1898 100644
--- a/application/src/main/java/org/thingsboard/server/controller/RuleEngineController.java
+++ b/application/src/main/java/org/thingsboard/server/controller/RuleEngineController.java
@@ -158,8 +158,7 @@ public class RuleEngineController extends BaseController {
} else {
entityId = EntityIdFactory.getByTypeAndId(entityType, entityIdStr);
}
- //Check that this is a valid JSON
- JacksonUtil.toJsonNode(requestBody);
+ checkMsgReportUser(JacksonUtil.toJsonNode(requestBody));
final DeferredResult response = new DeferredResult<>();
accessValidator.validate(currentUser, Operation.WRITE, entityId, new HttpValidationCallback(response, new FutureCallback>() {
@Override
diff --git a/application/src/main/java/org/thingsboard/server/controller/SchedulerEventController.java b/application/src/main/java/org/thingsboard/server/controller/SchedulerEventController.java
index 8cc02b2eb8..bb2624509d 100644
--- a/application/src/main/java/org/thingsboard/server/controller/SchedulerEventController.java
+++ b/application/src/main/java/org/thingsboard/server/controller/SchedulerEventController.java
@@ -2,6 +2,7 @@
// SPDX-License-Identifier: BUSL-1.1
package org.thingsboard.server.controller;
+import com.fasterxml.jackson.databind.node.ObjectNode;
import io.swagger.v3.oas.annotations.Hidden;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.media.ArraySchema;
@@ -21,7 +22,9 @@ import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;
import org.thingsboard.common.util.JacksonUtil;
+import org.thingsboard.server.common.data.StringUtils;
import org.thingsboard.server.common.data.edge.Edge;
+import org.thingsboard.server.common.data.exception.ThingsboardErrorCode;
import org.thingsboard.server.common.data.exception.ThingsboardException;
import org.thingsboard.server.common.data.id.CustomerId;
import org.thingsboard.server.common.data.id.EdgeId;
@@ -161,11 +164,26 @@ public class SchedulerEventController extends BaseController {
private void checkEventConfigPermissions(SchedulerEvent schedulerEvent) throws ThingsboardException {
if (GENERATE_REPORT.equals(schedulerEvent.getType())) {
SecurityUser currentUser = getCurrentUser();
- ReportConfig reportConfig = checkNotNull(JacksonUtil.treeToValue(schedulerEvent.getConfiguration(), ReportConfig.class),
- "Report scheduler event configuration should be specified!");
+ ReportConfig reportConfig = JacksonUtil.treeToValue(schedulerEvent.getConfiguration(), ReportConfig.class);
+ if (reportConfig == null) {
+ throw new ThingsboardException("Report scheduler event configuration should be specified!", ThingsboardErrorCode.BAD_REQUEST_PARAMS);
+ }
checkReportTemplateId(reportConfig.getReportTemplateId(), Operation.READ);
- UserId reportUserId = checkNotNull(reportConfig.getUserId(), "Report user must be specified!");
+ UserId reportUserId = reportConfig.getUserId();
+ if (reportUserId == null) {
+ throw new ThingsboardException("Report user must be specified!", ThingsboardErrorCode.BAD_REQUEST_PARAMS);
+ }
+ checkReportUser(reportUserId);
checkUserOwnerPermission(currentUser, reportUserId);
+ } else if (schedulerEvent.getConfiguration() != null) {
+ if (schedulerEvent.getConfiguration().path("msgBody").path("reportConfig") instanceof ObjectNode reportConfig
+ && reportConfig.path("useCurrentUserCredentials").asBoolean(false)
+ && reportConfig.path("userId").isTextual()
+ && StringUtils.isNotBlank(reportConfig.get("userId").asText())) {
+ UserId reportUserId = resolveReportUser(new UserId(toUUID(reportConfig.get("userId").asText())), true);
+ reportConfig.put("userId", reportUserId.toString());
+ }
+ checkMsgReportUser(schedulerEvent.getConfiguration().path("msgBody"));
}
}
diff --git a/application/src/main/java/org/thingsboard/server/controller/SelfRegistrationController.java b/application/src/main/java/org/thingsboard/server/controller/SelfRegistrationController.java
index 3122c978d1..945bb50108 100644
--- a/application/src/main/java/org/thingsboard/server/controller/SelfRegistrationController.java
+++ b/application/src/main/java/org/thingsboard/server/controller/SelfRegistrationController.java
@@ -64,6 +64,9 @@ public class SelfRegistrationController extends BaseController {
if (selfRegistrationParams.getNotificationRecipient() != null) {
checkNotificationTargetId(selfRegistrationParams.getNotificationRecipient(), Operation.READ);
}
+ if (selfRegistrationParams.getDomainId() != null) {
+ checkDomainId(selfRegistrationParams.getDomainId(), Operation.READ);
+ }
if (Authority.TENANT_ADMIN.equals(authority)) {
savedSelfRegistrationParams = whiteLabelingService.saveTenantSelfRegistrationParams(getTenantId(), selfRegistrationParams);
JsonNode privacyPolicyNode = whiteLabelingService.getTenantPrivacyPolicy(securityUser.getTenantId());
diff --git a/application/src/main/java/org/thingsboard/server/controller/SignUpController.java b/application/src/main/java/org/thingsboard/server/controller/SignUpController.java
index 305385a8e3..7a3cf1eec2 100644
--- a/application/src/main/java/org/thingsboard/server/controller/SignUpController.java
+++ b/application/src/main/java/org/thingsboard/server/controller/SignUpController.java
@@ -79,7 +79,6 @@ import org.thingsboard.server.service.security.model.SecurityUser;
import org.thingsboard.server.service.security.model.UserPrincipal;
import org.thingsboard.server.service.security.model.token.JwtTokenFactory;
import org.thingsboard.server.service.security.system.SystemSecurityService;
-import org.thingsboard.server.utils.MiscUtils;
import java.io.ByteArrayInputStream;
import java.io.IOException;
@@ -209,7 +208,7 @@ public class SignUpController extends BaseController {
UserCredentials savedUserCredentials = saveUserCredentials(savedUser, signUpRequest);
try {
- sendEmailVerification(tenantId, request, savedUserCredentials, email, null, signUpRequest.getPkgName(), signUpRequest.getPlatform());
+ sendEmailVerification(tenantId, request, savedUser, savedUserCredentials, email, signUpRequest.getPkgName(), signUpRequest.getPlatform());
} catch (ThingsboardException e) {
customerService.deleteCustomer(tenantId, savedCustomer.getId());
throw e;
@@ -227,11 +226,9 @@ public class SignUpController extends BaseController {
return SignUpResult.SUCCESS;
}
- private void sendEmailVerification(TenantId tenantId, HttpServletRequest request, UserCredentials userCredentials,
- String targetEmail, String baseUrl, String pkgName, PlatformType platformType) throws ThingsboardException {
- if (baseUrl == null) {
- baseUrl = MiscUtils.constructBaseUrl(request);
- }
+ private void sendEmailVerification(TenantId tenantId, HttpServletRequest request, User user, UserCredentials userCredentials,
+ String targetEmail, String pkgName, PlatformType platformType) throws ThingsboardException {
+ String baseUrl = systemSecurityService.getBaseUrl(user.getAuthority(), user.getTenantId(), user.getCustomerId(), request);
String activationLink = String.format("%s/api/noauth/activateEmail?emailCode=%s", baseUrl, userCredentials.getActivateToken());
if (!StringUtils.isEmpty(pkgName)) {
checkNotNull(platformType);
@@ -265,7 +262,7 @@ public class SignUpController extends BaseController {
}
@ApiOperation(value = "Resend Activation Email (resendEmailActivation)",
- notes = "Request to resend the activation email for the user. Checks that user was not activated yet.")
+ notes = "Request to resend the activation email for a user who signed up through this domain or mobile application and has not verified the email yet.")
@PostMapping(value = "/noauth/resendEmailActivation")
public void resendEmailActivation(
@Parameter(description = "Email of the user.", required = true, example = "john.doe@company.com")
@@ -285,19 +282,17 @@ public class SignUpController extends BaseController {
}
User existingUser = userService.findUserByEmail(TenantId.SYS_TENANT_ID, email);
- if (existingUser != null) {
- UserCredentials credentials = userService.findUserCredentialsByUserId(existingUser.getTenantId(), existingUser.getId());
- if (credentials.isEnabled()) {
- throw new DataValidationException("User with email '" + existingUser.getEmail() + "' "
- + " is already active!");
- } else {
- credentials = userService.checkUserActivationToken(tenantId, credentials);
- sendEmailVerification(tenantId, request, credentials, email, null, pkgName, platform);
- }
- } else {
+ if (existingUser == null || !tenantId.equals(existingUser.getTenantId())) {
throw new DataValidationException("User with email '" + email + "' "
+ " is not registered!");
}
+ UserCredentials credentials = userService.findUserCredentialsByUserId(tenantId, existingUser.getId());
+ if (credentials.isEnabled() || credentials.getActivateToken() == null || credentials.getPassword() == null) {
+ throw new DataValidationException("User with email '" + existingUser.getEmail() + "' "
+ + " is already active!");
+ }
+ credentials = userService.checkUserActivationToken(tenantId, credentials);
+ sendEmailVerification(tenantId, request, existingUser, credentials, email, pkgName, platform);
}
@ApiOperation(value = "Activate User using code from Email (activateEmail)",
@@ -395,16 +390,19 @@ public class SignUpController extends BaseController {
if (userCredentials.getPassword() == null) {
throw new ThingsboardException("Unable to activate user!", ThingsboardErrorCode.PERMISSION_DENIED);
}
+ User user = userService.findUserById(TenantId.SYS_TENANT_ID, userCredentials.getUserId());
+ if (user == null || !tenantId.equals(user.getTenantId())) {
+ throw new ThingsboardException("Invalid email code!", ThingsboardErrorCode.BAD_REQUEST_PARAMS);
+ }
String encodedPassword = userCredentials.getPassword();
UserCredentials credentials = userService.activateUserCredentials(TenantId.SYS_TENANT_ID, emailCode, encodedPassword);
- User user = userService.findUserById(TenantId.SYS_TENANT_ID, credentials.getUserId());
long acceptedTs = System.currentTimeMillis();
user.setPrivacyPolicyAccepted(acceptedTs);
user.setTermsOfUseAccepted(acceptedTs);
user = userService.saveUser(tenantId, user);
UserPrincipal principal = new UserPrincipal(UserPrincipal.Type.USER_NAME, user.getEmail());
SecurityUser securityUser = new SecurityUser(user, credentials.isEnabled(), principal, getMergedUserPermissions(user, false));
- String baseUrl = MiscUtils.constructBaseUrl(request);
+ String baseUrl = systemSecurityService.getBaseUrl(user.getAuthority(), user.getTenantId(), user.getCustomerId(), request);
String loginUrl;
if (!StringUtils.isEmpty(pkgName)) {
loginUrl = UriComponentsBuilder.fromUriString(baseUrl).path("/api/noauth/login")
@@ -574,10 +572,11 @@ public class SignUpController extends BaseController {
List permissions = selfRegistrationParams.getPermissions();
for (GroupPermission permission : permissions) {
+ permission.setId(null);
permission.setTenantId(tenantId);
permission.setUserGroupId(usersEntityGroup.getId());
if (permission.getEntityGroupId() != null) {
- EntityGroup entityGroup = entityGroupService.findEntityGroupById(tenantId, permission.getEntityGroupId());
+ EntityGroup entityGroup = entityGroupService.findEntityGroupInfoByTenantIdAndId(tenantId, permission.getEntityGroupId());
if (entityGroup != null) {
permission.setEntityGroupType(entityGroup.getType());
groupPermissionService.saveGroupPermission(tenantId, permission);
diff --git a/application/src/main/java/org/thingsboard/server/controller/UsageInfoController.java b/application/src/main/java/org/thingsboard/server/controller/UsageInfoController.java
index 7196fe5c92..2bf6be25da 100644
--- a/application/src/main/java/org/thingsboard/server/controller/UsageInfoController.java
+++ b/application/src/main/java/org/thingsboard/server/controller/UsageInfoController.java
@@ -12,7 +12,6 @@ import org.springframework.web.bind.annotation.RestController;
import org.thingsboard.server.common.data.UsageInfo;
import org.thingsboard.server.common.data.exception.ThingsboardException;
import org.thingsboard.server.common.data.permission.Operation;
-import org.thingsboard.server.common.data.permission.Resource;
import org.thingsboard.server.dao.usage.UsageInfoService;
import org.thingsboard.server.queue.util.TbCoreComponent;
@@ -30,7 +29,7 @@ public class UsageInfoController extends BaseController {
@PreAuthorize("hasAuthority('TENANT_ADMIN')")
@GetMapping(value = "/usage")
public UsageInfo getTenantUsageInfo() throws ThingsboardException {
- if (!getMergedUserPermissions(getCurrentUser(), false).hasGenericPermission(Resource.ALL, Operation.READ)) {
+ if (!getMergedUserPermissions(getCurrentUser(), false).hasGenericPermissionExceptAi(Operation.READ)) {
throw new ThingsboardException("You don't have permission to read UsageInfo!", PERMISSION_DENIED);
}
return checkNotNull(usageInfoService.getUsageInfo(getCurrentUser().getTenantId()));
diff --git a/application/src/main/java/org/thingsboard/server/controller/UserController.java b/application/src/main/java/org/thingsboard/server/controller/UserController.java
index e27dc20357..25dff3c9d4 100644
--- a/application/src/main/java/org/thingsboard/server/controller/UserController.java
+++ b/application/src/main/java/org/thingsboard/server/controller/UserController.java
@@ -292,7 +292,7 @@ public class UserController extends BaseController {
HttpServletRequest request) throws ThingsboardException {
SecurityUser securityUser = getCurrentUser();
User user = checkNotNull(userService.findUserByEmail(securityUser.getTenantId(), email));
- accessControlService.checkPermission(securityUser, Resource.USER, Operation.READ, user.getId(), user);
+ accessControlService.checkPermission(securityUser, Resource.USER, Operation.WRITE, user.getId(), user);
UserActivationLink activationLink = tbUserService.getActivationLink(securityUser.getTenantId(), securityUser.getCustomerId(), securityUser.getAuthority(), user.getId(), request);
try {
@@ -323,7 +323,7 @@ public class UserController extends BaseController {
HttpServletRequest request) throws ThingsboardException {
checkParameter(USER_ID, strUserId);
UserId userId = new UserId(toUUID(strUserId));
- checkUserId(userId, Operation.READ);
+ checkUserId(userId, Operation.WRITE);
SecurityUser securityUser = getCurrentUser();
return tbUserService.getActivationLink(securityUser.getTenantId(), securityUser.getCustomerId(), securityUser.getAuthority(), userId, request);
}
diff --git a/application/src/main/java/org/thingsboard/server/exception/AiCreditsExceededException.java b/application/src/main/java/org/thingsboard/server/exception/AiCreditsExceededException.java
new file mode 100644
index 0000000000..643def19d2
--- /dev/null
+++ b/application/src/main/java/org/thingsboard/server/exception/AiCreditsExceededException.java
@@ -0,0 +1,20 @@
+// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc.
+// SPDX-License-Identifier: BUSL-1.1
+package org.thingsboard.server.exception;
+
+import lombok.Getter;
+import org.thingsboard.server.common.data.exception.ThingsboardErrorCode;
+
+@Getter
+public class AiCreditsExceededException extends ThingsboardRuntimeException {
+
+ public static final String TENANT_LIMIT = "TENANT";
+
+ private final String limitType;
+
+ public AiCreditsExceededException(String limitType) {
+ super("Out of AI credits", ThingsboardErrorCode.TOO_MANY_REQUESTS);
+ this.limitType = limitType;
+ }
+
+}
diff --git a/application/src/main/java/org/thingsboard/server/exception/ThingsboardAiCreditsExceededResponse.java b/application/src/main/java/org/thingsboard/server/exception/ThingsboardAiCreditsExceededResponse.java
new file mode 100644
index 0000000000..19996a2c73
--- /dev/null
+++ b/application/src/main/java/org/thingsboard/server/exception/ThingsboardAiCreditsExceededResponse.java
@@ -0,0 +1,28 @@
+// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc.
+// SPDX-License-Identifier: BUSL-1.1
+package org.thingsboard.server.exception;
+
+import io.swagger.v3.oas.annotations.media.Schema;
+import org.springframework.http.HttpStatus;
+import org.thingsboard.server.common.data.exception.ThingsboardErrorCode;
+
+@Schema
+public class ThingsboardAiCreditsExceededResponse extends ThingsboardErrorResponse {
+
+ private final String aiCreditsLimit;
+
+ protected ThingsboardAiCreditsExceededResponse(String message, String aiCreditsLimit) {
+ super(message, ThingsboardErrorCode.TOO_MANY_REQUESTS, HttpStatus.TOO_MANY_REQUESTS);
+ this.aiCreditsLimit = aiCreditsLimit;
+ }
+
+ public static ThingsboardAiCreditsExceededResponse of(String message, String aiCreditsLimit) {
+ return new ThingsboardAiCreditsExceededResponse(message, aiCreditsLimit);
+ }
+
+ @Schema(description = "Which AI credits limit is used up: TENANT for the tenant's monthly limit", accessMode = Schema.AccessMode.READ_ONLY)
+ public String getAiCreditsLimit() {
+ return aiCreditsLimit;
+ }
+
+}
diff --git a/application/src/main/java/org/thingsboard/server/exception/ThingsboardErrorResponseHandler.java b/application/src/main/java/org/thingsboard/server/exception/ThingsboardErrorResponseHandler.java
index a522c03652..4923bbb451 100644
--- a/application/src/main/java/org/thingsboard/server/exception/ThingsboardErrorResponseHandler.java
+++ b/application/src/main/java/org/thingsboard/server/exception/ThingsboardErrorResponseHandler.java
@@ -12,7 +12,7 @@ import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.hibernate.exception.ConstraintViolationException;
-import org.springframework.boot.web.servlet.error.ErrorController;
+import org.springframework.boot.webmvc.error.ErrorController;
import org.springframework.dao.DataAccessException;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
@@ -93,6 +93,7 @@ public class ThingsboardErrorResponseHandler extends ResponseEntityExceptionHand
errorCodeToStatusMap.put(ThingsboardErrorCode.ENTITIES_LIMIT_EXCEEDED, HttpStatus.FORBIDDEN);
errorCodeToStatusMap.put(ThingsboardErrorCode.VERSION_CONFLICT, HttpStatus.CONFLICT);
errorCodeToStatusMap.put(ThingsboardErrorCode.SETUP_INCOMPLETE, HttpStatus.LOCKED);
+ errorCodeToStatusMap.put(ThingsboardErrorCode.SERVICE_UNAVAILABLE, HttpStatus.SERVICE_UNAVAILABLE);
}
private static ThingsboardErrorCode statusToErrorCode(HttpStatus status) {
@@ -198,6 +199,12 @@ public class ThingsboardErrorResponseHandler extends ResponseEntityExceptionHand
}
private void handleThingsboardRuntimeException(ThingsboardRuntimeException thingsboardRuntimeException, HttpServletResponse response) throws IOException {
+ if (thingsboardRuntimeException instanceof AiCreditsExceededException aiCreditsExceeded) {
+ response.setStatus(HttpStatus.TOO_MANY_REQUESTS.value());
+ JacksonUtil.writeValue(response.getWriter(),
+ ThingsboardAiCreditsExceededResponse.of(aiCreditsExceeded.getMessage(), aiCreditsExceeded.getLimitType()));
+ return;
+ }
ThingsboardErrorCode errorCode = thingsboardRuntimeException.getErrorCode();
HttpStatus status = errorCodeToStatus(errorCode);
response.setStatus(status.value());
diff --git a/application/src/main/java/org/thingsboard/server/install/ThingsboardInstallService.java b/application/src/main/java/org/thingsboard/server/install/ThingsboardInstallService.java
index 07d14417bd..5a5d08f6c7 100644
--- a/application/src/main/java/org/thingsboard/server/install/ThingsboardInstallService.java
+++ b/application/src/main/java/org/thingsboard/server/install/ThingsboardInstallService.java
@@ -226,7 +226,7 @@ public class ThingsboardInstallService {
} catch (EntityCapExceededException e) {
// A deliberate pre-flight refusal: report the plain policy message, not an unexpected failure.
throw new ThingsboardInstallException(e.getMessage(), e);
- } catch (Exception e) {
+ } catch (Throwable e) {
log.error("Unexpected error during ThingsBoard installation!", e);
throw new ThingsboardInstallException("Unexpected error during ThingsBoard installation!", e);
} finally {
diff --git a/application/src/main/java/org/thingsboard/server/service/ai/DefaultTbAiService.java b/application/src/main/java/org/thingsboard/server/service/ai/DefaultTbAiService.java
index f3b60383eb..174fe9cb85 100644
--- a/application/src/main/java/org/thingsboard/server/service/ai/DefaultTbAiService.java
+++ b/application/src/main/java/org/thingsboard/server/service/ai/DefaultTbAiService.java
@@ -17,6 +17,7 @@ import org.thingsboard.server.common.data.ApiUsageRecordKey;
import org.thingsboard.server.common.data.User;
import org.thingsboard.server.common.data.exception.ThingsboardErrorCode;
import org.thingsboard.server.common.stats.TbApiUsageReportClient;
+import org.thingsboard.server.exception.AiCreditsExceededException;
import org.thingsboard.server.exception.ThingsboardRuntimeException;
import org.thingsboard.server.queue.util.TbCoreComponent;
import org.thingsboard.server.service.ai.transport.TbAiChannelRejectedException;
@@ -152,9 +153,9 @@ class DefaultTbAiService implements TbAiService {
private static String toUserFriendlyMessage(Throwable e) {
if (e instanceof TimeoutException) {
- return "Request timed out";
+ return TbAiOperations.TIMED_OUT_MESSAGE;
} else if (e instanceof TbAiChannelUnavailableException) {
- return "Service unavailable";
+ return TbAiOperations.UNAVAILABLE_MESSAGE;
} else if (e instanceof TbAiChannelRejectedException || e instanceof ThingsboardRuntimeException) {
return e.getMessage();
}
@@ -176,13 +177,15 @@ class DefaultTbAiService implements TbAiService {
case 404 -> ThingsboardErrorCode.ITEM_NOT_FOUND;
case 409 -> ThingsboardErrorCode.VERSION_CONFLICT;
case 429 -> ThingsboardErrorCode.TOO_MANY_REQUESTS;
+ case 401, 403 -> ThingsboardErrorCode.PERMISSION_DENIED;
+ case 502, 503, 504 -> ThingsboardErrorCode.SERVICE_UNAVAILABLE;
default -> ThingsboardErrorCode.GENERAL;
};
}
private void checkApiUsage(SecurityUser user) {
if (!apiUsageStateService.getApiUsageState(user.getTenantId()).isAiEnabled()) {
- throw new ThingsboardRuntimeException("Out of AI credits", ThingsboardErrorCode.TOO_MANY_REQUESTS);
+ throw new AiCreditsExceededException(AiCreditsExceededException.TENANT_LIMIT);
}
}
diff --git a/application/src/main/java/org/thingsboard/server/service/ai/chat/AiChatService.java b/application/src/main/java/org/thingsboard/server/service/ai/chat/AiChatService.java
index 2eae20227a..c355f38b05 100644
--- a/application/src/main/java/org/thingsboard/server/service/ai/chat/AiChatService.java
+++ b/application/src/main/java/org/thingsboard/server/service/ai/chat/AiChatService.java
@@ -15,8 +15,12 @@ public interface AiChatService {
void updateChat(UUID chatId, JsonNode request, SecurityUser user);
+ void stopChat(UUID chatId, SecurityUser user);
+
JsonNode listChats(SecurityUser user);
+ JsonNode listChatStatuses(SecurityUser user);
+
JsonNode getChatMessages(UUID chatId, SecurityUser user);
void deleteChat(UUID chatId, SecurityUser user);
diff --git a/application/src/main/java/org/thingsboard/server/service/ai/chat/DefaultAiChatService.java b/application/src/main/java/org/thingsboard/server/service/ai/chat/DefaultAiChatService.java
index 1b15fc8045..0fff311678 100644
--- a/application/src/main/java/org/thingsboard/server/service/ai/chat/DefaultAiChatService.java
+++ b/application/src/main/java/org/thingsboard/server/service/ai/chat/DefaultAiChatService.java
@@ -9,6 +9,8 @@ import org.springframework.stereotype.Service;
import org.thingsboard.ai.common.channel.ChannelProtocol;
import org.thingsboard.ai.common.channel.ChatOperationRequest;
import org.thingsboard.common.util.JacksonUtil;
+import org.thingsboard.server.cache.limits.RateLimitService;
+import org.thingsboard.server.common.data.limit.LimitedApi;
import org.thingsboard.server.queue.util.TbCoreComponent;
import org.thingsboard.server.service.ai.TbAiService;
import org.thingsboard.server.service.ai.transport.TbAiOperation;
@@ -27,15 +29,17 @@ import java.util.UUID;
class DefaultAiChatService implements AiChatService {
private static final JsonNode TOOL_CARDS = JacksonUtil.newObjectNode().put("toolCards", true);
+ static final String RATE_LIMITED = "RATE_LIMITED";
private final TbAiService tbAiService;
private final TbAiTransport tbAiTransport;
private final TbAiOperations operations;
+ private final RateLimitService rateLimitService;
@Override
public JsonNode createChat(JsonNode request, SecurityUser user) {
return tbAiService.process(tokenProvider -> operations.execute(
- new TbAiOperation(ChannelProtocol.CHAT_CREATE, new ChatOperationRequest(null, request)), user, tokenProvider), user, false);
+ new TbAiOperation(ChannelProtocol.CHAT_CREATE, new ChatOperationRequest(null, request)), user, tokenProvider), user, true);
}
@Override
@@ -50,12 +54,24 @@ class DefaultAiChatService implements AiChatService {
new TbAiOperation(ChannelProtocol.CHAT_LIST, null), user, tokenProvider), user, false);
}
+ @Override
+ public JsonNode listChatStatuses(SecurityUser user) {
+ return tbAiService.process(tokenProvider -> operations.execute(
+ new TbAiOperation(ChannelProtocol.CHAT_STATUS, null), user, tokenProvider), user, false);
+ }
+
@Override
public JsonNode getChatMessages(UUID chatId, SecurityUser user) {
return tbAiService.process(tokenProvider -> operations.execute(
new TbAiOperation(ChannelProtocol.CHAT_MESSAGES, new ChatOperationRequest(chatId, TOOL_CARDS)), user, tokenProvider), user, false);
}
+ @Override
+ public void stopChat(UUID chatId, SecurityUser user) {
+ tbAiService.process(tokenProvider -> operations.execute(
+ new TbAiOperation(ChannelProtocol.CHAT_STOP, new ChatOperationRequest(chatId, null)), user, tokenProvider), user, false);
+ }
+
@Override
public void deleteChat(UUID chatId, SecurityUser user) {
tbAiService.process(tokenProvider -> operations.execute(
@@ -67,6 +83,14 @@ class DefaultAiChatService implements AiChatService {
UUID chatId, JsonNode request, String tbAccessToken, String acceptLanguage, String clientOrigin,
SecurityUser user
) {
+ if (!rateLimitService.checkRateLimit(LimitedApi.AI_CHAT_REQUESTS, user.getTenantId())) {
+ return Flux.just(ServerSentEvent.builder()
+ .event("error")
+ .data(JacksonUtil.toString(JacksonUtil.newObjectNode()
+ .put("message", "Rate limit exceeded")
+ .put("code", RATE_LIMITED)))
+ .build());
+ }
var link = new TbAiTurnLink();
return tbAiService.processStream(chatId, tokenProvider -> {
var context = new TbAiTurnContext(user, tbAccessToken, acceptLanguage, tokenProvider, clientOrigin);
diff --git a/application/src/main/java/org/thingsboard/server/service/ai/solution/AiSolutionService.java b/application/src/main/java/org/thingsboard/server/service/ai/solution/AiSolutionService.java
index b0f7763131..5e5582df98 100644
--- a/application/src/main/java/org/thingsboard/server/service/ai/solution/AiSolutionService.java
+++ b/application/src/main/java/org/thingsboard/server/service/ai/solution/AiSolutionService.java
@@ -25,10 +25,16 @@ public interface AiSolutionService {
void clearStep(UUID solutionId, SolutionStep step, SecurityUser user);
+ JsonNode stopSolution(UUID solutionId, SecurityUser user);
+
JsonNode installSolution(UUID solutionId, String tbAccessToken, String clientOrigin, SecurityUser user);
JsonNode uninstallSolution(UUID solutionId, String tbAccessToken, String clientOrigin, SecurityUser user);
void deleteSolution(UUID solutionId, SecurityUser user);
+ void updateSolution(UUID solutionId, JsonNode request, SecurityUser user);
+
+ JsonNode getInstallProgress(UUID solutionId, SecurityUser user);
+
}
diff --git a/application/src/main/java/org/thingsboard/server/service/ai/solution/DefaultAiSolutionService.java b/application/src/main/java/org/thingsboard/server/service/ai/solution/DefaultAiSolutionService.java
index c110699cbd..91d8297daa 100644
--- a/application/src/main/java/org/thingsboard/server/service/ai/solution/DefaultAiSolutionService.java
+++ b/application/src/main/java/org/thingsboard/server/service/ai/solution/DefaultAiSolutionService.java
@@ -10,12 +10,15 @@ import org.thingsboard.ai.common.data.solution.SolutionStep;
import org.thingsboard.server.common.data.exception.ThingsboardErrorCode;
import org.thingsboard.server.exception.ThingsboardRuntimeException;
import org.thingsboard.server.common.data.util.CollectionsUtil;
+import org.thingsboard.server.cache.limits.RateLimitService;
+import org.thingsboard.server.common.data.limit.LimitedApi;
import org.thingsboard.server.queue.util.TbCoreComponent;
import org.thingsboard.ai.common.channel.ChannelProtocol;
import org.thingsboard.ai.common.channel.SolutionChatRequest;
import org.thingsboard.ai.common.channel.SolutionDataRequest;
import org.thingsboard.ai.common.channel.SolutionOperationRequest;
import org.thingsboard.ai.common.channel.SolutionStepRequest;
+import org.thingsboard.ai.common.channel.SolutionUpdateRequest;
import org.thingsboard.server.service.ai.TbAiService;
import org.thingsboard.server.service.ai.transport.TbAiOperation;
import org.thingsboard.server.service.ai.transport.TbAiOperations;
@@ -32,11 +35,12 @@ public class DefaultAiSolutionService implements AiSolutionService {
private final TbAiService tbAiService;
private final TbAiOperations operations;
+ private final RateLimitService rateLimitService;
@Override
public JsonNode startNew(SecurityUser user) {
return tbAiService.process(tokenProvider -> operations.execute(
- new TbAiOperation(ChannelProtocol.SOLUTION_START, null), user, tokenProvider), user, false);
+ new TbAiOperation(ChannelProtocol.SOLUTION_START, null), user, tokenProvider), user);
}
@Override
@@ -58,6 +62,9 @@ public class DefaultAiSolutionService implements AiSolutionService {
if (StringUtils.isBlank(text) && attached == null) {
throw new ThingsboardRuntimeException("Message cannot be blank", ThingsboardErrorCode.BAD_REQUEST_PARAMS);
}
+ if (!rateLimitService.checkRateLimit(LimitedApi.AI_CHAT_REQUESTS, user.getTenantId())) {
+ throw new ThingsboardRuntimeException("Rate limit exceeded", ThingsboardErrorCode.TOO_MANY_REQUESTS);
+ }
return tbAiService.process(tokenProvider -> operations.execute(
new TbAiOperation(ChannelProtocol.SOLUTION_CHAT, new SolutionChatRequest(solutionId, step, text, attached)), user, tokenProvider), user);
}
@@ -80,6 +87,12 @@ public class DefaultAiSolutionService implements AiSolutionService {
new TbAiOperation(ChannelProtocol.SOLUTION_STEP_CLEAR, new SolutionStepRequest(solutionId, step)), user, tokenProvider), user, false);
}
+ @Override
+ public JsonNode stopSolution(UUID solutionId, SecurityUser user) {
+ return tbAiService.process(tokenProvider -> operations.execute(
+ new TbAiOperation(ChannelProtocol.SOLUTION_STOP, new SolutionOperationRequest(solutionId)), user, tokenProvider), user, false);
+ }
+
@Override
public JsonNode installSolution(UUID solutionId, String tbAccessToken, String clientOrigin, SecurityUser user) {
return tbAiService.process(tokenProvider -> operations.execute(
@@ -100,4 +113,16 @@ public class DefaultAiSolutionService implements AiSolutionService {
new TbAiOperation(ChannelProtocol.SOLUTION_DELETE, new SolutionOperationRequest(solutionId)), user, tokenProvider), user, false);
}
+ @Override
+ public void updateSolution(UUID solutionId, JsonNode request, SecurityUser user) {
+ tbAiService.process(tokenProvider -> operations.execute(
+ new TbAiOperation(ChannelProtocol.SOLUTION_UPDATE, new SolutionUpdateRequest(solutionId, request)), user, tokenProvider), user, false);
+ }
+
+ @Override
+ public JsonNode getInstallProgress(UUID solutionId, SecurityUser user) {
+ return tbAiService.process(tokenProvider -> operations.execute(
+ new TbAiOperation(ChannelProtocol.SOLUTION_PROGRESS, new SolutionOperationRequest(solutionId)), user, tokenProvider), user, false);
+ }
+
}
diff --git a/application/src/main/java/org/thingsboard/server/service/ai/transport/ChannelTbAiOperations.java b/application/src/main/java/org/thingsboard/server/service/ai/transport/ChannelTbAiOperations.java
index 5d6b1c4846..f336bc1c4a 100644
--- a/application/src/main/java/org/thingsboard/server/service/ai/transport/ChannelTbAiOperations.java
+++ b/application/src/main/java/org/thingsboard/server/service/ai/transport/ChannelTbAiOperations.java
@@ -52,7 +52,7 @@ class ChannelTbAiOperations {
} catch (NotStartedException e) {
if (attempt >= 2) {
log.warn("AI channel operation '{}' was refused twice: {}", operation.type(), e.getMessage());
- return failure("Service unavailable");
+ return failure(HttpStatus.SERVICE_UNAVAILABLE, TbAiOperations.UNAVAILABLE_MESSAGE);
}
log.debug("AI channel operation '{}' was not started ({}), retrying on a new channel", operation.type(), e.getMessage());
fresh = true;
@@ -76,8 +76,8 @@ class ChannelTbAiOperations {
}
}
- static TbAiResponse failure(String message) {
- return TbAiResponse.builder().success(false).error(message).build();
+ static TbAiResponse failure(HttpStatus status, String message) {
+ return TbAiResponse.builder().success(false).status(status.value()).error(message).build();
}
static TbAiResponse toResponse(OperationResult result) {
@@ -136,15 +136,15 @@ class ChannelTbAiOperations {
return result.get(OPERATION_TIMEOUT.toMillis(), TimeUnit.MILLISECONDS);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
- return failure("Request interrupted");
+ return failure(HttpStatus.SERVICE_UNAVAILABLE, "Request interrupted");
} catch (TimeoutException e) {
- return failure("Request timed out");
+ return failure(HttpStatus.GATEWAY_TIMEOUT, TbAiOperations.TIMED_OUT_MESSAGE);
} catch (ExecutionException e) {
if (e.getCause() instanceof NotStartedException notStarted) {
throw notStarted;
}
log.warn("AI channel operation '{}' failed: {}", operation.type(), ExceptionUtils.getRootCauseMessage(e));
- return failure("Service unavailable");
+ return failure(HttpStatus.SERVICE_UNAVAILABLE, TbAiOperations.UNAVAILABLE_MESSAGE);
} finally {
finish();
}
diff --git a/application/src/main/java/org/thingsboard/server/service/ai/transport/ChannelTbAiTransport.java b/application/src/main/java/org/thingsboard/server/service/ai/transport/ChannelTbAiTransport.java
index c8e49e4797..9cedb4a509 100644
--- a/application/src/main/java/org/thingsboard/server/service/ai/transport/ChannelTbAiTransport.java
+++ b/application/src/main/java/org/thingsboard/server/service/ai/transport/ChannelTbAiTransport.java
@@ -25,7 +25,7 @@ import java.util.concurrent.atomic.AtomicBoolean;
/**
* Runs a chat turn on a pooled channel and re-emits its events as SSE. A turn the channel did not start (refused, or
* closed with 1001 before any frame for it) is retried once on a new channel; a channel that cannot be opened fails
- * the turn with "Service unavailable".
+ * the turn with {@link TbAiOperations#UNAVAILABLE_MESSAGE}.
*/
@Slf4j
@Component
@@ -166,7 +166,7 @@ class ChannelTbAiTransport implements TbAiTransport {
end(null);
} else {
log.warn("[{}] AI channel closed during the turn [{}] {}", chatId, code, reason);
- end(errorEvent("Service unavailable"));
+ end(errorEvent(TbAiOperations.UNAVAILABLE_MESSAGE));
}
}
diff --git a/application/src/main/java/org/thingsboard/server/service/ai/transport/TbAiChannelPool.java b/application/src/main/java/org/thingsboard/server/service/ai/transport/TbAiChannelPool.java
index 9cb93f24d1..a5875c01df 100644
--- a/application/src/main/java/org/thingsboard/server/service/ai/transport/TbAiChannelPool.java
+++ b/application/src/main/java/org/thingsboard/server/service/ai/transport/TbAiChannelPool.java
@@ -2,6 +2,8 @@
// SPDX-License-Identifier: BUSL-1.1
package org.thingsboard.server.service.ai.transport;
+import com.auth0.jwt.JWT;
+import com.auth0.jwt.exceptions.JWTDecodeException;
import io.netty.handler.codec.http.websocketx.WebSocketClientHandshakeException;
import jakarta.annotation.PreDestroy;
import lombok.extern.slf4j.Slf4j;
@@ -13,6 +15,7 @@ import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.thingsboard.ai.common.channel.ChannelProtocol;
import org.thingsboard.ai.common.channel.TbAiChannelClient;
+import org.thingsboard.ai.common.client.TbAiClaims;
import org.thingsboard.ai.common.client.TbAiClient;
import org.thingsboard.ai.common.client.TbAiHeaders;
import org.thingsboard.common.util.ThingsBoardThreadFactory;
@@ -120,11 +123,17 @@ class TbAiChannelPool {
PoolKey key = new PoolKey(context.tenantId(), context.userId());
CompletableFuture pending = null;
if (!fresh) {
+ String limits = limitsOf(currentToken(context));
Group group = groups.computeIfAbsent(key, k -> new Group());
synchronized (group) {
long now = nanoClock.getAsLong();
for (int i = group.connections.size() - 1; i >= 0; i--) {
TbAiPooledConnection connection = group.connections.get(i);
+ if (connection.isStaleFor(limits)) {
+ log.debug("[{}] Retiring an AI channel opened with other limits", key);
+ connection.retire();
+ continue;
+ }
if (connection.tryReserve(now)) {
return CompletableFuture.completedFuture(connection);
}
@@ -185,7 +194,9 @@ class TbAiChannelPool {
private CompletableFuture connect(TbAiTurnContext context, PoolKey key, boolean pooled) {
var connection = new TbAiPooledConnection(key, context.clientOrigin(), pooled,
maxOperationsPerConnection, channelClient.codec(), this, nanoClock.getAsLong());
- channelClient.connect(handshakeTokenProvider(context), connection)
+ String token = currentToken(context);
+ connection.handshakeLimits(limitsOf(token));
+ channelClient.connect(handshakeTokenProvider(context, token), connection)
.subscribeOn(Schedulers.boundedElastic())
.subscribe(connection::opened, error -> connection.failed(toConnectError(error)));
return connection.ready()
@@ -298,13 +309,32 @@ class TbAiChannelPool {
return true;
}
- private TbAiClient.TokenProvider handshakeTokenProvider(TbAiTurnContext context) {
+ private static String currentToken(TbAiTurnContext context) {
+ try {
+ return context.tokenProvider() != null ? context.tokenProvider().getToken() : null;
+ } catch (RuntimeException e) {
+ return null;
+ }
+ }
+
+ static String limitsOf(String token) {
+ if (token == null) {
+ return null;
+ }
+ try {
+ return JWT.decode(token).getClaim(TbAiClaims.PROFILE_CONFIG).asString();
+ } catch (JWTDecodeException e) {
+ return null;
+ }
+ }
+
+ private TbAiClient.TokenProvider handshakeTokenProvider(TbAiTurnContext context, String token) {
TbAiClient.TokenProvider delegate = context.tokenProvider();
String acceptLanguage = context.acceptLanguage();
return new TbAiClient.TokenProvider() {
@Override
public String getToken() {
- return delegate.getToken();
+ return token != null ? token : delegate.getToken();
}
@Override
@@ -324,7 +354,7 @@ class TbAiChannelPool {
if (cause instanceof WebSocketClientHandshakeException handshake && handshake.response() != null) {
int status = handshake.response().status().code();
if (status == HttpStatus.UNAUTHORIZED.value() || status == HttpStatus.FORBIDDEN.value()) {
- return new TbAiChannelRejectedException(HttpStatus.valueOf(status).getReasonPhrase());
+ return new TbAiChannelRejectedException(HttpStatus.valueOf(status));
}
}
if (cause instanceof TbAiChannelRejectedException || cause instanceof TbAiChannelUnavailableException) {
diff --git a/application/src/main/java/org/thingsboard/server/service/ai/transport/TbAiChannelRejectedException.java b/application/src/main/java/org/thingsboard/server/service/ai/transport/TbAiChannelRejectedException.java
index b0dc2324a7..2b63861a53 100644
--- a/application/src/main/java/org/thingsboard/server/service/ai/transport/TbAiChannelRejectedException.java
+++ b/application/src/main/java/org/thingsboard/server/service/ai/transport/TbAiChannelRejectedException.java
@@ -2,13 +2,20 @@
// SPDX-License-Identifier: BUSL-1.1
package org.thingsboard.server.service.ai.transport;
+import lombok.Getter;
+import org.springframework.http.HttpStatus;
+
/**
* TB AI refused the channel handshake with 401 or 403; the reason phrase is shown to the user.
*/
+@Getter
public class TbAiChannelRejectedException extends RuntimeException {
- public TbAiChannelRejectedException(String reason) {
- super(reason);
+ private final HttpStatus status;
+
+ public TbAiChannelRejectedException(HttpStatus status) {
+ super(status.getReasonPhrase());
+ this.status = status;
}
}
diff --git a/application/src/main/java/org/thingsboard/server/service/ai/transport/TbAiOperations.java b/application/src/main/java/org/thingsboard/server/service/ai/transport/TbAiOperations.java
index 32052870c1..80fa6a1e23 100644
--- a/application/src/main/java/org/thingsboard/server/service/ai/transport/TbAiOperations.java
+++ b/application/src/main/java/org/thingsboard/server/service/ai/transport/TbAiOperations.java
@@ -4,6 +4,7 @@ package org.thingsboard.server.service.ai.transport;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
+import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.thingsboard.ai.common.client.TbAiClient;
import org.thingsboard.ai.common.client.TbAiClient.TbAiResponse;
@@ -17,6 +18,9 @@ import org.thingsboard.server.service.security.system.SystemSecurityService;
@RequiredArgsConstructor
public class TbAiOperations {
+ public static final String UNAVAILABLE_MESSAGE = "The AI service is unavailable. Try again.";
+ public static final String TIMED_OUT_MESSAGE = "The AI service did not answer in time. Try again.";
+
private final ChannelTbAiOperations channelOperations;
private final SystemSecurityService systemSecurityService;
@@ -33,9 +37,9 @@ public class TbAiOperations {
return channelOperations.execute(operation, context);
} catch (TbAiChannelUnavailableException e) {
log.warn("[{}][{}] AI channel unavailable for '{}': {}", context.tenantId(), context.userId(), operation.type(), e.getMessage());
- return ChannelTbAiOperations.failure("Service unavailable");
+ return ChannelTbAiOperations.failure(HttpStatus.SERVICE_UNAVAILABLE, UNAVAILABLE_MESSAGE);
} catch (TbAiChannelRejectedException e) {
- return ChannelTbAiOperations.failure(e.getMessage());
+ return ChannelTbAiOperations.failure(e.getStatus(), e.getMessage());
}
}
diff --git a/application/src/main/java/org/thingsboard/server/service/ai/transport/TbAiPooledConnection.java b/application/src/main/java/org/thingsboard/server/service/ai/transport/TbAiPooledConnection.java
index 3b77aad205..b5f0b606d1 100644
--- a/application/src/main/java/org/thingsboard/server/service/ai/transport/TbAiPooledConnection.java
+++ b/application/src/main/java/org/thingsboard/server/service/ai/transport/TbAiPooledConnection.java
@@ -32,7 +32,7 @@ final class TbAiPooledConnection implements ChannelFrameListener {
// Protocol version 1 is the baseline. A later feature that this ThingsBoard handles goes here, so TB AI can tell
// before using it that this ThingsBoard understands it.
- static final List CLIENT_CAPABILITIES = List.of();
+ static final List CLIENT_CAPABILITIES = List.of(ChannelProtocol.CHAT_KIT_CAPABILITY);
private final TbAiChannelPool.PoolKey key;
private final String origin;
@@ -54,6 +54,7 @@ final class TbAiPooledConnection implements ChannelFrameListener {
private volatile ChannelSession session;
private volatile int maxFrameBytes = TbAiChannelClient.DEFAULT_MAX_FRAME_BYTES;
private volatile List serverCapabilities = List.of();
+ private volatile String handshakeLimits;
/**
* Created with one reservation for the caller that opens it, so callers waiting on the same handshake cannot
@@ -198,6 +199,20 @@ final class TbAiPooledConnection implements ChannelFrameListener {
}
}
+ void handshakeLimits(String limits) {
+ this.handshakeLimits = limits;
+ }
+
+ /**
+ * True when the channel shook hands with other limits than the caller's current token carries (the tenant
+ * profile's rate limits among them): its view of the user is out of date, so it should take no new work. Claims
+ * that change on every signing, such as the client address or the issue time, do not count.
+ */
+ boolean isStaleFor(String currentLimits) {
+ String limits = handshakeLimits;
+ return currentLimits != null && limits != null && !limits.equals(currentLimits);
+ }
+
void retire() {
boolean close;
synchronized (lock) {
diff --git a/application/src/main/java/org/thingsboard/server/service/edge/DefaultEdgeLicenseService.java b/application/src/main/java/org/thingsboard/server/service/edge/DefaultEdgeLicenseService.java
index 45263ef7fd..069fd5083d 100644
--- a/application/src/main/java/org/thingsboard/server/service/edge/DefaultEdgeLicenseService.java
+++ b/application/src/main/java/org/thingsboard/server/service/edge/DefaultEdgeLicenseService.java
@@ -6,6 +6,7 @@ package org.thingsboard.server.service.edge;
import com.fasterxml.jackson.databind.JsonNode;
import jakarta.annotation.PostConstruct;
import lombok.extern.slf4j.Slf4j;
+import org.apache.hc.client5.http.config.ConnectionConfig;
import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
import org.apache.hc.client5.http.impl.classic.HttpClientBuilder;
import org.apache.hc.client5.http.impl.classic.HttpClients;
@@ -134,7 +135,6 @@ public class DefaultEdgeLicenseService implements EdgeLicenseService {
httpClient = HttpClientBuilder.create().useSystemProperties().setConnectionManager(createConnectionManager(true)).build();
HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory();
factory.setHttpClient(httpClient);
- factory.setConnectTimeout(CONNECT_TIMEOUT);
return new RestTemplate(factory);
} else if (proxyEnabled) {
log.warn("Going to use Proxy Server: [{}:{}]", System.getProperty("tb.proxy.host"), System.getProperty("tb.proxy.port"));
@@ -143,13 +143,11 @@ public class DefaultEdgeLicenseService implements EdgeLicenseService {
.setProxy(new HttpHost("https", System.getProperty("tb.proxy.host"), Integer.parseInt(System.getProperty("tb.proxy.port")))).build();
HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory();
factory.setHttpClient(httpClient);
- factory.setConnectTimeout(CONNECT_TIMEOUT);
return new RestTemplate(factory);
} else {
httpClient = HttpClients.custom().setConnectionManager(createConnectionManager(false)).build();
HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory();
factory.setHttpClient(httpClient);
- factory.setConnectTimeout(CONNECT_TIMEOUT);
return new RestTemplate(factory);
}
}
@@ -157,8 +155,10 @@ public class DefaultEdgeLicenseService implements EdgeLicenseService {
private HttpClientConnectionManager createConnectionManager(boolean systemProperties) {
var socketFactory = systemProperties ? SSLConnectionSocketFactory.getSystemSocketFactory() : SSLConnectionSocketFactory.getSocketFactory();
var socketConfig = SocketConfig.custom().setSoTimeout(Timeout.of(READ_TIMEOUT, TimeUnit.MILLISECONDS)).build();
+ var connectionConfig = ConnectionConfig.custom().setConnectTimeout(Timeout.of(CONNECT_TIMEOUT, TimeUnit.MILLISECONDS)).build();
return PoolingHttpClientConnectionManagerBuilder.create()
.setDefaultSocketConfig(socketConfig)
+ .setDefaultConnectionConfig(connectionConfig)
.setSSLSocketFactory(socketFactory).build();
}
diff --git a/application/src/main/java/org/thingsboard/server/service/edge/rpc/processor/telemetry/BaseTelemetryProcessor.java b/application/src/main/java/org/thingsboard/server/service/edge/rpc/processor/telemetry/BaseTelemetryProcessor.java
index 04d7939917..0f51d5525d 100644
--- a/application/src/main/java/org/thingsboard/server/service/edge/rpc/processor/telemetry/BaseTelemetryProcessor.java
+++ b/application/src/main/java/org/thingsboard/server/service/edge/rpc/processor/telemetry/BaseTelemetryProcessor.java
@@ -193,7 +193,7 @@ public abstract class BaseTelemetryProcessor extends BaseEdgeProcessor {
}
}
case ENTITY_GROUP -> {
- EntityGroup entityGroup = edgeCtx.getEntityGroupService().findEntityGroupById(tenantId, new EntityGroupId(entityId.getId()));
+ EntityGroup entityGroup = edgeCtx.getEntityGroupService().findEntityGroupInfoByTenantIdAndId(tenantId, new EntityGroupId(entityId.getId()));
if (entityGroup != null) {
metaData.putValue("entityGroupName", entityGroup.getName());
metaData.putValue("entityGroupType", entityGroup.getType().name());
diff --git a/application/src/main/java/org/thingsboard/server/service/entitiy/user/DefaultTbUserSettingsService.java b/application/src/main/java/org/thingsboard/server/service/entitiy/user/DefaultTbUserSettingsService.java
index ddb154c88a..a045db3b86 100644
--- a/application/src/main/java/org/thingsboard/server/service/entitiy/user/DefaultTbUserSettingsService.java
+++ b/application/src/main/java/org/thingsboard/server/service/entitiy/user/DefaultTbUserSettingsService.java
@@ -1,5 +1,6 @@
// SPDX-FileCopyrightText: Copyright The ThingsBoard Authors
-// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Modifications Copyright ThingsBoard, Inc.
+// SPDX-License-Identifier: Apache-2.0 AND BUSL-1.1
package org.thingsboard.server.service.entitiy.user;
import com.fasterxml.jackson.databind.JsonNode;
@@ -39,7 +40,7 @@ import java.util.stream.Collectors;
@Slf4j
public class DefaultTbUserSettingsService implements TbUserSettingsService {
- private static final int MAX_DASHBOARD_INFO_LIST_SIZE = 10;
+ private static final int MAX_DASHBOARD_INFO_LIST_SIZE = 50;
private static final Predicate EMPTY_TITLE = i -> StringUtils.isEmpty(i.getTitle());
private final UserSettingsService settingsService;
diff --git a/application/src/main/java/org/thingsboard/server/service/install/lts/V4_4_2_0Migration.java b/application/src/main/java/org/thingsboard/server/service/install/lts/V4_4_2_0Migration.java
new file mode 100644
index 0000000000..4c7a4dbeb4
--- /dev/null
+++ b/application/src/main/java/org/thingsboard/server/service/install/lts/V4_4_2_0Migration.java
@@ -0,0 +1,41 @@
+// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc.
+// SPDX-License-Identifier: BUSL-1.1
+package org.thingsboard.server.service.install.lts;
+
+import lombok.RequiredArgsConstructor;
+import lombok.extern.slf4j.Slf4j;
+import org.springframework.stereotype.Component;
+import org.thingsboard.server.common.data.id.TenantId;
+import org.thingsboard.server.common.data.notification.NotificationType;
+import org.thingsboard.server.dao.notification.DefaultNotifications;
+import org.thingsboard.server.dao.notification.NotificationSettingsService;
+import org.thingsboard.server.queue.util.TbCoreComponent;
+
+@Slf4j
+@Component
+@TbCoreComponent
+@RequiredArgsConstructor
+public class V4_4_2_0Migration implements Migration {
+
+ private final NotificationSettingsService notificationSettingsService;
+ private final DefaultNotifications defaultNotifications;
+
+ @Override
+ public String getVersion() {
+ return "4.4.2.0";
+ }
+
+ @Override
+ public void apply() {
+ createAiCreditsLimitIncreaseRequestTemplate();
+ }
+
+ private void createAiCreditsLimitIncreaseRequestTemplate() {
+ if (notificationSettingsService.isNotificationConfigured(TenantId.SYS_TENANT_ID, NotificationType.AI_CREDITS_LIMIT_INCREASE_REQUEST)) {
+ log.debug("The AI credits limit increase request notification template already exists");
+ return;
+ }
+ defaultNotifications.create(TenantId.SYS_TENANT_ID, DefaultNotifications.aiCreditsLimitIncreaseRequest);
+ log.info("Created the AI credits limit increase request notification template");
+ }
+}
diff --git a/application/src/main/java/org/thingsboard/server/service/install/update/EntityViewGroupAllUpdater.java b/application/src/main/java/org/thingsboard/server/service/install/update/EntityViewGroupAllUpdater.java
index 88b58152ed..212c59aa5d 100644
--- a/application/src/main/java/org/thingsboard/server/service/install/update/EntityViewGroupAllUpdater.java
+++ b/application/src/main/java/org/thingsboard/server/service/install/update/EntityViewGroupAllUpdater.java
@@ -31,7 +31,7 @@ class EntityViewGroupAllUpdater extends EntityGroupAllPaginatedUpdater compositeCallback = operationCount > 1 ? new CompositeCallback(operationCount, callback) : callback;
if (hasTelemetry) {
- process(sessionInfo, data.getPostTelemetryMsg(), compositeCallback);
+ process(sessionInfo, data.getPostTelemetryMsg(), data.getTelemetryTypeCastDisabledKeysList(), compositeCallback);
}
if (hasAttributes) {
- process(sessionInfo, data.getPostAttributesMsg(), compositeCallback);
+ process(sessionInfo, data.getPostAttributesMsg(), data.getAttributesTypeCastDisabledKeysList(), compositeCallback);
}
};
}
@@ -226,11 +227,11 @@ public class DefaultPlatformIntegrationService extends IntegrationActivityManage
IntegrationCallback compositeCallback = operationCount > 1 ? new CompositeCallback(operationCount, callback) : callback;
if (hasTelemetry) {
- process(asset, data.getPostTelemetryMsg(), compositeCallback);
+ process(asset, data.getPostTelemetryMsg(), data.getTelemetryTypeCastDisabledKeysList(), compositeCallback);
}
if (hasAttributes) {
- process(asset, data.getPostAttributesMsg(), compositeCallback);
+ process(asset, data.getPostAttributesMsg(), data.getAttributesTypeCastDisabledKeysList(), compositeCallback);
}
};
}
@@ -363,6 +364,11 @@ public class DefaultPlatformIntegrationService extends IntegrationActivityManage
@Override
public void process(SessionInfoProto sessionInfo, PostTelemetryMsg msg, IntegrationCallback callback) {
+ process(sessionInfo, msg, Collections.emptySet(), callback);
+ }
+
+ // typeCastDisabledKeys: the keys whose string values the converter kept as strings, passed to the rule engine in the metadata.
+ void process(SessionInfoProto sessionInfo, PostTelemetryMsg msg, Collection typeCastDisabledKeys, IntegrationCallback callback) {
try {
if (msg.getTsKvListCount() == 0) {
callback.onSuccess(null);
@@ -381,6 +387,7 @@ public class DefaultPlatformIntegrationService extends IntegrationActivityManage
metaData.putValue("deviceName", sessionInfo.getDeviceName());
metaData.putValue("deviceType", sessionInfo.getDeviceType());
metaData.putValue("ts", tsKv.getTs() + "");
+ metaData.putTypeCastDisabledKeys(typeCastDisabledKeys);
JsonObject json = JsonUtils.getJsonObject(tsKv.getKvList());
sendToRuleEngine(tenantId, deviceId, sessionInfo, json, metaData, TbMsgType.POST_TELEMETRY_REQUEST, packCallback);
}
@@ -391,6 +398,10 @@ public class DefaultPlatformIntegrationService extends IntegrationActivityManage
@Override
public void process(SessionInfoProto sessionInfo, PostAttributeMsg msg, IntegrationCallback callback) {
+ process(sessionInfo, msg, Collections.emptySet(), callback);
+ }
+
+ void process(SessionInfoProto sessionInfo, PostAttributeMsg msg, Collection typeCastDisabledKeys, IntegrationCallback callback) {
try {
TenantId tenantId = TenantId.fromUUID(new UUID(sessionInfo.getTenantIdMSB(), sessionInfo.getTenantIdLSB()));
DeviceId deviceId = new DeviceId(new UUID(sessionInfo.getDeviceIdMSB(), sessionInfo.getDeviceIdLSB()));
@@ -399,6 +410,7 @@ public class DefaultPlatformIntegrationService extends IntegrationActivityManage
TbMsgMetaData metaData = new TbMsgMetaData();
metaData.putValue("deviceName", sessionInfo.getDeviceName());
metaData.putValue("deviceType", sessionInfo.getDeviceType());
+ metaData.putTypeCastDisabledKeys(typeCastDisabledKeys);
sendToRuleEngine(tenantId, deviceId, sessionInfo, json, metaData, TbMsgType.POST_ATTRIBUTES_REQUEST,
new IntegrationTbQueueCallback(new ApiStatsProxyCallback<>(tenantId, getCustomerId(sessionInfo), msg.getKvList().size(), callback)));
} catch (Exception e) {
@@ -717,7 +729,7 @@ public class DefaultPlatformIntegrationService extends IntegrationActivityManage
return metaData;
}
- private void process(Asset asset, PostTelemetryMsg msg, IntegrationCallback callback) {
+ private void process(Asset asset, PostTelemetryMsg msg, Collection typeCastDisabledKeys, IntegrationCallback callback) {
try {
if (msg.getTsKvListCount() == 0) {
callback.onSuccess(null);
@@ -733,6 +745,7 @@ public class DefaultPlatformIntegrationService extends IntegrationActivityManage
metaData.putValue("assetName", asset.getName());
metaData.putValue("assetType", asset.getType());
metaData.putValue("ts", tsKv.getTs() + "");
+ metaData.putTypeCastDisabledKeys(typeCastDisabledKeys);
JsonObject json = JsonUtils.getJsonObject(tsKv.getKvList());
sendToRuleEngine(asset.getTenantId(), asset.getId(), asset.getAssetProfileId(),
asset.getCustomerId(), json, metaData, TbMsgType.POST_TELEMETRY_REQUEST, packCallback);
@@ -742,12 +755,13 @@ public class DefaultPlatformIntegrationService extends IntegrationActivityManage
}
}
- private void process(Asset asset, PostAttributeMsg msg, IntegrationCallback callback) {
+ private void process(Asset asset, PostAttributeMsg msg, Collection typeCastDisabledKeys, IntegrationCallback callback) {
try {
JsonObject json = JsonUtils.getJsonObject(msg.getKvList());
TbMsgMetaData metaData = new TbMsgMetaData();
metaData.putValue("assetName", asset.getName());
metaData.putValue("assetType", asset.getType());
+ metaData.putTypeCastDisabledKeys(typeCastDisabledKeys);
sendToRuleEngine(asset.getTenantId(), asset.getId(), asset.getAssetProfileId(),
asset.getCustomerId(), json, metaData, TbMsgType.POST_ATTRIBUTES_REQUEST,
new IntegrationTbQueueCallback(new ApiStatsProxyCallback<>(asset.getTenantId(), asset.getCustomerId(), msg.getKvList().size(), callback)));
diff --git a/application/src/main/java/org/thingsboard/server/service/iot_hub/DefaultDevicePackageUpdateService.java b/application/src/main/java/org/thingsboard/server/service/iot_hub/DefaultDevicePackageService.java
similarity index 70%
rename from application/src/main/java/org/thingsboard/server/service/iot_hub/DefaultDevicePackageUpdateService.java
rename to application/src/main/java/org/thingsboard/server/service/iot_hub/DefaultDevicePackageService.java
index f4604beea4..e025d41fe0 100644
--- a/application/src/main/java/org/thingsboard/server/service/iot_hub/DefaultDevicePackageUpdateService.java
+++ b/application/src/main/java/org/thingsboard/server/service/iot_hub/DefaultDevicePackageService.java
@@ -9,6 +9,8 @@ import com.fasterxml.jackson.databind.node.TextNode;
import com.google.gson.JsonParser;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
+import org.apache.commons.lang3.exception.ExceptionUtils;
+import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;
import org.springframework.transaction.support.TransactionTemplate;
import org.springframework.web.client.RestClientException;
@@ -16,10 +18,13 @@ import org.thingsboard.common.util.JacksonUtil;
import org.thingsboard.rule.engine.api.AttributesSaveRequest;
import org.thingsboard.server.common.adaptor.JsonConverter;
import org.thingsboard.server.common.data.AttributeScope;
+import org.thingsboard.server.common.data.Customer;
import org.thingsboard.server.common.data.Dashboard;
import org.thingsboard.server.common.data.Device;
import org.thingsboard.server.common.data.DeviceProfile;
import org.thingsboard.server.common.data.EntityType;
+import org.thingsboard.server.common.data.GroupEntity;
+import org.thingsboard.server.common.data.HasCustomerId;
import org.thingsboard.server.common.data.HasName;
import org.thingsboard.server.common.data.HasTenantId;
import org.thingsboard.server.common.data.HasVersion;
@@ -30,14 +35,17 @@ import org.thingsboard.server.common.data.exception.EntityVersionMismatchExcepti
import org.thingsboard.server.common.data.exception.ThingsboardErrorCode;
import org.thingsboard.server.common.data.exception.ThingsboardException;
import org.thingsboard.server.common.data.id.ConverterId;
+import org.thingsboard.server.common.data.id.CustomerId;
import org.thingsboard.server.common.data.id.DashboardId;
import org.thingsboard.server.common.data.id.DeviceId;
import org.thingsboard.server.common.data.id.DeviceProfileId;
+import org.thingsboard.server.common.data.id.EntityGroupId;
import org.thingsboard.server.common.data.id.EntityId;
import org.thingsboard.server.common.data.id.IntegrationId;
import org.thingsboard.server.common.data.id.IotHubInstalledItemId;
import org.thingsboard.server.common.data.id.RuleChainId;
import org.thingsboard.server.common.data.id.TenantId;
+import org.thingsboard.server.common.data.group.EntityGroup;
import org.thingsboard.server.common.data.integration.Integration;
import org.thingsboard.server.common.data.iot_hub.DeviceInstalledItemDescriptor;
import org.thingsboard.server.common.data.iot_hub.IotHubInstalledItem;
@@ -63,9 +71,12 @@ import org.thingsboard.server.dao.subscription.PlatformFeature;
import org.thingsboard.server.dao.subscription.SubscriptionService;
import org.thingsboard.server.exception.DataValidationException;
import org.thingsboard.server.exception.EntitiesLimitExceededException;
+import org.thingsboard.server.exception.ThingsboardEntitiesLimitExceededResponse;
+import org.thingsboard.server.exception.ThingsboardErrorResponse;
import org.thingsboard.server.queue.util.TbCoreComponent;
import org.thingsboard.server.service.entitiy.AbstractTbEntityService;
import org.thingsboard.server.service.entitiy.integration.TbIntegrationService;
+import org.thingsboard.server.service.install.ProjectInfo;
import org.thingsboard.server.service.rule.TbRuleChainService;
import org.thingsboard.server.service.security.model.SecurityUser;
import org.thingsboard.server.service.telemetry.TelemetrySubscriptionService;
@@ -86,18 +97,17 @@ import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
- * Applies an update of an installed device package in one transaction. The install wizard resolves the templates
- * of the new version (the same way it installs them) and sends the entity of each step; this service checks the
- * plan, saves every entity and the new version of the installed item together, and rolls all of it back on a
- * failure. The side effects of the saves (actors, integration restart, edge, caches) run after commit, so a
- * rollback leaves no trace; the audit log, version control and the attributes, which aren't transactional,
- * are written after commit too.
+ * Installs a device package, or updates an installed one, in one transaction. The install wizard resolves the
+ * templates of the version and sends the entity of each step; this service checks the plan, saves every entity
+ * and the installed item together, and rolls all of it back on a failure. The side effects of the saves (actors,
+ * integration restart, edge, caches) run after commit, so a rollback leaves no trace; the audit log, version control
+ * and the attributes, which aren't transactional, are written after commit too.
*/
@Service
@TbCoreComponent
@Slf4j
@RequiredArgsConstructor
-public class DefaultDevicePackageUpdateService extends AbstractTbEntityService implements DevicePackageUpdateService {
+public class DefaultDevicePackageService extends AbstractTbEntityService implements DevicePackageService {
// Step type of the package -> the alias its templates refer to it by, e.g. ${deviceProfile.id}
private static final Map STEP_ALIASES = Map.of(
@@ -110,7 +120,7 @@ public class DefaultDevicePackageUpdateService extends AbstractTbEntityService i
"DOWNLINK_CONVERTER", "downlinkConverter",
"INTEGRATION", "integration");
private static final Pattern ENTITY_PLACEHOLDER = Pattern.compile("\\$\\{([A-Za-z]+)\\.([A-Za-z]+)}");
- private static final String UNEXPECTED_ERROR = "Failed to update the device package";
+ private static final String UNEXPECTED_ERROR = "Failed to save the device package";
private final IotHubInstalledItemService installedItemService;
private final IotHubRestClient iotHubRestClient;
@@ -129,6 +139,7 @@ public class DefaultDevicePackageUpdateService extends AbstractTbEntityService i
private final AttributesService attributesService;
private final TelemetrySubscriptionService telemetryService;
private final TransactionTemplate transactionTemplate;
+ private final ProjectInfo projectInfo;
@Override
public List check(SecurityUser user, IotHubInstalledItemId installedItemId) {
@@ -162,33 +173,168 @@ public class DefaultDevicePackageUpdateService extends AbstractTbEntityService i
}
@Override
- public DeviceUpdateResult apply(SecurityUser user, IotHubInstalledItemId installedItemId, DeviceUpdateRequest request) {
+ public DevicePackageResult install(SecurityUser user, DevicePackageRequest request) {
+ TenantId tenantId = user.getTenantId();
+ log.info("[{}] Installing device package version {}", tenantId, request.getVersionId());
+ DevicePackageResult result = apply(user, "install of version " + request.getVersionId(), () -> {
+ if (request.getVersionId() == null || request.getFromVersionId() != null || toUuid(request.getVersionId()) == null) {
+ throw new IllegalArgumentException("Invalid install request");
+ }
+ Placement placement = placement(tenantId, request);
+ JsonNode versionInfo = iotHubRestClient.getVersionInfo(request.getVersionId());
+ if (versionInfo == null) {
+ throw new IllegalArgumentException("Failed to get version info from IoT Hub");
+ }
+ // The package owns nothing yet, so overwriting an entity the tenant has needs a confirmation
+ DeviceInstalledItemDescriptor previous = new DeviceInstalledItemDescriptor();
+ validateInstallSteps(request);
+ validate(tenantId, previous, request);
+ return transactionTemplate.execute(status -> {
+ Applied applied = applySteps(tenantId, previous, request, null, placement);
+ IotHubInstalledItem installedItem = new IotHubInstalledItem();
+ installedItem.setTenantId(tenantId);
+ installedItem.setItemId(UUID.fromString(versionInfo.get("itemId").asText()));
+ installedItem.setItemVersionId(UUID.fromString(request.getVersionId()));
+ installedItem.setItemName(versionInfo.get("name").asText());
+ installedItem.setItemType("DEVICE");
+ installedItem.setVersion(versionInfo.get("version").asText());
+ installedItem.setDescriptor(applied.descriptor());
+ installedItemService.save(tenantId, installedItem);
+ return applied;
+ });
+ });
+ if (result.isSuccess()) {
+ reportInstall(user, request.getVersionId());
+ log.info("[{}] Installed device package version {}", tenantId, request.getVersionId());
+ }
+ return result;
+ }
+
+ @Override
+ public DevicePackageResult update(SecurityUser user, IotHubInstalledItemId installedItemId, DevicePackageRequest request) {
TenantId tenantId = user.getTenantId();
log.info("[{}] Updating device package {} to version {}", tenantId, installedItemId, request.getVersionId());
- Applied applied;
- try {
+ DevicePackageResult result = apply(user, "update of " + installedItemId, () -> {
DevicePackage devicePackage = findDevicePackage(tenantId, installedItemId);
JsonNode versionInfo = iotHubRestClient.getVersionInfo(request.getVersionId());
if (versionInfo == null || !devicePackage.installedItem().getItemId().toString().equals(versionInfo.path("itemId").asText())) {
throw new IllegalArgumentException("The version belongs to another item");
}
- validatePlan(devicePackage, request);
- checkFeatures(tenantId, request);
- validateIntegrations(tenantId, request);
- applied = transactionTemplate.execute(status -> applySteps(tenantId, devicePackage, request, versionInfo));
+ validate(tenantId, devicePackage.descriptor(), request);
+ return transactionTemplate.execute(status -> {
+ IotHubInstalledItem installedItem = lockInstalledItem(tenantId, devicePackage, request);
+ Applied applied = applySteps(tenantId, devicePackage.descriptor(), request, installedItem.getItemVersionId(), Placement.NONE);
+ installedItem.setItemVersionId(UUID.fromString(request.getVersionId()));
+ installedItem.setItemName(versionInfo.get("name").asText());
+ installedItem.setVersion(versionInfo.get("version").asText());
+ installedItem.setDescriptor(applied.descriptor());
+ installedItemService.save(tenantId, installedItem);
+ return applied;
+ });
+ });
+ if (result.isSuccess()) {
+ log.info("[{}] Updated device package {} to version {}", tenantId, installedItemId, request.getVersionId());
+ }
+ return result;
+ }
+
+ /** Runs the planned change and, once it committed, what isn't transactional; a failure leaves nothing changed. */
+ private DevicePackageResult apply(SecurityUser user, String operation, PackageChange change) {
+ TenantId tenantId = user.getTenantId();
+ Applied applied;
+ try {
+ applied = change.apply();
} catch (StepFailure e) {
- log.warn("[{}] Device package update of {} failed on step [{}], nothing was changed", tenantId, installedItemId, e.stepKey, e.getCause());
- return DeviceUpdateResult.error(userMessage(e.getCause()), e.stepKey);
+ log.warn("[{}] Device package {} failed on step [{}], nothing was changed", tenantId, operation, e.stepKey, e.getCause());
+ return DevicePackageResult.error(userMessage(e.getCause()), e.stepKey, limitOf(e.getCause()));
} catch (RestClientException e) {
- log.error("[{}] IoT Hub request failed while updating device package {}", tenantId, installedItemId, e);
- return DeviceUpdateResult.error("IoT Hub is unavailable. Try again later.", null);
+ log.error("[{}] IoT Hub request failed during the device package {}", tenantId, operation, e);
+ return DevicePackageResult.error("IoT Hub is unavailable. Try again later.", null);
} catch (Exception e) {
- log.warn("[{}] Device package update of {} failed, nothing was changed", tenantId, installedItemId, e);
- return DeviceUpdateResult.error(userMessage(e), null);
+ log.warn("[{}] Device package {} failed, nothing was changed", tenantId, operation, e);
+ return DevicePackageResult.error(userMessage(e), null);
}
afterCommit(user, tenantId, applied);
- log.info("[{}] Updated device package {} to version {}", tenantId, installedItemId, request.getVersionId());
- return DeviceUpdateResult.success(applied.descriptor(), applied.outputs());
+ return DevicePackageResult.success(applied.descriptor(), applied.outputs());
+ }
+
+ /** Counts the install on the Hub; the package is installed whether or not the Hub hears of it. */
+ private void reportInstall(SecurityUser user, String versionId) {
+ TenantId tenantId = user.getTenantId();
+ try {
+ InstallReport report = DefaultIotHubService.buildInstallReport(tenantId.getId(), user.getId().getId(),
+ projectInfo.getProjectVersion(), projectInfo.getProductType());
+ iotHubRestClient.reportVersionInstalled(versionId, report);
+ } catch (Exception e) {
+ log.warn("[{}] Failed to report install for version {}: {}", tenantId, versionId, e.getMessage());
+ }
+ }
+
+ /**
+ * At install a kept entity is one the user chose to use as it is: the package doesn't own it. An existing device or
+ * gateway is never overwritten: its credentials are what its firmware uses.
+ */
+ private static void validateInstallSteps(DevicePackageRequest request) {
+ if (request.getSteps() == null) {
+ return;
+ }
+ for (DevicePackageRequest.Step step : request.getSteps()) {
+ boolean deviceOrGateway = "DEVICE".equals(step.getType()) || "GATEWAY".equals(step.getType());
+ if ((step.getAction() == DevicePackageRequest.Action.KEEP && !"use-existing".equals(step.getResolution()))
+ || (step.getAction() == DevicePackageRequest.Action.OVERWRITE && deviceOrGateway)) {
+ throw new IllegalArgumentException("Invalid install step: " + step.getName());
+ }
+ }
+ }
+
+ /**
+ * The customer and the device group the install was opened from; each must be the tenant's. The group's own
+ * permission isn't checked again: the endpoint's checkAllPermissions already requires ALL operations on ALL resources.
+ */
+ private Placement placement(TenantId tenantId, DevicePackageRequest request) {
+ CustomerId customerId = request.getCustomerId() != null && !CustomerId.NULL_UUID.equals(request.getCustomerId())
+ ? new CustomerId(request.getCustomerId()) : null;
+ if (customerId != null && !isTenantsCustomer(tenantId, customerId)) {
+ throw new IllegalArgumentException("Invalid install request");
+ }
+ if (request.getEntityGroupId() == null) {
+ return new Placement(customerId, customerId, null);
+ }
+ EntityGroup group = entityGroupService.findEntityGroupById(tenantId, new EntityGroupId(request.getEntityGroupId()));
+ EntityId owner = group != null ? group.getOwnerId() : null;
+ boolean tenants = owner != null && (tenantId.equals(owner)
+ || (owner.getEntityType() == EntityType.CUSTOMER && isTenantsCustomer(tenantId, new CustomerId(owner.getId()))));
+ if (group == null || group.getType() != EntityType.DEVICE || !tenants) {
+ throw new IllegalArgumentException("Invalid install request");
+ }
+ // As a device saved into a group: with no customer given, a new one goes to the group's customer
+ CustomerId deviceCustomerId = customerId == null && owner.getEntityType() == EntityType.CUSTOMER ? new CustomerId(owner.getId()) : customerId;
+ return new Placement(customerId, deviceCustomerId, group);
+ }
+
+ private boolean isTenantsCustomer(TenantId tenantId, CustomerId customerId) {
+ Customer customer = customerService.findCustomerById(tenantId, customerId);
+ return customer != null && tenantId.equals(customer.getTenantId());
+ }
+
+ /**
+ * Puts the entity in the customer the install was opened from. An overwrite never changes the owner, with or without
+ * a customer: the dao would move the entity past the owner change, leaving its groups and the owner cache stale.
+ */
+ private static void assignCustomer(GroupEntity> entity, CustomerId customerId, GroupEntity> current, DevicePackageRequest.Step step) {
+ if (customerId != null) {
+ entity.setOwnerId(customerId);
+ }
+ if (current != null && !current.getOwnerId().equals(entity.getOwnerId())) {
+ throw new IllegalArgumentException(step.getName() + " belongs to another owner");
+ }
+ }
+
+ /** What is checked before the transaction: the plan, the tenant's plan features and the integrations' configuration. */
+ private void validate(TenantId tenantId, DeviceInstalledItemDescriptor previous, DevicePackageRequest request) throws Exception {
+ validatePlan(ownedIds(previous), request);
+ checkFeatures(tenantId, request);
+ validateIntegrations(tenantId, request);
}
private DevicePackage findDevicePackage(TenantId tenantId, IotHubInstalledItemId installedItemId) {
@@ -201,50 +347,49 @@ public class DefaultDevicePackageUpdateService extends AbstractTbEntityService i
}
/**
- * The update may only change what the package owns, or what the user confirmed. The device and the gateway,
+ * The device package may only change what it owns, or what the user confirmed. Its own device and gateway,
* whose credentials the firmware uses, are never changed.
*/
- private void validatePlan(DevicePackage devicePackage, DeviceUpdateRequest request) {
+ private void validatePlan(Set ownedIds, DevicePackageRequest request) {
if (request.getSteps() == null || request.getSteps().isEmpty()) {
- throw new IllegalArgumentException("The update has no steps");
+ throw new IllegalArgumentException("The device package has no steps");
}
- Set ownedIds = ownedIds(devicePackage.descriptor());
// A form's values are saved under its key too, so an entity step may not share it
Set stateKeys = request.getInstallState() != null ? new HashSet<>(request.getInstallState().keySet()) : new HashSet<>();
- for (DeviceUpdateRequest.Step step : request.getSteps()) {
+ for (DevicePackageRequest.Step step : request.getSteps()) {
if (step.getName() == null || step.getAction() == null || !isKnownType(step.getType())) {
- throw new IllegalArgumentException("Invalid update step: " + step.getName());
+ throw new IllegalArgumentException("Invalid step: " + step.getName());
}
if (!stateKeys.add(step.stateKey())) {
- throw new IllegalArgumentException("Duplicate update step: " + step.stateKey());
+ throw new IllegalArgumentException("Duplicate step: " + step.stateKey());
}
boolean deviceOrGateway = "DEVICE".equals(step.getType()) || "GATEWAY".equals(step.getType());
switch (step.getAction()) {
case KEEP, OVERWRITE -> {
if (step.getEntityId() == null && !"GATEWAY_CONNECTOR".equals(step.getType())) {
- throw new IllegalArgumentException("No entity for update step: " + step.getName());
+ throw new IllegalArgumentException("No entity for step: " + step.getName());
}
boolean owned = step.getEntityId() != null && ownedIds.contains(step.getEntityId());
- if (step.getAction() == DeviceUpdateRequest.Action.OVERWRITE && !owned && !step.isConfirmed()
+ if (step.getAction() == DevicePackageRequest.Action.OVERWRITE && !owned && !step.isConfirmed()
&& !"GATEWAY_CONNECTOR".equals(step.getType())) {
throw new IllegalArgumentException("Overwriting an entity of another package needs a confirmation: " + step.getName());
}
- if (step.getAction() == DeviceUpdateRequest.Action.OVERWRITE && deviceOrGateway && owned) {
+ if (step.getAction() == DevicePackageRequest.Action.OVERWRITE && deviceOrGateway && owned) {
throw new IllegalArgumentException("The device and its credentials don't change on update");
}
}
case CREATE -> {
}
}
- if (step.getAction() != DeviceUpdateRequest.Action.KEEP && (step.getEntity() == null || !step.getEntity().isObject())) {
- throw new IllegalArgumentException("No entity data for update step: " + step.getName());
+ if (step.getAction() != DevicePackageRequest.Action.KEEP && (step.getEntity() == null || !step.getEntity().isObject())) {
+ throw new IllegalArgumentException("No entity data for step: " + step.getName());
}
}
}
/** Integrations and converters are saved as through their API, which needs the feature in the tenant's plan. */
- private void checkFeatures(TenantId tenantId, DeviceUpdateRequest request) {
- boolean savesIntegrations = request.getSteps().stream().anyMatch(step -> step.getAction() != DeviceUpdateRequest.Action.KEEP
+ private void checkFeatures(TenantId tenantId, DevicePackageRequest request) {
+ boolean savesIntegrations = request.getSteps().stream().anyMatch(step -> step.getAction() != DevicePackageRequest.Action.KEEP
&& ("INTEGRATION".equals(step.getType()) || step.getType().endsWith("_CONVERTER")));
if (savesIntegrations) {
subscriptionService.checkFeatureAllowed(tenantId, PlatformFeature.INTEGRATIONS);
@@ -252,13 +397,13 @@ public class DefaultDevicePackageUpdateService extends AbstractTbEntityService i
}
/** The configuration of an integration is checked by a remote call, so before the transaction. */
- private void validateIntegrations(TenantId tenantId, DeviceUpdateRequest request) throws Exception {
- for (DeviceUpdateRequest.Step step : request.getSteps()) {
- if (!"INTEGRATION".equals(step.getType()) || step.getAction() == DeviceUpdateRequest.Action.KEEP) {
+ private void validateIntegrations(TenantId tenantId, DevicePackageRequest request) throws Exception {
+ for (DevicePackageRequest.Step step : request.getSteps()) {
+ if (!"INTEGRATION".equals(step.getType()) || step.getAction() == DevicePackageRequest.Action.KEEP) {
continue;
}
ObjectNode body = step.getEntity().deepCopy();
- // Converters this update creates have no id yet; the configuration doesn't depend on them
+ // Converters the request creates have no id yet; the configuration doesn't depend on them
body.remove(List.of("id", "defaultConverterId", "downlinkConverterId"));
Integration integration = JacksonUtil.treeToValue(body, Integration.class);
integration.setTenantId(tenantId);
@@ -274,9 +419,12 @@ public class DefaultDevicePackageUpdateService extends AbstractTbEntityService i
}
}
- private Applied applySteps(TenantId tenantId, DevicePackage devicePackage, DeviceUpdateRequest request, JsonNode versionInfo) {
- IotHubInstalledItem installedItem = lockInstalledItem(tenantId, devicePackage, request);
- DeviceInstalledItemDescriptor previous = devicePackage.descriptor();
+ /**
+ * Saves the entities of the steps and builds the descriptor of the installed item, which the caller saves in the
+ * same transaction. previous is what the package had: on install an empty descriptor, and installedVersionId null.
+ */
+ private Applied applySteps(TenantId tenantId, DeviceInstalledItemDescriptor previous, DevicePackageRequest request, UUID installedVersionId,
+ Placement placement) {
Set ownedIds = ownedIds(previous);
Map aliasOutputs = new HashMap<>();
Map outputs = new LinkedHashMap<>();
@@ -289,23 +437,25 @@ public class DefaultDevicePackageUpdateService extends AbstractTbEntityService i
});
}
List stepEntityIds = new ArrayList<>();
- Map usedExistingIds = usedExistingIds(previous);
+ Map usedExistingIds = new LinkedHashMap<>();
+ previous.getUsedExistingEntityIdsIncludingLegacy().forEach(id -> usedExistingIds.put(id.getId(), id));
List saved = new ArrayList<>();
- List connectorSteps = new ArrayList<>();
+ List grouped = new ArrayList<>();
+ List connectorSteps = new ArrayList<>();
List attributes = new ArrayList<>();
DashboardId dashboardId = null;
- for (DeviceUpdateRequest.Step step : request.getSteps()) {
+ for (DevicePackageRequest.Step step : request.getSteps()) {
try {
if ("GATEWAY_CONNECTOR".equals(step.getType())) {
// A connector lives in the gateway's attributes, which aren't transactional: saved after commit
- if (step.getAction() != DeviceUpdateRequest.Action.KEEP) {
+ if (step.getAction() != DevicePackageRequest.Action.KEEP) {
connectorSteps.add(copyWithEntity(step, resolvePlaceholders(step.getEntity(), aliasOutputs)));
}
continue;
}
JsonNode entity = step.getEntity() != null ? resolvePlaceholders(step.getEntity(), aliasOutputs) : null;
- StepResult result = applyStep(tenantId, step, entity);
+ StepResult result = applyStep(tenantId, step, entity, placement);
ObjectNode output = result.output();
aliasOutputs.put(STEP_ALIASES.get(step.getType()), output);
outputs.put(step.stateKey(), output);
@@ -317,7 +467,7 @@ public class DefaultDevicePackageUpdateService extends AbstractTbEntityService i
state.put("resolution", resolution);
// A kept entity keeps the checksum of what the package left: the current one would take the
// user's changes for the package's, and the next update would overwrite them without a warning
- String checksum = step.getAction() == DeviceUpdateRequest.Action.KEEP ? previousChecksum(previous, step.getEntityId()) : result.checksum();
+ String checksum = step.getAction() == DevicePackageRequest.Action.KEEP ? previousChecksum(previous, step.getEntityId()) : result.checksum();
if (checksum != null) {
state.put("checksum", checksum);
}
@@ -343,8 +493,15 @@ public class DefaultDevicePackageUpdateService extends AbstractTbEntityService i
if (result.saved() != null) {
saved.add(result.saved());
}
- if (step.getAction() != DeviceUpdateRequest.Action.KEEP && !"use-existing".equals(resolution)) {
- // As at install, the step's attributes go with the entity it saved; written after commit
+ if (placement.entityGroup() != null && result.saved() != null && result.saved().created()
+ && result.entityId().getEntityType() == EntityType.DEVICE) {
+ entityGroupService.addEntityToEntityGroup(tenantId, placement.entityGroup().getId(), result.entityId());
+ grouped.add(result.saved());
+ }
+ // The step's attributes go with the entity it saved; at install also onto an entity the user chose to
+ // use, as the install always did. Written after commit
+ boolean install = installedVersionId == null;
+ if (install || (step.getAction() != DevicePackageRequest.Action.KEEP && !"use-existing".equals(resolution))) {
attributes.add(new StepAttributes(step.getName(), result.entityId(), step.getServerAttributes(), step.getSharedAttributes()));
}
} catch (StepFailure e) {
@@ -356,7 +513,7 @@ public class DefaultDevicePackageUpdateService extends AbstractTbEntityService i
// An update to the installed version itself, e.g. of ThingsBoard's default converter only, sends just the steps
// it changes: the other steps and the forms keep their install state
- if (UUID.fromString(request.getVersionId()).equals(installedItem.getItemVersionId()) && previous.getInstallState() != null) {
+ if (UUID.fromString(request.getVersionId()).equals(installedVersionId) && previous.getInstallState() != null) {
previous.getInstallState().forEach((key, value) -> {
if (value instanceof ObjectNode state) {
installState.putIfAbsent(key, state);
@@ -376,15 +533,10 @@ public class DefaultDevicePackageUpdateService extends AbstractTbEntityService i
carryMetadataStates(previous, tracked, state);
descriptor.setInstallState(state);
- installedItem.setItemVersionId(UUID.fromString(request.getVersionId()));
- installedItem.setItemName(versionInfo.get("name").asText());
- installedItem.setVersion(versionInfo.get("version").asText());
- installedItem.setDescriptor(descriptor);
- installedItemService.save(tenantId, installedItem);
// Resolved once every entity is saved: attributes may refer to a later step's entity
List resolvedAttributes = attributes.stream().map(a -> new StepAttributes(a.stepName(), a.entityId(),
resolvePlaceholders(a.server(), aliasOutputs), resolvePlaceholders(a.shared(), aliasOutputs))).toList();
- return new Applied(descriptor, outputs, saved, connectorSteps, resolvedAttributes, aliasOutputs);
+ return new Applied(descriptor, outputs, saved, connectorSteps, resolvedAttributes, aliasOutputs, placement.entityGroup(), grouped);
}
/** The checksums the installed device packages recorded, by entity. */
@@ -422,7 +574,7 @@ public class DefaultDevicePackageUpdateService extends AbstractTbEntityService i
* Another update of the package, e.g. a second click or another tab, waits here until this one commits, and then
* fails: the plan was made for the version installed before. Without it both would create the new entities.
*/
- private IotHubInstalledItem lockInstalledItem(TenantId tenantId, DevicePackage devicePackage, DeviceUpdateRequest request) {
+ private IotHubInstalledItem lockInstalledItem(TenantId tenantId, DevicePackage devicePackage, DevicePackageRequest request) {
IotHubInstalledItem installedItem = installedItemService.findByIdForUpdate(tenantId, devicePackage.installedItem().getId());
UUID planned = request.getFromVersionId() != null ? request.getFromVersionId() : devicePackage.installedItem().getItemVersionId();
if (installedItem == null || !planned.equals(installedItem.getItemVersionId())
@@ -432,11 +584,11 @@ public class DefaultDevicePackageUpdateService extends AbstractTbEntityService i
return installedItem;
}
- private StepResult applyStep(TenantId tenantId, DeviceUpdateRequest.Step step, JsonNode entity) throws ThingsboardException {
+ private StepResult applyStep(TenantId tenantId, DevicePackageRequest.Step step, JsonNode entity, Placement placement) throws ThingsboardException {
return switch (step.getType()) {
case "DEVICE_PROFILE" -> saveDeviceProfile(tenantId, step, entity);
- case "DEVICE", "GATEWAY" -> saveDevice(tenantId, step, entity);
- case "DASHBOARD" -> saveDashboard(tenantId, step, entity);
+ case "DEVICE", "GATEWAY" -> saveDevice(tenantId, step, entity, placement);
+ case "DASHBOARD" -> saveDashboard(tenantId, step, entity, placement);
case "RULE_CHAIN" -> saveRuleChain(tenantId, step, entity);
case "UPLINK_CONVERTER", "DOWNLINK_CONVERTER" -> saveConverter(tenantId, step, entity);
case "INTEGRATION" -> saveIntegration(tenantId, step, entity);
@@ -444,16 +596,16 @@ public class DefaultDevicePackageUpdateService extends AbstractTbEntityService i
};
}
- private StepResult saveDeviceProfile(TenantId tenantId, DeviceUpdateRequest.Step step, JsonNode entity) {
+ private StepResult saveDeviceProfile(TenantId tenantId, DevicePackageRequest.Step step, JsonNode entity) {
DeviceProfileId id = step.getEntityId() != null ? new DeviceProfileId(step.getEntityId()) : null;
DeviceProfile current = id != null ? deviceProfileService.findDeviceProfileById(tenantId, id) : null;
- if (step.getAction() == DeviceUpdateRequest.Action.KEEP) {
+ if (step.getAction() == DevicePackageRequest.Action.KEEP) {
existing(tenantId, current, step);
return kept(id, current.getName());
}
DeviceProfile profile = JacksonUtil.treeToValue(entity, DeviceProfile.class);
profile.setTenantId(tenantId);
- if (step.getAction() == DeviceUpdateRequest.Action.OVERWRITE) {
+ if (step.getAction() == DevicePackageRequest.Action.OVERWRITE) {
existing(tenantId, current, step);
prepareOverwrite(profile, id, current, step);
// The tenant's default profile stays the default one
@@ -466,31 +618,34 @@ public class DefaultDevicePackageUpdateService extends AbstractTbEntityService i
return savedResult(tenantId, result.getId(), result, step, output(result.getId(), result.getName()));
}
- private StepResult saveDevice(TenantId tenantId, DeviceUpdateRequest.Step step, JsonNode entity) {
+ private StepResult saveDevice(TenantId tenantId, DevicePackageRequest.Step step, JsonNode entity, Placement placement) {
DeviceId id = step.getEntityId() != null ? new DeviceId(step.getEntityId()) : null;
Device device;
boolean created = false;
- if (step.getAction() == DeviceUpdateRequest.Action.CREATE) {
+ if (step.getAction() == DevicePackageRequest.Action.CREATE) {
Device template = JacksonUtil.treeToValue(entity, Device.class);
template.setTenantId(tenantId);
template.setId(null);
template.setVersion(null);
+ assignCustomer(template, placement.deviceCustomerId(), null, step);
device = deviceService.saveDevice(template);
created = true;
} else {
Device current = id != null ? deviceService.findDeviceById(tenantId, id) : null;
device = existing(tenantId, current, step);
- if (step.getAction() == DeviceUpdateRequest.Action.OVERWRITE) {
- // Another device the user chose to overwrite; the package's own device never changes
+ if (step.getAction() == DevicePackageRequest.Action.OVERWRITE) {
+ // On update, another device the user chose to overwrite; it keeps its credentials. The package's own
+ // device never changes, and an install never overwrites one
Device template = JacksonUtil.treeToValue(entity, Device.class);
template.setTenantId(tenantId);
prepareOverwrite(template, id, current, step);
+ assignCustomer(template, placement.customerId(), current, step);
device = deviceService.saveDevice(template);
created = true;
}
}
DeviceCredentials credentials = deviceCredentialsService.findDeviceCredentialsByDeviceId(tenantId, device.getId());
- if (created && step.getCredentials() != null && step.getCredentials().isObject()) {
+ if (step.getAction() == DevicePackageRequest.Action.CREATE && step.getCredentials() != null && step.getCredentials().isObject()) {
credentials = applyCredentials(tenantId, credentials, step.getCredentials());
}
ObjectNode output = output(device.getId(), device.getName());
@@ -500,7 +655,7 @@ public class DefaultDevicePackageUpdateService extends AbstractTbEntityService i
if ("GATEWAY".equals(step.getType())) {
output.put("dockerComposeUrl", "/api/device-connectivity/gateway-launch/" + device.getId().getId() + "/docker-compose/download");
}
- SavedEntity saved = created ? new SavedEntity(device.getId(), device, step.getAction() == DeviceUpdateRequest.Action.CREATE) : null;
+ SavedEntity saved = created ? new SavedEntity(device.getId(), device, step.getAction() == DevicePackageRequest.Action.CREATE) : null;
return new StepResult(device.getId(), output, null, saved);
}
@@ -520,16 +675,16 @@ public class DefaultDevicePackageUpdateService extends AbstractTbEntityService i
return deviceCredentialsService.updateDeviceCredentials(tenantId, credentials);
}
- private StepResult saveDashboard(TenantId tenantId, DeviceUpdateRequest.Step step, JsonNode entity) {
+ private StepResult saveDashboard(TenantId tenantId, DevicePackageRequest.Step step, JsonNode entity, Placement placement) {
DashboardId id = step.getEntityId() != null ? new DashboardId(step.getEntityId()) : null;
Dashboard current = id != null ? dashboardService.findDashboardById(tenantId, id) : null;
- if (step.getAction() == DeviceUpdateRequest.Action.KEEP) {
+ if (step.getAction() == DevicePackageRequest.Action.KEEP) {
existing(tenantId, current, step);
return kept(id, current.getTitle());
}
Dashboard dashboard = JacksonUtil.treeToValue(entity, Dashboard.class);
dashboard.setTenantId(tenantId);
- if (step.getAction() == DeviceUpdateRequest.Action.OVERWRITE) {
+ if (step.getAction() == DevicePackageRequest.Action.OVERWRITE) {
existing(tenantId, current, step);
prepareOverwrite(dashboard, id, current, step);
// The dashboard keeps its owner and the customers it is assigned to
@@ -537,25 +692,27 @@ public class DefaultDevicePackageUpdateService extends AbstractTbEntityService i
dashboard.setCustomerId(current.getCustomerId());
}
dashboard.setAssignedCustomers(current.getAssignedCustomers());
+ assignCustomer(dashboard, placement.customerId(), current, step);
} else {
dashboard.setId(null);
dashboard.setVersion(null);
+ assignCustomer(dashboard, placement.customerId(), null, step);
}
Dashboard result = dashboardService.saveDashboard(dashboard);
return savedResult(tenantId, result.getId(), result, step, output(result.getId(), result.getTitle()));
}
- private StepResult saveRuleChain(TenantId tenantId, DeviceUpdateRequest.Step step, JsonNode entity) throws ThingsboardException {
+ private StepResult saveRuleChain(TenantId tenantId, DevicePackageRequest.Step step, JsonNode entity) throws ThingsboardException {
RuleChainId id = step.getEntityId() != null ? new RuleChainId(step.getEntityId()) : null;
RuleChain current = id != null ? ruleChainService.findRuleChainById(tenantId, id) : null;
- if (step.getAction() == DeviceUpdateRequest.Action.KEEP) {
+ if (step.getAction() == DevicePackageRequest.Action.KEEP) {
existing(tenantId, current, step);
return kept(id, current.getName());
}
JsonNode ruleChainJson = entity.has("ruleChain") ? entity.get("ruleChain") : entity;
RuleChain ruleChain = JacksonUtil.treeToValue(ruleChainJson, RuleChain.class);
ruleChain.setTenantId(tenantId);
- if (step.getAction() == DeviceUpdateRequest.Action.OVERWRITE) {
+ if (step.getAction() == DevicePackageRequest.Action.OVERWRITE) {
existing(tenantId, current, step);
prepareOverwrite(ruleChain, id, current, step);
// A rule chain the tenant made its root one stays the root
@@ -578,17 +735,17 @@ public class DefaultDevicePackageUpdateService extends AbstractTbEntityService i
return savedResult(tenantId, result.getId(), result, step, output(result.getId(), result.getName()));
}
- private StepResult saveConverter(TenantId tenantId, DeviceUpdateRequest.Step step, JsonNode entity) {
+ private StepResult saveConverter(TenantId tenantId, DevicePackageRequest.Step step, JsonNode entity) {
ConverterId id = step.getEntityId() != null ? new ConverterId(step.getEntityId()) : null;
Converter current = id != null ? converterService.findConverterById(tenantId, id) : null;
- if (step.getAction() == DeviceUpdateRequest.Action.KEEP) {
+ if (step.getAction() == DevicePackageRequest.Action.KEEP) {
existing(tenantId, current, step);
return kept(id, current.getName());
}
Converter converter = JacksonUtil.treeToValue(entity, Converter.class);
converter.setTenantId(tenantId);
converter.setType("UPLINK_CONVERTER".equals(step.getType()) ? ConverterType.UPLINK : ConverterType.DOWNLINK);
- if (step.getAction() == DeviceUpdateRequest.Action.OVERWRITE) {
+ if (step.getAction() == DevicePackageRequest.Action.OVERWRITE) {
existing(tenantId, current, step);
prepareOverwrite(converter, id, current, step);
} else {
@@ -599,10 +756,10 @@ public class DefaultDevicePackageUpdateService extends AbstractTbEntityService i
return savedResult(tenantId, result.getId(), result, step, output(result.getId(), result.getName()));
}
- private StepResult saveIntegration(TenantId tenantId, DeviceUpdateRequest.Step step, JsonNode entity) {
+ private StepResult saveIntegration(TenantId tenantId, DevicePackageRequest.Step step, JsonNode entity) {
IntegrationId id = step.getEntityId() != null ? new IntegrationId(step.getEntityId()) : null;
Integration current = id != null ? integrationService.findIntegrationById(tenantId, id) : null;
- if (step.getAction() == DeviceUpdateRequest.Action.KEEP) {
+ if (step.getAction() == DevicePackageRequest.Action.KEEP) {
existing(tenantId, current, step);
Integration merged = withMergedMetadata(current, step.getMetadata());
if (merged != null) {
@@ -613,7 +770,7 @@ public class DefaultDevicePackageUpdateService extends AbstractTbEntityService i
}
Integration integration = JacksonUtil.treeToValue(entity, Integration.class);
integration.setTenantId(tenantId);
- if (step.getAction() == DeviceUpdateRequest.Action.OVERWRITE) {
+ if (step.getAction() == DevicePackageRequest.Action.OVERWRITE) {
existing(tenantId, current, step);
prepareOverwrite(integration, id, current, step);
// The devices keep sending to the same endpoint
@@ -668,7 +825,7 @@ public class DefaultDevicePackageUpdateService extends AbstractTbEntityService i
/**
* A copy of the integration with the step's metadata entries merged into its metadata; null when that changes nothing.
- * A copy: the integration may be the cache's own instance, which a rolled back update must not change.
+ * A copy: the integration may be the cache's own instance, which a rolled back install or update must not change.
*/
private static Integration withMergedMetadata(Integration integration, JsonNode entries) {
if (entries == null || !entries.isObject() || entries.isEmpty()) {
@@ -698,7 +855,7 @@ public class DefaultDevicePackageUpdateService extends AbstractTbEntityService i
* The overwritten entity keeps its id and its current name (the user may have renamed it). The version the
* user reviewed makes the save fail if someone changed the entity since.
*/
- private void prepareOverwrite(Object entity, EntityId id, Object current, DeviceUpdateRequest.Step step) {
+ private void prepareOverwrite(Object entity, EntityId id, Object current, DevicePackageRequest.Step step) {
switch (entity) {
case DeviceProfile p -> { p.setId((DeviceProfileId) id); p.setName(((DeviceProfile) current).getName()); }
case Device d -> { d.setId((DeviceId) id); d.setName(((Device) current).getName()); }
@@ -715,9 +872,9 @@ public class DefaultDevicePackageUpdateService extends AbstractTbEntityService i
((HasVersion) entity).setVersion(currentVersion);
}
- private T existing(TenantId tenantId, T current, DeviceUpdateRequest.Step step) {
+ private T existing(TenantId tenantId, T current, DevicePackageRequest.Step step) {
if (current == null || !tenantId.equals(((HasTenantId) current).getTenantId())) {
- throw new IllegalArgumentException(step.getName() + " was deleted. Check the update again.");
+ throw new IllegalArgumentException(step.getName() + " was deleted meanwhile. Check the package again.");
}
return current;
}
@@ -745,9 +902,9 @@ public class DefaultDevicePackageUpdateService extends AbstractTbEntityService i
* transaction may come from the cache, which is evicted only after commit. A rule chain is read back with
* its metadata, which isn't cached.
*/
- private StepResult savedResult(TenantId tenantId, EntityId id, Object entity, DeviceUpdateRequest.Step step, ObjectNode output) {
+ private StepResult savedResult(TenantId tenantId, EntityId id, Object entity, DevicePackageRequest.Step step, ObjectNode output) {
String checksum = entity instanceof RuleChain ? packageEntities.checksum(tenantId, id) : EntityChecksum.of(entity);
- return new StepResult(id, output, checksum, new SavedEntity(id, entity, step.getAction() == DeviceUpdateRequest.Action.CREATE));
+ return new StepResult(id, output, checksum, new SavedEntity(id, entity, step.getAction() == DevicePackageRequest.Action.CREATE));
}
private static ObjectNode output(EntityId id, String name) {
@@ -775,7 +932,7 @@ public class DefaultDevicePackageUpdateService extends AbstractTbEntityService i
}
}
- /** Replaces ${.} of entities this update has saved, e.g. the id of a converter it created. */
+ /** Replaces ${.} of entities the request has saved, e.g. the id of a converter it created. */
static JsonNode resolvePlaceholders(JsonNode node, Map aliasOutputs) {
if (node == null) {
return null;
@@ -834,17 +991,29 @@ public class DefaultDevicePackageUpdateService extends AbstractTbEntityService i
return id != null && dashboardService.findDashboardById(tenantId, id) != null ? id : null;
}
- /** What isn't transactional: the audit log, version control and attributes. A failure here doesn't undo the update. */
+ /**
+ * What isn't transactional: the audit log, version control and attributes. A failure here doesn't undo the install
+ * or update.
+ */
private void afterCommit(SecurityUser user, TenantId tenantId, Applied applied) {
for (SavedEntity saved : applied.saved()) {
try {
- logEntityActionService.logEntityAction(tenantId, saved.id(), (HasName) saved.entity(),
+ CustomerId customerId = saved.entity() instanceof HasCustomerId owned ? owned.getCustomerId() : null;
+ logEntityActionService.logEntityAction(tenantId, saved.id(), (HasName) saved.entity(), customerId,
saved.created() ? ActionType.ADDED : ActionType.UPDATED, user);
if (saved.id().getEntityType() != EntityType.DEVICE) {
autoCommit(user, saved.id());
}
} catch (Exception e) {
- log.warn("[{}] Failed to log the device package update of {}", tenantId, saved.id(), e);
+ log.warn("[{}] Failed to log the device package change of {}", tenantId, saved.id(), e);
+ }
+ }
+ for (SavedEntity saved : applied.grouped()) {
+ try {
+ logEntityActionService.logEntityAction(tenantId, saved.id(), (HasName) saved.entity(), ((HasCustomerId) saved.entity()).getCustomerId(),
+ ActionType.ADDED_TO_ENTITY_GROUP, user, saved.id().toString(), applied.entityGroup().getId().toString(), applied.entityGroup().getName());
+ } catch (Exception e) {
+ log.warn("[{}] Failed to log adding {} to its entity group", tenantId, saved.id(), e);
}
}
for (StepAttributes step : applied.attributes()) {
@@ -855,7 +1024,7 @@ public class DefaultDevicePackageUpdateService extends AbstractTbEntityService i
log.warn("[{}] Failed to save the attributes of device package step [{}]", tenantId, step.stepName(), e);
}
}
- for (DeviceUpdateRequest.Step step : applied.connectorSteps()) {
+ for (DevicePackageRequest.Step step : applied.connectorSteps()) {
try {
saveConnector(tenantId, applied.aliasOutputs().get("gateway"), step.getEntity());
} catch (Exception e) {
@@ -903,9 +1072,20 @@ public class DefaultDevicePackageUpdateService extends AbstractTbEntityService i
* The message the wizard shows: the ones validation and limits give, as they are; anything else, e.g. a database
* error, as a common message, with the details in the log.
*/
+ static JsonNode limitOf(Throwable e) {
+ SubscriptionException subscription = ExceptionUtils.throwableOfType(e, SubscriptionException.class);
+ if (subscription != null) {
+ return JacksonUtil.valueToTree(ThingsboardErrorResponse.ofSubscriptionViolation(subscription.getMessage(), subscription.getErrorCode(),
+ subscription.getEntry(), subscription.getValue(), HttpStatus.FORBIDDEN));
+ }
+ EntitiesLimitExceededException entities = ExceptionUtils.throwableOfType(e, EntitiesLimitExceededException.class);
+ return entities == null ? null
+ : JacksonUtil.valueToTree(ThingsboardEntitiesLimitExceededResponse.of(entities.getMessage(), entities.getEntityType(), entities.getLimit()));
+ }
+
static String userMessage(Throwable e) {
if (e instanceof EntityVersionMismatchException) {
- return "Someone changed it while you were reviewing the update. Check the update again.";
+ return "Someone changed it meanwhile. Check the package again.";
}
if (e instanceof DataValidationException || e instanceof EntitiesLimitExceededException || e instanceof IllegalArgumentException
|| e instanceof SubscriptionException) {
@@ -927,29 +1107,7 @@ public class DefaultDevicePackageUpdateService extends AbstractTbEntityService i
*/
private static Set ownedIds(DeviceInstalledItemDescriptor descriptor) {
Set ids = new HashSet<>(createdIds(descriptor).keySet());
- ids.removeAll(usedExistingIds(descriptor).keySet());
- return ids;
- }
-
- /**
- * The entities the user chose to use as they were. An install made before the descriptor kept them has them only in
- * its install state, which the first update carries over into the descriptor.
- */
- private static Map usedExistingIds(DeviceInstalledItemDescriptor descriptor) {
- Map ids = new LinkedHashMap<>();
- if (descriptor.getUsedExistingEntityIds() != null) {
- descriptor.getUsedExistingEntityIds().forEach(id -> ids.put(id.getId(), id));
- return ids;
- }
- Map createdIds = createdIds(descriptor);
- if (descriptor.getInstallState() != null) {
- descriptor.getInstallState().values().forEach(state -> {
- UUID id = toUuid(state.path("entityOutput").path("id").asText());
- if (id != null && "use-existing".equals(state.path("resolution").asText()) && createdIds.containsKey(id)) {
- ids.put(id, createdIds.get(id));
- }
- });
- }
+ descriptor.getUsedExistingEntityIdsIncludingLegacy().forEach(id -> ids.remove(id.getId()));
return ids;
}
@@ -961,8 +1119,8 @@ public class DefaultDevicePackageUpdateService extends AbstractTbEntityService i
return ids;
}
- private static DeviceUpdateRequest.Step copyWithEntity(DeviceUpdateRequest.Step step, JsonNode entity) {
- DeviceUpdateRequest.Step copy = JacksonUtil.treeToValue(JacksonUtil.valueToTree(step), DeviceUpdateRequest.Step.class);
+ private static DevicePackageRequest.Step copyWithEntity(DevicePackageRequest.Step step, JsonNode entity) {
+ DevicePackageRequest.Step copy = JacksonUtil.treeToValue(JacksonUtil.valueToTree(step), DevicePackageRequest.Step.class);
if (entity != null) {
copy.setEntity(entity);
}
@@ -972,6 +1130,11 @@ public class DefaultDevicePackageUpdateService extends AbstractTbEntityService i
private record DevicePackage(IotHubInstalledItem installedItem, DeviceInstalledItemDescriptor descriptor) {
}
+ @FunctionalInterface
+ private interface PackageChange {
+ Applied apply() throws Exception;
+ }
+
private record StepResult(EntityId entityId, ObjectNode output, String checksum, SavedEntity saved) {
}
@@ -982,8 +1145,16 @@ public class DefaultDevicePackageUpdateService extends AbstractTbEntityService i
}
private record Applied(DeviceInstalledItemDescriptor descriptor, Map outputs, List saved,
- List connectorSteps, List attributes,
- Map aliasOutputs) {
+ List connectorSteps, List attributes,
+ Map aliasOutputs, EntityGroup entityGroup, List grouped) {
+ }
+
+ /**
+ * Where an install opened from a customer's or a device group's page puts its entities. A new device follows the
+ * group's customer when no customer is given, as a device saved into a group does; an update has none.
+ */
+ private record Placement(CustomerId customerId, CustomerId deviceCustomerId, EntityGroup entityGroup) {
+ static final Placement NONE = new Placement(null, null, null);
}
/** A step that failed: the transaction rolls back, and the wizard shows which step it was. */
diff --git a/application/src/main/java/org/thingsboard/server/service/iot_hub/DefaultIotHubService.java b/application/src/main/java/org/thingsboard/server/service/iot_hub/DefaultIotHubService.java
index ddbe8ec5d7..86f6456300 100644
--- a/application/src/main/java/org/thingsboard/server/service/iot_hub/DefaultIotHubService.java
+++ b/application/src/main/java/org/thingsboard/server/service/iot_hub/DefaultIotHubService.java
@@ -8,15 +8,22 @@ import com.fasterxml.jackson.databind.node.ObjectNode;
import jakarta.servlet.http.HttpServletRequest;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
+import org.apache.commons.lang3.exception.ExceptionUtils;
import org.springframework.stereotype.Service;
import org.thingsboard.common.util.ExceptionUtil;
import org.thingsboard.common.util.JacksonUtil;
import org.thingsboard.server.common.data.Customer;
+import org.thingsboard.server.common.data.Dashboard;
+import org.thingsboard.server.common.data.Device;
import org.thingsboard.server.common.data.DeviceProfile;
+import org.thingsboard.server.common.data.HasTenantId;
import org.thingsboard.server.common.data.EntityType;
import org.thingsboard.server.common.data.asset.AssetProfile;
import org.thingsboard.server.common.data.cf.CalculatedField;
import org.thingsboard.server.common.data.cf.CalculatedFieldType;
+import org.thingsboard.server.common.data.cf.configuration.ArgumentsBasedCalculatedFieldConfiguration;
+import org.thingsboard.server.common.data.cf.configuration.geofencing.GeofencingCalculatedFieldConfiguration;
+import org.thingsboard.server.common.data.converter.Converter;
import org.thingsboard.server.common.data.exception.ThingsboardException;
import org.thingsboard.server.common.data.group.EntityGroup;
import org.thingsboard.server.common.data.group.EntityGroupInfo;
@@ -43,6 +50,7 @@ import org.thingsboard.server.common.data.iot_hub.RuleChainInstalledItemDescript
import org.thingsboard.server.common.data.iot_hub.SolutionTemplateInstalledItemDescriptor;
import org.thingsboard.server.common.data.iot_hub.WidgetInstalledItemDescriptor;
import org.thingsboard.server.common.data.subscription.SubscriptionException;
+import org.thingsboard.server.exception.DataValidationException;
import org.thingsboard.server.exception.EntitiesLimitExceededException;
import org.thingsboard.server.common.data.page.PageData;
import org.thingsboard.server.common.data.page.PageLink;
@@ -91,8 +99,11 @@ import java.util.HexFormat;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
+import java.util.Objects;
import java.util.Set;
import java.util.UUID;
+import java.util.stream.Collectors;
+import java.util.stream.Stream;
@Service
@TbCoreComponent
@@ -251,7 +262,7 @@ public class DefaultIotHubService implements IotHubService {
}
private EntityGroupInfo checkEntityGroup(SecurityUser user, EntityGroupId entityGroupId) throws ThingsboardException {
- EntityGroupInfo entityGroup = entityGroupService.findEntityGroupInfoById(user.getTenantId(), entityGroupId);
+ EntityGroupInfo entityGroup = entityGroupService.findEntityGroupInfoByTenantIdAndId(user.getTenantId(), entityGroupId);
if (entityGroup == null) {
throw new IllegalArgumentException("Entity group with id [" + entityGroupId + "] is not found");
}
@@ -268,6 +279,7 @@ public class DefaultIotHubService implements IotHubService {
}
calculatedField.setId(null);
calculatedField.setTenantId(tenantId);
+ mapTenantReferences(calculatedField, tenantId);
if (data != null && data.has("entityId")) {
EntityId entityId = JacksonUtil.treeToValue(data.get("entityId"), EntityId.class);
calculatedField.setEntityId(entityId);
@@ -292,6 +304,7 @@ public class DefaultIotHubService implements IotHubService {
}
alarmRule.setId(null);
alarmRule.setTenantId(tenantId);
+ mapTenantReferences(alarmRule, tenantId);
if (data != null && data.has("entityId")) {
EntityId entityId = JacksonUtil.treeToValue(data.get("entityId"), EntityId.class);
alarmRule.setEntityId(entityId);
@@ -421,7 +434,7 @@ public class DefaultIotHubService implements IotHubService {
String itemType = installedItem.getItemType();
if ("DEVICE".equals(itemType)) {
- // Updated in one transaction from the install wizard of the new version, see DevicePackageUpdateService
+ // Updated in one transaction from the install wizard of the new version, see DevicePackageService
throw new IllegalArgumentException("A device package is updated by the install wizard of the new version");
}
IotHubInstalledItemDescriptor descriptor = installedItem.getDescriptor();
@@ -531,6 +544,7 @@ public class DefaultIotHubService implements IotHubService {
existing.setName(newCf.getName());
existing.setType(newCf.getType());
existing.setConfiguration(newCf.getConfiguration());
+ mapTenantReferences(existing, tenantId);
tbCalculatedFieldService.save(existing, user);
}
@@ -551,9 +565,26 @@ public class DefaultIotHubService implements IotHubService {
existing.setName(newCf.getName());
existing.setType(newCf.getType());
existing.setConfiguration(newCf.getConfiguration());
+ mapTenantReferences(existing, tenantId);
tbCalculatedFieldService.save(existing, user);
}
+ private void mapTenantReferences(CalculatedField calculatedField, TenantId tenantId) {
+ if (calculatedField.getConfiguration() instanceof GeofencingCalculatedFieldConfiguration geofencingCfg) {
+ geofencingCfg.getZoneGroups().values().forEach(zoneGroupConfiguration -> {
+ if (zoneGroupConfiguration.getRefEntityId() != null && zoneGroupConfiguration.getRefEntityId().getEntityType() == EntityType.TENANT) {
+ zoneGroupConfiguration.setRefEntityId(tenantId);
+ }
+ });
+ } else if (calculatedField.getConfiguration() instanceof ArgumentsBasedCalculatedFieldConfiguration argBasedConfig) {
+ argBasedConfig.getArguments().values().forEach(argument -> {
+ if (argument.getRefEntityId() != null && argument.getRefEntityId().getEntityType() == EntityType.TENANT) {
+ argument.setRefEntityId(tenantId);
+ }
+ });
+ }
+ }
+
private void updateRuleChain(TenantId tenantId, RuleChainInstalledItemDescriptor descriptor, byte[] fileData) throws Exception {
JsonNode json = JacksonUtil.toJsonNode(new String(fileData));
RuleChainMetaData metadata;
@@ -674,6 +705,8 @@ public class DefaultIotHubService implements IotHubService {
UUID itemId = UUID.fromString(versionInfo.get("itemId").asText());
String version = versionInfo.get("version").asText();
+ validateDevicePackageEntities(tenantId, descriptor);
+
IotHubInstalledItem installedItem = new IotHubInstalledItem();
installedItem.setTenantId(tenantId);
installedItem.setItemId(itemId);
@@ -720,7 +753,9 @@ public class DefaultIotHubService implements IotHubService {
/**
* Deletes what a device package created, except the entities another installed device package
* also uses (e.g. an integration it took over with Overwrite): deleting those would break that package,
- * and the ones the user had before and the package took as they were (use existing).
+ * and the ones the user had before and the package took as they were (use existing). A device profile that devices
+ * still use stays too, e.g. with the devices a LoRaWAN integration created, and any kept profile keeps what it refers
+ * to: TB deletes neither.
* A kept integration loses the metadata entries the package added.
*/
private void deleteDevicePackageEntities(TenantId tenantId, IotHubInstalledItemId installedItemId,
@@ -729,7 +764,7 @@ public class DefaultIotHubService implements IotHubService {
if (createdEntityIds == null || createdEntityIds.isEmpty()) {
return;
}
- Set usedExisting = usedExistingIds(descriptor);
+ Set usedExisting = descriptor.getUsedExistingEntityIdsIncludingLegacy().stream().map(EntityId::getId).collect(Collectors.toSet());
List otherPackages = new ArrayList<>();
Map> usedByOtherPackages = findEntitiesOfOtherDevicePackages(tenantId, installedItemId, otherPackages);
// An entity goes before what it refers to: a device before its profile, a profile before its default dashboard
@@ -737,22 +772,42 @@ public class DefaultIotHubService implements IotHubService {
List ordered = new ArrayList<>(createdEntityIds);
Collections.reverse(ordered);
ordered.sort(Comparator.comparingInt(id -> DELETE_ORDER.getOrDefault(id.getEntityType(), DELETE_ORDER.size())));
+ // What a kept profile refers to: its default rule chain and dashboard, which come after it in the order
+ Set referencedByKeptProfiles = new HashSet<>();
for (EntityId entityId : ordered) {
if (usedExisting.contains(entityId.getId())) {
log.info("[{}] Kept {} {}: the package took it as it was", tenantId, entityId.getEntityType(), entityId.getId());
removeIntegrationMetadata(tenantId, entityId, descriptor, otherPackages);
+ profileReferences(tenantId, entityId).forEach(reference -> referencedByKeptProfiles.add(reference.getId()));
continue;
}
Set usedBy = usedByOtherPackages.get(entityId.getId());
if (usedBy != null) {
log.info("[{}] Kept {} {}: installed device packages {} use it", tenantId, entityId.getEntityType(), entityId.getId(), usedBy);
removeIntegrationMetadata(tenantId, entityId, descriptor, otherPackages);
+ profileReferences(tenantId, entityId).forEach(reference -> referencedByKeptProfiles.add(reference.getId()));
+ continue;
+ }
+ if (referencedByKeptProfiles.contains(entityId.getId())) {
+ log.info("[{}] Kept {} {}: a kept device profile refers to it", tenantId, entityId.getEntityType(), entityId.getId());
+ continue;
+ }
+ // The package's own devices are deleted by now; the ones left came from elsewhere, e.g. a LoRaWAN integration
+ long devices = countProfileDevices(tenantId, entityId, Set.of());
+ if (devices > 0) {
+ log.info("[{}] Kept device profile {}: devices use it ({})", tenantId, entityId.getId(), devices);
+ profileReferences(tenantId, entityId).forEach(reference -> referencedByKeptProfiles.add(reference.getId()));
continue;
}
try {
deleteDevicePackageEntity(tenantId, entityId, user);
} catch (Exception e) {
- log.error("[{}] Failed to delete device package entity: {}", tenantId, entityId, e);
+ // A reference the package doesn't know of, e.g. a profile the user made later with the package's rule chain
+ if (ExceptionUtils.indexOfType(e, DataValidationException.class) >= 0) {
+ log.info("[{}] Kept {} {}: {}", tenantId, entityId.getEntityType(), entityId.getId(), ExceptionUtils.getRootCauseMessage(e));
+ } else {
+ log.error("[{}] Failed to delete device package entity: {}", tenantId, entityId, e);
+ }
}
}
}
@@ -773,8 +828,8 @@ public class DefaultIotHubService implements IotHubService {
return;
}
try {
- Integration integration = integrationService.findIntegrationById(tenantId, new IntegrationId(entityId.getId()));
- if (integration == null || !(integration.getConfiguration() != null
+ // Only an integration of this tenant: the id comes from the stored descriptor
+ if (!(findDevicePackageEntity(tenantId, entityId) instanceof Integration integration) || !(integration.getConfiguration() != null
&& integration.getConfiguration().get("metadata") instanceof ObjectNode metadata)
|| keys.stream().noneMatch(metadata::has)) {
return;
@@ -811,16 +866,26 @@ public class DefaultIotHubService implements IotHubService {
throw new IllegalArgumentException("Installed item not found");
}
List kept = new ArrayList<>();
+ List referenced = new ArrayList<>();
Set usedByItems = new HashSet<>();
int usedExistingCount = 0;
if (installedItem.getDescriptor() instanceof DeviceInstalledItemDescriptor dd && dd.getCreatedEntityIds() != null) {
- Set usedExisting = usedExistingIds(dd);
+ Set usedExisting = dd.getUsedExistingEntityIdsIncludingLegacy().stream().map(EntityId::getId).collect(Collectors.toSet());
Map> usedByOtherPackages = findEntitiesOfOtherDevicePackages(tenantId, installedItemId, new ArrayList<>());
+ // The delete removes these before the profiles, so they don't keep a profile; a kept device does
+ Set deletedDevices = new HashSet<>();
+ dd.getCreatedEntityIds().stream()
+ .filter(id -> id.getEntityType() == EntityType.DEVICE && !usedExisting.contains(id.getId()) && !usedByOtherPackages.containsKey(id.getId()))
+ .forEach(id -> deletedDevices.add(id.getId()));
+ Set created = new HashSet<>();
+ dd.getCreatedEntityIds().forEach(id -> created.add(id.getId()));
+ Set keptIds = new HashSet<>();
for (EntityId entityId : dd.getCreatedEntityIds()) {
Set usedBy = usedByOtherPackages.get(entityId.getId());
boolean taken = usedExisting.contains(entityId.getId());
if (usedBy != null || taken) {
- kept.add(new InstalledItemKeptEntities.KeptEntity(entityId, entityService.fetchEntityName(tenantId, entityId).orElse(null)));
+ kept.add(keptEntity(tenantId, entityId));
+ keptIds.add(entityId.getId());
}
if (usedBy != null) {
usedByItems.addAll(usedBy);
@@ -829,17 +894,65 @@ public class DefaultIotHubService implements IotHubService {
usedExistingCount++;
}
}
+ for (EntityId entityId : dd.getCreatedEntityIds()) {
+ if (!keptIds.contains(entityId.getId()) && countProfileDevices(tenantId, entityId, deletedDevices) > 0) {
+ referenced.add(keptEntity(tenantId, entityId));
+ keptIds.add(entityId.getId());
+ }
+ }
+ // A kept profile, for whatever reason, keeps what it refers to
+ for (EntityId entityId : dd.getCreatedEntityIds()) {
+ if (!keptIds.contains(entityId.getId())) {
+ continue;
+ }
+ for (EntityId reference : profileReferences(tenantId, entityId)) {
+ if (created.contains(reference.getId()) && keptIds.add(reference.getId())) {
+ referenced.add(keptEntity(tenantId, reference));
+ }
+ }
+ }
}
- return new InstalledItemKeptEntities(kept, usedByItems.size(), usedExistingCount);
+ return new InstalledItemKeptEntities(kept, usedByItems.size(), usedExistingCount, referenced);
}
- /** The entities the package took as they were at install (use existing); none for installs before 4.4.1 kept them. */
- private static Set usedExistingIds(DeviceInstalledItemDescriptor descriptor) {
- Set ids = new HashSet<>();
- if (descriptor.getUsedExistingEntityIds() != null) {
- descriptor.getUsedExistingEntityIds().forEach(id -> ids.add(id.getId()));
+ private InstalledItemKeptEntities.KeptEntity keptEntity(TenantId tenantId, EntityId entityId) {
+ String name = findDevicePackageEntity(tenantId, entityId) != null
+ ? entityService.fetchEntityName(tenantId, entityId).orElse(null) : null;
+ return new InstalledItemKeptEntities.KeptEntity(entityId, name);
+ }
+
+ /** The default rule chains and dashboard of a device profile, which TB doesn't delete while it refers to them; none for another entity. */
+ private List profileReferences(TenantId tenantId, EntityId profileId) {
+ List references = new ArrayList<>();
+ if (profileId.getEntityType() != EntityType.DEVICE_PROFILE) {
+ return references;
+ }
+ DeviceProfile profile = deviceProfileService.findDeviceProfileById(tenantId, new DeviceProfileId(profileId.getId()));
+ if (profile != null) {
+ Stream.of(profile.getDefaultRuleChainId(), profile.getDefaultEdgeRuleChainId(), profile.getDefaultDashboardId())
+ .filter(Objects::nonNull)
+ .forEach(references::add);
+ }
+ return references;
+ }
+
+ /**
+ * How many devices use the device profile {@code entityId}, apart from {@code excludedDevices}; 0 for another entity.
+ * TB doesn't delete a profile that devices use.
+ */
+ private long countProfileDevices(TenantId tenantId, EntityId entityId, Set excludedDevices) {
+ if (entityId.getEntityType() != EntityType.DEVICE_PROFILE) {
+ return 0;
}
- return ids;
+ DeviceProfileId profileId = new DeviceProfileId(entityId.getId());
+ long count = deviceService.findDeviceIdsByTenantIdAndDeviceProfileId(tenantId, profileId, new PageLink(1)).getTotalElements();
+ for (UUID deviceId : excludedDevices) {
+ Device device = deviceService.findDeviceById(tenantId, new DeviceId(deviceId));
+ if (device != null && profileId.equals(device.getDeviceProfileId())) {
+ count--;
+ }
+ }
+ return Math.max(count, 0);
}
/** The other installed device packages' entities, by id; the packages' descriptors go to {@code otherPackages}. */
@@ -864,36 +977,56 @@ public class DefaultIotHubService implements IotHubService {
return usedBy;
}
- private void deleteDevicePackageEntity(TenantId tenantId, EntityId entityId, SecurityUser user) throws ThingsboardException {
- switch (entityId.getEntityType()) {
- case DEVICE -> {
- var device = deviceService.findDeviceById(tenantId, new DeviceId(entityId.getId()));
- if (device != null) tbDeviceService.delete(device, user);
- }
- case DEVICE_PROFILE -> {
- var profile = deviceProfileService.findDeviceProfileById(tenantId, new DeviceProfileId(entityId.getId()));
- if (profile != null) tbDeviceProfileService.delete(profile, user);
- }
- case DASHBOARD -> {
- var dashboard = dashboardService.findDashboardById(tenantId, new DashboardId(entityId.getId()));
- if (dashboard != null) tbDashboardService.delete(dashboard, user);
- }
- case RULE_CHAIN -> {
- var ruleChain = ruleChainService.findRuleChainById(tenantId, new RuleChainId(entityId.getId()));
- if (ruleChain != null) tbRuleChainService.delete(ruleChain, user);
- }
- case INTEGRATION -> {
- IntegrationId integrationId = new IntegrationId(entityId.getId());
- var integration = integrationService.findIntegrationById(tenantId, integrationId);
- if (integration != null) {
- integrationService.deleteIntegration(tenantId, integrationId);
- }
- }
- case CONVERTER -> {
- var converter = converterService.findConverterById(tenantId, new ConverterId(entityId.getId()));
- if (converter != null) tbConverterService.delete(converter, user);
+ private void validateDevicePackageEntities(TenantId tenantId, DeviceInstalledItemDescriptor descriptor) {
+ if (descriptor == null) {
+ throw new IllegalArgumentException("Device package descriptor is required");
+ }
+ List entityIds = new ArrayList<>();
+ if (descriptor.getCreatedEntityIds() != null) {
+ entityIds.addAll(descriptor.getCreatedEntityIds());
+ }
+ if (descriptor.getDashboardId() != null) {
+ entityIds.add(descriptor.getDashboardId());
+ }
+ if (descriptor.getUsedExistingEntityIds() != null) {
+ entityIds.addAll(descriptor.getUsedExistingEntityIds());
+ }
+ for (EntityId entityId : entityIds) {
+ if (entityId == null || findDevicePackageEntity(tenantId, entityId) == null) {
+ throw new IllegalArgumentException("Device package entity not found: " + entityId);
}
- default -> log.warn("[{}] Unsupported entity type for device package delete: {}", tenantId, entityId.getEntityType());
+ }
+ }
+
+ private HasTenantId findDevicePackageEntity(TenantId tenantId, EntityId entityId) {
+ HasTenantId entity = switch (entityId.getEntityType()) {
+ case DEVICE -> deviceService.findDeviceById(tenantId, new DeviceId(entityId.getId()));
+ case DEVICE_PROFILE -> deviceProfileService.findDeviceProfileById(tenantId, new DeviceProfileId(entityId.getId()));
+ case DASHBOARD -> dashboardService.findDashboardById(tenantId, new DashboardId(entityId.getId()));
+ case RULE_CHAIN -> ruleChainService.findRuleChainById(tenantId, new RuleChainId(entityId.getId()));
+ case INTEGRATION -> integrationService.findIntegrationById(tenantId, new IntegrationId(entityId.getId()));
+ case CONVERTER -> converterService.findConverterById(tenantId, new ConverterId(entityId.getId()));
+ default -> null;
+ };
+ return entity != null && tenantId.equals(entity.getTenantId()) ? entity : null;
+ }
+
+ private void deleteDevicePackageEntity(TenantId tenantId, EntityId entityId, SecurityUser user) throws ThingsboardException {
+ HasTenantId entity = findDevicePackageEntity(tenantId, entityId);
+ if (entity instanceof Device device) {
+ tbDeviceService.delete(device, user);
+ } else if (entity instanceof DeviceProfile profile) {
+ tbDeviceProfileService.delete(profile, user);
+ } else if (entity instanceof Dashboard dashboard) {
+ tbDashboardService.delete(dashboard, user);
+ } else if (entity instanceof RuleChain ruleChain) {
+ tbRuleChainService.delete(ruleChain, user);
+ } else if (entity instanceof Integration integration) {
+ integrationService.deleteIntegration(tenantId, integration.getId());
+ } else if (entity instanceof Converter converter) {
+ tbConverterService.delete(converter, user);
+ } else {
+ log.warn("[{}] Skipped device package entity {}: not found", tenantId, entityId);
}
}
diff --git a/application/src/main/java/org/thingsboard/server/service/iot_hub/DeviceUpdateRequest.java b/application/src/main/java/org/thingsboard/server/service/iot_hub/DevicePackageRequest.java
similarity index 67%
rename from application/src/main/java/org/thingsboard/server/service/iot_hub/DeviceUpdateRequest.java
rename to application/src/main/java/org/thingsboard/server/service/iot_hub/DevicePackageRequest.java
index a62f556c57..f79f023672 100644
--- a/application/src/main/java/org/thingsboard/server/service/iot_hub/DeviceUpdateRequest.java
+++ b/application/src/main/java/org/thingsboard/server/service/iot_hub/DevicePackageRequest.java
@@ -10,28 +10,33 @@ import java.util.Map;
import java.util.UUID;
/**
- * The update of an installed device package as the install wizard planned it: the entity of each install step
- * of the new version, already resolved from its template, and what to do with it. The server applies all of it
- * in one transaction, together with the new version of the installed item, or nothing.
+ * The install or update of a device package as the install wizard planned it: the entity of each install step
+ * of the version being installed, already resolved from its template, and what to do with it. The server applies
+ * all of it in one transaction, together with the installed item, or nothing.
*/
@Data
-public class DeviceUpdateRequest {
+public class DevicePackageRequest {
private String versionId;
- // The version installed when the wizard planned the update; the update fails if the package changed since
+ // Update only: the version installed when the wizard planned the update, which fails if the package changed since
private UUID fromVersionId;
- // The install method of the new version's steps; the installed one when not set
+ // The install method of the steps; an update without it keeps the installed one
private String selectedInstallMethod;
// The form values of the install state, by step: the server adds the entities to it
private Map installState;
+ // Install only, from a customer's or a device group's page: the customer the device, the gateway and the dashboard
+ // go to, and the group the created device or gateway is added to. An update ignores them
+ private UUID customerId;
+ private UUID entityGroupId;
private List steps;
public enum Action {
- // Taken as it is: the new version doesn't change it, or the user kept an entity they had
+ // Taken as it is: an update's new version doesn't change it, or the user kept an entity they had
KEEP,
// Takes the entity from the step
OVERWRITE,
- // A new entity: new in this version, deleted since install, or a copy next to one with the same name
+ // A new entity: one the package installs, a step new in this version or deleted since install, or a copy
+ // next to one with the same name
CREATE
}
@@ -51,13 +56,13 @@ public class DeviceUpdateRequest {
private Long expectedVersion;
// The user confirmed overwriting an entity of another package or one they didn't install with this package
private boolean confirmed;
- // OVERWRITE and CREATE: the entity resolved from the template. ${.} of an entity this
- // update creates is left for the server, which knows its id only once it is created.
+ // OVERWRITE and CREATE: the entity resolved from the template. ${.} of an entity the
+ // request creates is left for the server, which knows its id only once it is created.
private JsonNode entity;
// DEVICE and GATEWAY: the credentials template, if any
private JsonNode credentials;
// OVERWRITE and CREATE: the attributes of the saved entity, written after the transaction. Like the entity,
- // they may keep ${.} of an entity this update creates.
+ // they may keep ${.} of an entity the request creates.
private JsonNode serverAttributes;
private JsonNode sharedAttributes;
// The resolution the install state records for it
@@ -65,7 +70,8 @@ public class DeviceUpdateRequest {
// INTEGRATION: the step's metadata entries, which the package's converter reads. A KEEP merges them into the
// integration, e.g. one the package took as it was; null removes an entry
private JsonNode metadata;
- // UPLINK_CONVERTER: the step takes ThingsBoard's default converter, which the install state records for the update check
+ // UPLINK_CONVERTER: the step takes ThingsBoard's default converter. The install state records it, so that a later
+ // update checks that converter against ThingsBoard's default one
private boolean defaultConverter;
/**
diff --git a/application/src/main/java/org/thingsboard/server/service/iot_hub/DeviceUpdateResult.java b/application/src/main/java/org/thingsboard/server/service/iot_hub/DevicePackageResult.java
similarity index 55%
rename from application/src/main/java/org/thingsboard/server/service/iot_hub/DeviceUpdateResult.java
rename to application/src/main/java/org/thingsboard/server/service/iot_hub/DevicePackageResult.java
index 5c8ec6e8d7..f7d75ff652 100644
--- a/application/src/main/java/org/thingsboard/server/service/iot_hub/DeviceUpdateResult.java
+++ b/application/src/main/java/org/thingsboard/server/service/iot_hub/DevicePackageResult.java
@@ -2,6 +2,7 @@
// SPDX-License-Identifier: BUSL-1.1
package org.thingsboard.server.service.iot_hub;
+import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import lombok.AllArgsConstructor;
import lombok.Data;
@@ -17,7 +18,7 @@ import java.util.Map;
@Data
@NoArgsConstructor
@AllArgsConstructor
-public class DeviceUpdateResult {
+public class DevicePackageResult {
private boolean success;
private String errorMessage;
@@ -25,13 +26,19 @@ public class DeviceUpdateResult {
private DeviceInstalledItemDescriptor descriptor;
// By install state key of the step: what the install instructions resolve, e.g. ${integration.httpEndpoint}, ${device.token}
private Map outputs;
+ // When a step failed on an entity or subscription limit: the same body ThingsBoard answers such a request with (403)
+ private JsonNode limit;
- public static DeviceUpdateResult success(DeviceInstalledItemDescriptor descriptor, Map outputs) {
- return new DeviceUpdateResult(true, null, null, descriptor, outputs);
+ public static DevicePackageResult success(DeviceInstalledItemDescriptor descriptor, Map outputs) {
+ return new DevicePackageResult(true, null, null, descriptor, outputs, null);
}
- public static DeviceUpdateResult error(String errorMessage, String failedStep) {
- return new DeviceUpdateResult(false, errorMessage, failedStep, null, null);
+ public static DevicePackageResult error(String errorMessage, String failedStep) {
+ return error(errorMessage, failedStep, null);
+ }
+
+ public static DevicePackageResult error(String errorMessage, String failedStep, JsonNode limit) {
+ return new DevicePackageResult(false, errorMessage, failedStep, null, null, limit);
}
}
diff --git a/application/src/main/java/org/thingsboard/server/service/iot_hub/DevicePackageUpdateService.java b/application/src/main/java/org/thingsboard/server/service/iot_hub/DevicePackageService.java
similarity index 59%
rename from application/src/main/java/org/thingsboard/server/service/iot_hub/DevicePackageUpdateService.java
rename to application/src/main/java/org/thingsboard/server/service/iot_hub/DevicePackageService.java
index 5688056c98..60103c6e01 100644
--- a/application/src/main/java/org/thingsboard/server/service/iot_hub/DevicePackageUpdateService.java
+++ b/application/src/main/java/org/thingsboard/server/service/iot_hub/DevicePackageService.java
@@ -7,13 +7,16 @@ import org.thingsboard.server.service.security.model.SecurityUser;
import java.util.List;
-/** Updates an installed device package to another version of its item. */
-public interface DevicePackageUpdateService {
+/** Installs a device package, or updates an installed one to another version of its item. */
+public interface DevicePackageService {
/** The package's entities as they are now: whether they still exist, changed since, or are shared. */
List check(SecurityUser user, IotHubInstalledItemId installedItemId);
+ /** Installs the version in one transaction, together with its installed item, or nothing. */
+ DevicePackageResult install(SecurityUser user, DevicePackageRequest request);
+
/** Applies the update in one transaction, together with the new version of the installed item, or nothing. */
- DeviceUpdateResult apply(SecurityUser user, IotHubInstalledItemId installedItemId, DeviceUpdateRequest request);
+ DevicePackageResult update(SecurityUser user, IotHubInstalledItemId installedItemId, DevicePackageRequest request);
}
diff --git a/application/src/main/java/org/thingsboard/server/service/iot_hub/InstalledItemKeptEntities.java b/application/src/main/java/org/thingsboard/server/service/iot_hub/InstalledItemKeptEntities.java
index ad517c5327..7c3cfdbeb7 100644
--- a/application/src/main/java/org/thingsboard/server/service/iot_hub/InstalledItemKeptEntities.java
+++ b/application/src/main/java/org/thingsboard/server/service/iot_hub/InstalledItemKeptEntities.java
@@ -9,7 +9,10 @@ import org.thingsboard.server.common.data.id.EntityId;
import java.util.List;
-/** What deleting an installed item keeps: what other installed items use too, and what the user had before it. */
+/**
+ * What deleting an installed item keeps: what other installed items use too, what the user had before it, and what other
+ * tenant entities refer to (a LoRaWAN integration creates its devices on the first uplink, not the package).
+ */
@Data
@NoArgsConstructor
@AllArgsConstructor
@@ -20,6 +23,9 @@ public class InstalledItemKeptEntities {
private int usedByItemsCount;
// How many of the kept entities the user had before and the package took as they were (use existing)
private int usedExistingCount;
+ // What other tenant entities refer to: the package's device profiles that devices use, and the default rule chains and
+ // dashboard of a kept profile. Apart from entities, which an update reads as shared with other packages
+ private List referencedEntities;
@Data
@NoArgsConstructor
diff --git a/application/src/main/java/org/thingsboard/server/service/iot_hub/IotHubRestClient.java b/application/src/main/java/org/thingsboard/server/service/iot_hub/IotHubRestClient.java
index a12470271f..b404844e70 100644
--- a/application/src/main/java/org/thingsboard/server/service/iot_hub/IotHubRestClient.java
+++ b/application/src/main/java/org/thingsboard/server/service/iot_hub/IotHubRestClient.java
@@ -1,12 +1,13 @@
// SPDX-FileCopyrightText: Copyright The ThingsBoard Authors
-// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Modifications Copyright ThingsBoard, Inc.
+// SPDX-License-Identifier: Apache-2.0 AND BUSL-1.1
package org.thingsboard.server.service.iot_hub;
import com.fasterxml.jackson.databind.JsonNode;
import jakarta.annotation.PostConstruct;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
-import org.springframework.boot.web.client.RestTemplateBuilder;
+import org.springframework.boot.restclient.RestTemplateBuilder;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
diff --git a/application/src/main/java/org/thingsboard/server/service/mail/TbMailSender.java b/application/src/main/java/org/thingsboard/server/service/mail/TbMailSender.java
index b7759287af..28b0d9d27c 100644
--- a/application/src/main/java/org/thingsboard/server/service/mail/TbMailSender.java
+++ b/application/src/main/java/org/thingsboard/server/service/mail/TbMailSender.java
@@ -106,6 +106,8 @@ public class TbMailSender extends JavaMailSenderImpl {
}
}
javaMailProperties.put(MAIL_PROP + protocol + ".starttls.enable", enableTls);
+ // Angus Mail checks the server identity unless this is set
+ javaMailProperties.put(MAIL_PROP + protocol + ".ssl.checkserveridentity", "false");
if (enableTls && jsonConfig.has("tlsVersion") && !jsonConfig.get("tlsVersion").isNull()) {
String tlsVersion = jsonConfig.get("tlsVersion").asText();
if (StringUtils.isNoneEmpty(tlsVersion)) {
diff --git a/application/src/main/java/org/thingsboard/server/service/notification/DefaultNotificationCenter.java b/application/src/main/java/org/thingsboard/server/service/notification/DefaultNotificationCenter.java
index 496afd8323..9625fa596e 100644
--- a/application/src/main/java/org/thingsboard/server/service/notification/DefaultNotificationCenter.java
+++ b/application/src/main/java/org/thingsboard/server/service/notification/DefaultNotificationCenter.java
@@ -114,6 +114,9 @@ public class DefaultNotificationCenter extends AbstractSubscriptionService imple
NotificationTemplate notificationTemplate;
if (request.getTemplateId() != null) {
notificationTemplate = notificationTemplateService.findNotificationTemplateById(tenantId, request.getTemplateId());
+ if (notificationTemplate != null && !isTenantOrSystem(tenantId, notificationTemplate.getTenantId())) {
+ notificationTemplate = null;
+ }
} else {
notificationTemplate = request.getTemplate();
}
@@ -126,7 +129,7 @@ public class DefaultNotificationCenter extends AbstractSubscriptionService imple
List targets = new ArrayList<>();
for (UUID targetId : request.getTargets()) {
NotificationTarget target = notificationTargetService.findNotificationTargetById(tenantId, new NotificationTargetId(targetId));
- if (target != null) {
+ if (target != null && tenantId.equals(target.getTenantId())) {
targets.add(target);
} else {
log.debug("Unknown notification target {} in request {}", targetId, request);
@@ -516,6 +519,10 @@ public class DefaultNotificationCenter extends AbstractSubscriptionService imple
return "notification";
}
+ private static boolean isTenantOrSystem(TenantId tenantId, TenantId ownerId) {
+ return tenantId.equals(ownerId) || ownerId.isSysTenantId();
+ }
+
@Autowired
public void setChannels(List channels, NotificationCenter webNotificationChannel) {
this.channels = channels.stream().collect(Collectors.toMap(NotificationChannel::getDeliveryMethod, c -> c));
diff --git a/application/src/main/java/org/thingsboard/server/service/notification/channels/MicrosoftTeamsNotificationChannel.java b/application/src/main/java/org/thingsboard/server/service/notification/channels/MicrosoftTeamsNotificationChannel.java
index 9c7f4b0721..6837db7846 100644
--- a/application/src/main/java/org/thingsboard/server/service/notification/channels/MicrosoftTeamsNotificationChannel.java
+++ b/application/src/main/java/org/thingsboard/server/service/notification/channels/MicrosoftTeamsNotificationChannel.java
@@ -10,7 +10,7 @@ import lombok.RequiredArgsConstructor;
import lombok.Setter;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang3.StringUtils;
-import org.springframework.boot.web.client.RestTemplateBuilder;
+import org.springframework.boot.restclient.RestTemplateBuilder;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
diff --git a/application/src/main/java/org/thingsboard/server/service/notification/provider/DefaultFirebaseService.java b/application/src/main/java/org/thingsboard/server/service/notification/provider/DefaultFirebaseService.java
index fdee2f9c41..a4dc0125ea 100644
--- a/application/src/main/java/org/thingsboard/server/service/notification/provider/DefaultFirebaseService.java
+++ b/application/src/main/java/org/thingsboard/server/service/notification/provider/DefaultFirebaseService.java
@@ -1,5 +1,6 @@
// SPDX-FileCopyrightText: Copyright The ThingsBoard Authors
-// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Modifications Copyright ThingsBoard, Inc.
+// SPDX-License-Identifier: Apache-2.0 AND BUSL-1.1
package org.thingsboard.server.service.notification.provider;
import com.github.benmanes.caffeine.cache.Cache;
@@ -52,8 +53,11 @@ public class DefaultFirebaseService implements FirebaseService {
}
});
+ // mutable-content lets the iOS app's notification service extension
+ // add the template icon to the push before iOS shows it
Aps.Builder apsConfig = Aps.builder()
- .setSound("default");
+ .setSound("default")
+ .setMutableContent(true);
if (badge != null) {
apsConfig.setBadge(badge);
}
diff --git a/application/src/main/java/org/thingsboard/server/service/resource/DefaultTbResourceService.java b/application/src/main/java/org/thingsboard/server/service/resource/DefaultTbResourceService.java
index 63c840e7e1..3d7e67456c 100644
--- a/application/src/main/java/org/thingsboard/server/service/resource/DefaultTbResourceService.java
+++ b/application/src/main/java/org/thingsboard/server/service/resource/DefaultTbResourceService.java
@@ -26,6 +26,7 @@ import org.thingsboard.server.common.data.permission.Resource;
import org.thingsboard.server.common.data.widget.WidgetTypeDetails;
import org.thingsboard.server.dao.resource.ImageService;
import org.thingsboard.server.dao.resource.ResourceService;
+import org.thingsboard.server.exception.DataValidationException;
import org.thingsboard.server.queue.util.TbCoreComponent;
import org.thingsboard.server.service.entitiy.AbstractTbEntityService;
import org.thingsboard.server.service.security.model.SecurityUser;
@@ -57,6 +58,22 @@ public class DefaultTbResourceService extends AbstractTbEntityService implements
@Override
public TbResourceInfo save(TbResource resource, SecurityUser user) throws ThingsboardException {
+ if (resource.getId() != null) {
+ TbResourceInfo existing = checkNotNull(resourceService.findResourceInfoById(resource.getTenantId(), resource.getId()));
+ if ((resource.getResourceType() != null && resource.getResourceType() != existing.getResourceType()) ||
+ (resource.getResourceSubType() != null && resource.getResourceSubType() != existing.getResourceSubType())) {
+ throw new DataValidationException("Resource type can't be changed");
+ }
+ resource.setTenantId(existing.getTenantId());
+ resource.setCustomerId(existing.getCustomerId());
+ resource.setResourceType(existing.getResourceType());
+ resource.setResourceSubType(existing.getResourceSubType());
+ resource.setResourceKey(existing.getResourceKey());
+ resource.setCreatedTime(existing.getCreatedTime());
+ if (resource.getData() == null) {
+ resource.setEtag(existing.getEtag());
+ }
+ }
if (resource.getResourceType() == ResourceType.IMAGE) {
throw new IllegalArgumentException("Image resource type is not supported");
}
diff --git a/application/src/main/java/org/thingsboard/server/service/scheduler/DefaultSchedulerService.java b/application/src/main/java/org/thingsboard/server/service/scheduler/DefaultSchedulerService.java
index 7cd5cc685c..9859d9052b 100644
--- a/application/src/main/java/org/thingsboard/server/service/scheduler/DefaultSchedulerService.java
+++ b/application/src/main/java/org/thingsboard/server/service/scheduler/DefaultSchedulerService.java
@@ -274,7 +274,7 @@ public class DefaultSchedulerService extends AbstractPartitionBasedService entityGroupFuture = entityGroupService.findEntityGroupInfoByIdAsync(currentUser.getTenantId(), new EntityGroupId(entityId.getId()));
+ ListenableFuture entityGroupFuture = entityGroupService.findEntityGroupInfoByTenantIdAndIdAsync(currentUser.getTenantId(), new EntityGroupId(entityId.getId()));
Futures.addCallback(entityGroupFuture, getCallback(callback, entityGroup -> {
if (entityGroup == null) {
return ValidationResult.entityNotFound("Entity group with requested id wasn't found!");
diff --git a/application/src/main/java/org/thingsboard/server/service/security/auth/AbstractJwtAuthenticationToken.java b/application/src/main/java/org/thingsboard/server/service/security/auth/AbstractJwtAuthenticationToken.java
index 2db08ca0b7..41af05e308 100644
--- a/application/src/main/java/org/thingsboard/server/service/security/auth/AbstractJwtAuthenticationToken.java
+++ b/application/src/main/java/org/thingsboard/server/service/security/auth/AbstractJwtAuthenticationToken.java
@@ -1,11 +1,15 @@
// SPDX-FileCopyrightText: Copyright The ThingsBoard Authors
-// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Modifications Copyright ThingsBoard, Inc.
+// SPDX-License-Identifier: Apache-2.0 AND BUSL-1.1
package org.thingsboard.server.service.security.auth;
import org.springframework.security.authentication.AbstractAuthenticationToken;
+import org.springframework.security.core.GrantedAuthority;
import org.thingsboard.server.service.security.model.SecurityUser;
import org.thingsboard.server.service.security.model.token.RawAccessJwtToken;
+import java.util.Collection;
+
public abstract class AbstractJwtAuthenticationToken extends AbstractAuthenticationToken {
private static final long serialVersionUID = -6212297506742428406L;
@@ -14,7 +18,7 @@ public abstract class AbstractJwtAuthenticationToken extends AbstractAuthenticat
private SecurityUser securityUser;
public AbstractJwtAuthenticationToken(RawAccessJwtToken unsafeToken) {
- super(null);
+ super((Collection extends GrantedAuthority>) null);
this.rawAccessToken = unsafeToken;
this.setAuthenticated(false);
}
diff --git a/application/src/main/java/org/thingsboard/server/service/security/auth/jwt/SkipPathRequestMatcher.java b/application/src/main/java/org/thingsboard/server/service/security/auth/jwt/SkipPathRequestMatcher.java
index 6ff5ef42be..fe4b9fc987 100644
--- a/application/src/main/java/org/thingsboard/server/service/security/auth/jwt/SkipPathRequestMatcher.java
+++ b/application/src/main/java/org/thingsboard/server/service/security/auth/jwt/SkipPathRequestMatcher.java
@@ -4,7 +4,7 @@
package org.thingsboard.server.service.security.auth.jwt;
import jakarta.servlet.http.HttpServletRequest;
-import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
+import org.springframework.security.web.servlet.util.matcher.PathPatternRequestMatcher;
import org.springframework.security.web.util.matcher.OrRequestMatcher;
import org.springframework.security.web.util.matcher.RequestMatcher;
import org.springframework.util.Assert;
@@ -19,8 +19,9 @@ public class SkipPathRequestMatcher implements RequestMatcher {
public SkipPathRequestMatcher(List pathsToSkip, List pathsToProcess) {
Assert.notNull(pathsToSkip, "List of paths to skip is required.");
- List skip = pathsToSkip.stream().map(AntPathRequestMatcher::new).collect(Collectors.toList());
- List process = pathsToProcess.stream().map(AntPathRequestMatcher::new).collect(Collectors.toList());
+ PathPatternRequestMatcher.Builder builder = PathPatternRequestMatcher.withDefaults();
+ List skip = pathsToSkip.stream().map(builder::matcher).collect(Collectors.toList());
+ List process = pathsToProcess.stream().map(builder::matcher).collect(Collectors.toList());
skipMatchers = new OrRequestMatcher(skip);
processMatchers = new OrRequestMatcher(process);
}
diff --git a/application/src/main/java/org/thingsboard/server/service/security/auth/oauth2/CustomOAuth2ClientMapper.java b/application/src/main/java/org/thingsboard/server/service/security/auth/oauth2/CustomOAuth2ClientMapper.java
index 95de1eda02..4730ebb2b0 100644
--- a/application/src/main/java/org/thingsboard/server/service/security/auth/oauth2/CustomOAuth2ClientMapper.java
+++ b/application/src/main/java/org/thingsboard/server/service/security/auth/oauth2/CustomOAuth2ClientMapper.java
@@ -1,11 +1,12 @@
// SPDX-FileCopyrightText: Copyright The ThingsBoard Authors
-// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Modifications Copyright ThingsBoard, Inc.
+// SPDX-License-Identifier: Apache-2.0 AND BUSL-1.1
package org.thingsboard.server.service.security.auth.oauth2;
import com.fasterxml.jackson.core.JsonProcessingException;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
-import org.springframework.boot.web.client.RestTemplateBuilder;
+import org.springframework.boot.restclient.RestTemplateBuilder;
import org.springframework.security.oauth2.client.authentication.OAuth2AuthenticationToken;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
@@ -28,7 +29,7 @@ public class CustomOAuth2ClientMapper extends AbstractOAuth2ClientMapper impleme
private static final String PROVIDER_ACCESS_TOKEN = "provider-access-token";
- private RestTemplateBuilder restTemplateBuilder = new RestTemplateBuilder();
+ private final RestTemplateBuilder restTemplateBuilder = new RestTemplateBuilder();
@Override
public SecurityUser getOrCreateUserByClientPrincipal(HttpServletRequest request, OAuth2AuthenticationToken token, String providerAccessToken, OAuth2Client auth2Client) {
@@ -37,15 +38,16 @@ public class CustomOAuth2ClientMapper extends AbstractOAuth2ClientMapper impleme
return getOrCreateSecurityUserFromOAuth2User(oauth2User, auth2Client);
}
- private synchronized OAuth2User getOAuth2User(OAuth2AuthenticationToken token, String providerAccessToken, OAuth2CustomMapperConfig custom) {
+ private OAuth2User getOAuth2User(OAuth2AuthenticationToken token, String providerAccessToken, OAuth2CustomMapperConfig custom) {
+ RestTemplateBuilder builder = restTemplateBuilder;
if (!StringUtils.isEmpty(custom.getUsername()) && !StringUtils.isEmpty(custom.getPassword())) {
- restTemplateBuilder = restTemplateBuilder.basicAuthentication(custom.getUsername(), custom.getPassword());
+ builder = builder.basicAuthentication(custom.getUsername(), custom.getPassword());
}
if (custom.isSendToken() && !StringUtils.isEmpty(providerAccessToken)) {
- restTemplateBuilder = restTemplateBuilder.defaultHeader(PROVIDER_ACCESS_TOKEN, providerAccessToken);
+ builder = builder.defaultHeader(PROVIDER_ACCESS_TOKEN, providerAccessToken);
}
- RestTemplate restTemplate = restTemplateBuilder.build();
+ RestTemplate restTemplate = builder.build();
String request;
try {
request = JacksonUtil.getObjectMapperWithJavaTimeModule().writeValueAsString(token.getPrincipal());
diff --git a/application/src/main/java/org/thingsboard/server/service/security/auth/oauth2/GithubOAuth2ClientMapper.java b/application/src/main/java/org/thingsboard/server/service/security/auth/oauth2/GithubOAuth2ClientMapper.java
index 1a0bd06dcf..065db93fc7 100644
--- a/application/src/main/java/org/thingsboard/server/service/security/auth/oauth2/GithubOAuth2ClientMapper.java
+++ b/application/src/main/java/org/thingsboard/server/service/security/auth/oauth2/GithubOAuth2ClientMapper.java
@@ -1,5 +1,6 @@
// SPDX-FileCopyrightText: Copyright The ThingsBoard Authors
-// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Modifications Copyright ThingsBoard, Inc.
+// SPDX-License-Identifier: Apache-2.0 AND BUSL-1.1
package org.thingsboard.server.service.security.auth.oauth2;
import jakarta.servlet.http.HttpServletRequest;
@@ -7,7 +8,7 @@ import lombok.Data;
import lombok.ToString;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.boot.web.client.RestTemplateBuilder;
+import org.springframework.boot.restclient.RestTemplateBuilder;
import org.springframework.security.oauth2.client.authentication.OAuth2AuthenticationToken;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
diff --git a/application/src/main/java/org/thingsboard/server/service/security/auth/pat/ApiKeyAuthenticationToken.java b/application/src/main/java/org/thingsboard/server/service/security/auth/pat/ApiKeyAuthenticationToken.java
index 98aff443a0..af4f2af719 100644
--- a/application/src/main/java/org/thingsboard/server/service/security/auth/pat/ApiKeyAuthenticationToken.java
+++ b/application/src/main/java/org/thingsboard/server/service/security/auth/pat/ApiKeyAuthenticationToken.java
@@ -1,12 +1,15 @@
// SPDX-FileCopyrightText: Copyright The ThingsBoard Authors
-// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Modifications Copyright ThingsBoard, Inc.
+// SPDX-License-Identifier: Apache-2.0 AND BUSL-1.1
package org.thingsboard.server.service.security.auth.pat;
import org.springframework.security.authentication.AbstractAuthenticationToken;
+import org.springframework.security.core.GrantedAuthority;
import org.thingsboard.server.service.security.model.SecurityUser;
import org.thingsboard.server.service.security.model.token.ApiKeyAuthRequest;
import java.io.Serial;
+import java.util.Collection;
public class ApiKeyAuthenticationToken extends AbstractAuthenticationToken {
@@ -17,7 +20,7 @@ public class ApiKeyAuthenticationToken extends AbstractAuthenticationToken {
private SecurityUser securityUser;
public ApiKeyAuthenticationToken(ApiKeyAuthRequest apiKeyAuthRequest) {
- super(null);
+ super((Collection extends GrantedAuthority>) null);
this.apiKeyAuthRequest = apiKeyAuthRequest;
setAuthenticated(false);
}
diff --git a/application/src/main/java/org/thingsboard/server/service/security/permission/CustomerUserPermissions.java b/application/src/main/java/org/thingsboard/server/service/security/permission/CustomerUserPermissions.java
index 632dae9836..56fdba5d93 100644
--- a/application/src/main/java/org/thingsboard/server/service/security/permission/CustomerUserPermissions.java
+++ b/application/src/main/java/org/thingsboard/server/service/security/permission/CustomerUserPermissions.java
@@ -25,6 +25,7 @@ import org.thingsboard.server.common.data.id.HasId;
import org.thingsboard.server.common.data.id.ReportTemplateId;
import org.thingsboard.server.common.data.id.TbResourceId;
import org.thingsboard.server.common.data.menu.CustomMenuInfo;
+import org.thingsboard.server.common.data.pat.ApiKeyInfo;
import org.thingsboard.server.common.data.permission.GroupPermission;
import org.thingsboard.server.common.data.permission.Operation;
import org.thingsboard.server.common.data.permission.Resource;
@@ -525,6 +526,9 @@ public class CustomerUserPermissions extends AbstractPermissions {
if (!user.getTenantId().equals(entity.getTenantId())) {
return false;
}
+ if (!(entity instanceof ApiKeyInfo apiKeyInfo) || !user.getId().equals(apiKeyInfo.getUserId())) {
+ return false;
+ }
// This entity does not have groups, so we are checking only generic level permissions
return user.getUserPermissions().hasGenericPermission(Resource.API_KEY, operation);
}
diff --git a/application/src/main/java/org/thingsboard/server/service/security/system/DefaultSystemSecurityService.java b/application/src/main/java/org/thingsboard/server/service/security/system/DefaultSystemSecurityService.java
index 5a582026fd..ff2185e91b 100644
--- a/application/src/main/java/org/thingsboard/server/service/security/system/DefaultSystemSecurityService.java
+++ b/application/src/main/java/org/thingsboard/server/service/security/system/DefaultSystemSecurityService.java
@@ -332,7 +332,7 @@ public class DefaultSystemSecurityService implements SystemSecurityService {
@Override
public AccessJwtToken createUserAccessToken(TenantId tenantId, UserId userId) throws ThingsboardException {
User user = userService.findUserById(tenantId, userId);
- if (user == null) {
+ if (user == null || !user.getTenantId().equals(tenantId)) {
throw new ThingsboardException("Configured user [id: " + userId + "] was not found in system. Please use other user credentials.", ThingsboardErrorCode.BAD_REQUEST_PARAMS);
}
UserCredentials credentials = userService.findUserCredentialsByUserId(tenantId, userId);
diff --git a/application/src/main/java/org/thingsboard/server/service/subscription/DefaultTbEntityDataSubscriptionService.java b/application/src/main/java/org/thingsboard/server/service/subscription/DefaultTbEntityDataSubscriptionService.java
index 742f9b22ec..4e8467cba5 100644
--- a/application/src/main/java/org/thingsboard/server/service/subscription/DefaultTbEntityDataSubscriptionService.java
+++ b/application/src/main/java/org/thingsboard/server/service/subscription/DefaultTbEntityDataSubscriptionService.java
@@ -422,7 +422,13 @@ public class DefaultTbEntityDataSubscriptionService implements TbEntityDataSubsc
List entities = ctx.getEntitiesData();
ctx.cancelTasks();
ctx.clearEntitySubscriptions();
- if (entities.isEmpty()) {
+ if (ctx.isOwnerScoped()) {
+ ctx.fetchAlarms();
+ TbAlarmDataSubCtx finalCtx = ctx;
+ ScheduledFuture> task = scheduler.scheduleWithFixedDelay(
+ () -> refreshAlarmQuery(finalCtx), dynamicPageLinkRefreshInterval, dynamicPageLinkRefreshInterval, TimeUnit.SECONDS);
+ finalCtx.setRefreshTask(task);
+ } else if (entities.isEmpty()) {
AlarmDataUpdate update = new AlarmDataUpdate(cmd.getCmdId(), new PageData<>(), null, 0, 0);
ctx.sendWsMsg(update);
} else {
diff --git a/application/src/main/java/org/thingsboard/server/service/subscription/TbAbstractDataSubCtx.java b/application/src/main/java/org/thingsboard/server/service/subscription/TbAbstractDataSubCtx.java
index 6306ad7ab3..10db008227 100644
--- a/application/src/main/java/org/thingsboard/server/service/subscription/TbAbstractDataSubCtx.java
+++ b/application/src/main/java/org/thingsboard/server/service/subscription/TbAbstractDataSubCtx.java
@@ -66,6 +66,9 @@ public abstract class TbAbstractDataSubCtx newDataMap) {
+ }
+
@Override
protected synchronized void update() {
PageData newData = findEntityData();
@@ -78,6 +81,7 @@ public abstract class TbAbstractDataSubCtx newDataMap = newData.getData().stream().collect(Collectors.toMap(EntityData::getEntityId, Function.identity(), (a, b) -> a));
if (oldDataMap.size() == newDataMap.size() && oldDataMap.keySet().equals(newDataMap.keySet())) {
log.trace("[{}][{}] No updates to entity data found", sessionRef.getSessionId(), cmdId);
+ onSameEntities(newDataMap);
} else {
this.data = newData;
doUpdate(newDataMap);
diff --git a/application/src/main/java/org/thingsboard/server/service/subscription/TbAlarmDataSubCtx.java b/application/src/main/java/org/thingsboard/server/service/subscription/TbAlarmDataSubCtx.java
index 3b7c0824c1..fb2bef81ef 100644
--- a/application/src/main/java/org/thingsboard/server/service/subscription/TbAlarmDataSubCtx.java
+++ b/application/src/main/java/org/thingsboard/server/service/subscription/TbAlarmDataSubCtx.java
@@ -101,7 +101,10 @@ public class TbAlarmDataSubCtx extends TbAbstractDataSubCtx {
return;
}
AlarmDataUpdate update;
- if (!entitiesMap.isEmpty()) {
+ if (isOwnerScoped()) {
+ setAndMergeAlarmsData(findOwnerAlarms());
+ update = new AlarmDataUpdate(cmdId, alarms, null, maxEntitiesPerAlarmSubscription, 0);
+ } else if (!entitiesMap.isEmpty()) {
long start = System.currentTimeMillis();
PageData alarms = alarmService.findAlarmDataByQueryForEntities(getTenantId(),
getMergedUserPermissions(), query, getOrderedEntityIds());
@@ -116,9 +119,39 @@ public class TbAlarmDataSubCtx extends TbAbstractDataSubCtx {
sendWsMsg(update);
}
+ public boolean isOwnerScoped() {
+ return query != null && query.getEntityFilter() == null;
+ }
+
+ private PageData findOwnerAlarms() {
+ long start = System.currentTimeMillis();
+ PageData result = alarmService.findAlarmDataByQuery(getTenantId(), getCustomerId(), getMergedUserPermissions(), query);
+ stats.getAlarmQueryInvocationCnt().incrementAndGet();
+ stats.getAlarmQueryTimeSpent().addAndGet(System.currentTimeMillis() - start);
+ return result;
+ }
+
+ private void refreshOwnerAlarms() {
+ if (stopped) {
+ return;
+ }
+ PageData fresh = findOwnerAlarms();
+ if (alarms != null && alarms.getTotalElements() == fresh.getTotalElements() && alarms.getData().equals(fresh.getData())) {
+ return;
+ }
+ setAndMergeAlarmsData(fresh);
+ sendWsMsg(new AlarmDataUpdate(cmdId, alarms, null, maxEntitiesPerAlarmSubscription, 0));
+ }
+
public void fetchData() {
resetInvocationCounter();
log.trace("[{}] Fetching data: {}", cmdId, alarmInvocationAttempts);
+ if (isOwnerScoped()) {
+ data = PageData.emptyPageData();
+ entitiesMap.clear();
+ tooManyEntities = false;
+ return;
+ }
super.fetchData();
entitiesMap.clear();
tooManyEntities = data.hasNext();
@@ -232,6 +265,9 @@ public class TbAlarmDataSubCtx extends TbAbstractDataSubCtx {
}
public void cleanupOldAlarms() {
+ if (query.getPageLink().getTimeWindow() <= 0) {
+ return;
+ }
long expTime = System.currentTimeMillis() - query.getPageLink().getTimeWindow();
boolean shouldRefresh = false;
for (AlarmData alarmData : alarms.getData()) {
@@ -248,7 +284,7 @@ public class TbAlarmDataSubCtx extends TbAbstractDataSubCtx {
private boolean filter(Alarm alarm) {
AlarmDataPageLink filter = query.getPageLink();
long startTs = System.currentTimeMillis() - filter.getTimeWindow();
- if (alarm.getCreatedTime() < startTs) {
+ if (filter.getTimeWindow() > 0 && alarm.getCreatedTime() < startTs) {
//Skip update that does not match time window.
return false;
}
@@ -292,6 +328,11 @@ public class TbAlarmDataSubCtx extends TbAbstractDataSubCtx {
}
public synchronized void checkAndResetInvocationCounter() {
+ if (isOwnerScoped()) {
+ resetInvocationCounter();
+ refreshOwnerAlarms();
+ return;
+ }
boolean fetchNeeded = this.alarmInvocationAttempts > maxAlarmQueriesPerRefreshInterval;
resetInvocationCounter();
if (fetchNeeded) {
diff --git a/application/src/main/java/org/thingsboard/server/service/subscription/TbEntityDataSubCtx.java b/application/src/main/java/org/thingsboard/server/service/subscription/TbEntityDataSubCtx.java
index 1197da0d09..fa599ecac0 100644
--- a/application/src/main/java/org/thingsboard/server/service/subscription/TbEntityDataSubCtx.java
+++ b/application/src/main/java/org/thingsboard/server/service/subscription/TbEntityDataSubCtx.java
@@ -3,6 +3,7 @@
// SPDX-License-Identifier: Apache-2.0 AND BUSL-1.1
package org.thingsboard.server.service.subscription;
+import java.util.Objects;
import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
@@ -177,6 +178,38 @@ public class TbEntityDataSubCtx extends TbAbstractDataSubCtx {
});
}
+ @Override
+ protected void onSameEntities(Map newDataMap) {
+ List changed = new ArrayList<>();
+ for (EntityData current : data.getData()) {
+ EntityData fresh = newDataMap.get(current.getEntityId());
+ Map freshFields = fresh != null && fresh.getLatest() != null ? fresh.getLatest().get(EntityKeyType.ENTITY_FIELD) : null;
+ if (freshFields == null || freshFields.isEmpty() || current.getLatest() == null) {
+ continue;
+ }
+ if (!sameFieldValues(current.getLatest().get(EntityKeyType.ENTITY_FIELD), freshFields)) {
+ current.getLatest().put(EntityKeyType.ENTITY_FIELD, freshFields);
+ changed.add(new EntityData(current.getEntityId(), false, false, Map.of(EntityKeyType.ENTITY_FIELD, freshFields), null));
+ }
+ }
+ if (!changed.isEmpty()) {
+ sendWsMsg(new EntityDataUpdate(cmdId, null, changed, maxEntitiesPerDataSubscription));
+ }
+ }
+
+ private static boolean sameFieldValues(Map current, Map fresh) {
+ if (current == null || current.size() != fresh.size()) {
+ return false;
+ }
+ for (Map.Entry entry : fresh.entrySet()) {
+ TsValue value = current.get(entry.getKey());
+ if (value == null || !Objects.equals(value.getValue(), entry.getValue().getValue())) {
+ return false;
+ }
+ }
+ return true;
+ }
+
@Override
public synchronized void doUpdate(Map newDataMap) {
this.updateLatestTsData(this.data);
diff --git a/application/src/main/java/org/thingsboard/server/service/trendz/TrendzClient.java b/application/src/main/java/org/thingsboard/server/service/trendz/TrendzClient.java
index d5ecca2d90..5282b0df56 100644
--- a/application/src/main/java/org/thingsboard/server/service/trendz/TrendzClient.java
+++ b/application/src/main/java/org/thingsboard/server/service/trendz/TrendzClient.java
@@ -7,7 +7,7 @@ import jakarta.annotation.PostConstruct;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
-import org.springframework.boot.web.client.RestTemplateBuilder;
+import org.springframework.boot.restclient.RestTemplateBuilder;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
diff --git a/application/src/main/java/org/thingsboard/server/utils/MiscUtils.java b/application/src/main/java/org/thingsboard/server/utils/MiscUtils.java
index 7bb4775f16..bec30a395e 100644
--- a/application/src/main/java/org/thingsboard/server/utils/MiscUtils.java
+++ b/application/src/main/java/org/thingsboard/server/utils/MiscUtils.java
@@ -1,5 +1,6 @@
// SPDX-FileCopyrightText: Copyright The ThingsBoard Authors
-// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Modifications Copyright ThingsBoard, Inc.
+// SPDX-License-Identifier: Apache-2.0 AND BUSL-1.1
package org.thingsboard.server.utils;
import com.google.common.hash.HashFunction;
@@ -43,13 +44,20 @@ public class MiscUtils {
getPort(request));
}
- public static String getScheme(HttpServletRequest request){
- String scheme = request.getScheme();
+ public static String getScheme(HttpServletRequest request) {
String forwardedProto = request.getHeader("x-forwarded-proto");
- if (forwardedProto != null) {
- scheme = forwardedProto;
+ if (isHttpScheme(forwardedProto)) {
+ return forwardedProto.toLowerCase();
+ }
+ String scheme = request.getScheme();
+ if (forwardedProto == null && isHttpScheme(scheme)) {
+ return scheme.toLowerCase();
}
- return scheme;
+ return request.isSecure() ? "https" : "http";
+ }
+
+ private static boolean isHttpScheme(String scheme) {
+ return "http".equalsIgnoreCase(scheme) || "https".equalsIgnoreCase(scheme);
}
public static String getDomainName(HttpServletRequest request){
diff --git a/application/src/main/resources/thingsboard.yml b/application/src/main/resources/thingsboard.yml
index 992977aa83..35ba0f140d 100644
--- a/application/src/main/resources/thingsboard.yml
+++ b/application/src/main/resources/thingsboard.yml
@@ -13,6 +13,9 @@ server:
port: "${HTTP_BIND_PORT:8080}"
# Server forward headers strategy. Required for SWAGGER UI when reverse proxy is used
forward_headers_strategy: "${HTTP_FORWARD_HEADERS_STRATEGY:framework}"
+ tomcat:
+ # Maximum number of GET and POST request parameters Tomcat parses per request
+ max-parameter-count: "${SERVER_TOMCAT_MAX_PARAMETER_COUNT:10000}"
# Server SSL configuration
ssl:
# Enable/disable SSL support
@@ -1205,16 +1208,15 @@ spring.mvc.cors:
allow-credentials: "${TB_CORS_ALLOW_CREDENTIALS:true}"
# General spring parameters
-# Miscellaneous Spring Boot settings including circular references, Freemarker, async request timeout, path matching strategy, and static resource chain.
+# Miscellaneous Spring Boot settings including circular references, Freemarker, async request timeout, and path matching strategy.
spring.main.allow-circular-references: "true" # Spring Boot configuration property that controls whether circular dependencies between beans are allowed.
spring.freemarker.checkTemplateLocation: "false" # spring freemarker configuration
spring.mvc.async.request-timeout: "${SPRING_MVC_ASYNC_REQUEST_TIMEOUT:30000}" # The default timeout for asynchronous requests in milliseconds
spring.mvc.pathmatch.matching-strategy: "ANT_PATH_MATCHER" # For endpoints matching in Swagger
-spring.resources.chain:
- compressed: "true" # This property enables or disables support for serving pre-compressed resources (for example, a .gzip or .br file)
- strategy:
- content:
- enabled: "true" # This property enables or disables the content Version Strategy. This strategy allows Spring to generate a unique version for static resources, which is based on the content of the resource
+spring.http.converters.preferred-json-mapper: "jackson2" # JSON mapper for HTTP message conversion; ThingsBoard uses Jackson 2
+spring.web.resources.chain:
+ enabled: "true" # Enables the Spring resource chain explicitly instead of relying on a webjars locator being on the classpath
+ compressed: "true" # Serve the pre-compressed .br/.gz copies of the UI files built by ui-ngx when the client accepts them
spring.servlet.multipart.max-file-size: "${SPRING_SERVLET_MULTIPART_MAX_FILE_SIZE:50MB}" # Total file size cannot exceed 50MB when configuring file uploads
spring.servlet.multipart.max-request-size: "${SPRING_SERVLET_MULTIPART_MAX_REQUEST_SIZE:50MB}" # Total request size for a multipart/form-data cannot exceed 50MB
@@ -2554,7 +2556,7 @@ queue:
# Statistics printing interval for Edge services
print-interval-ms: "${TB_QUEUE_EDGE_STATS_PRINT_INTERVAL_MS:60000}"
integration:
- # Name of hash function used for consistent hash ring in Cluster Mode. See architecture docs for more details. Valid values - murmur3_32, murmur3_128 or sha256
+ # Number of partitions in each integration queue; there is one queue per integration type. Must match TB_QUEUE_INTEGRATION_PARTITIONS on the Integration Executors, otherwise downlinks, integration validation and Check connection may not reach the executor that runs the integration.
partitions: "${TB_QUEUE_INTEGRATION_PARTITIONS:3}"
# For high-priority notifications that require minimum latency and processing time
notifications_topic: "${TB_QUEUE_INTEGRATION_NOTIFICATIONS_TOPIC:tb_integration_executor.notifications}"
diff --git a/application/src/test/java/org/thingsboard/server/actors/rule/DefaultTbContextTest.java b/application/src/test/java/org/thingsboard/server/actors/rule/DefaultTbContextTest.java
index 4d17129844..c6f59216ac 100644
--- a/application/src/test/java/org/thingsboard/server/actors/rule/DefaultTbContextTest.java
+++ b/application/src/test/java/org/thingsboard/server/actors/rule/DefaultTbContextTest.java
@@ -1,5 +1,6 @@
// SPDX-FileCopyrightText: Copyright The ThingsBoard Authors
-// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Modifications Copyright ThingsBoard, Inc.
+// SPDX-License-Identifier: Apache-2.0 AND BUSL-1.1
package org.thingsboard.server.actors.rule;
import org.junit.jupiter.api.BeforeEach;
@@ -20,12 +21,18 @@ import org.thingsboard.server.actors.ruleChain.RuleChainOutputMsg;
import org.thingsboard.server.actors.ruleChain.RuleNodeCtx;
import org.thingsboard.server.actors.ruleChain.RuleNodeToRuleChainTellNextMsg;
import org.thingsboard.server.cluster.TbClusterService;
+import org.thingsboard.server.common.adaptor.JsonConverter;
import org.thingsboard.server.common.data.DataConstants;
import org.thingsboard.server.common.data.debug.DebugSettings;
import org.thingsboard.server.common.data.id.EntityId;
import org.thingsboard.server.common.data.id.RuleChainId;
import org.thingsboard.server.common.data.id.RuleNodeId;
import org.thingsboard.server.common.data.id.TenantId;
+import org.thingsboard.server.common.data.kv.AttributeKvEntry;
+import org.thingsboard.server.common.data.kv.BaseAttributeKvEntry;
+import org.thingsboard.server.common.data.kv.DataType;
+import org.thingsboard.server.common.data.kv.LongDataEntry;
+import org.thingsboard.server.common.data.kv.StringDataEntry;
import org.thingsboard.server.common.data.msg.TbMsgType;
import org.thingsboard.server.common.data.msg.TbNodeConnectionType;
import org.thingsboard.server.common.data.rule.RuleNode;
@@ -41,10 +48,12 @@ import org.thingsboard.server.queue.common.SimpleTbQueueCallback;
import java.util.Collections;
import java.util.List;
+import java.util.Map;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.function.Consumer;
+import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.Stream;
@@ -1093,6 +1102,35 @@ class DefaultTbContextTest {
.build();
}
+ @Test
+ public void givenSavedStringAttributes_whenAttributesUpdatedActionMsg_thenNumericStringsStayStringsWhenParsed() {
+ List attributes = List.of(
+ new BaseAttributeKvEntry(new StringDataEntry("joinEui", "0000000000000000"), 0L),
+ new BaseAttributeKvEntry(new StringDataEntry("devEui", "70B3D57ED0012345"), 0L),
+ new BaseAttributeKvEntry(new LongDataEntry("fCnt", 42L), 0L));
+
+ TbMsg msg = defaultTbContext.attributesUpdatedActionMsg(TENANT_ID, RULE_NODE_ID, DataConstants.CLIENT_SCOPE, attributes);
+
+ assertThat(msg.getType()).isEqualTo(TbMsgType.ATTRIBUTES_UPDATED.name());
+ assertThat(msg.getMetaData().getValue(DataConstants.SCOPE)).isEqualTo(DataConstants.CLIENT_SCOPE);
+ assertThat(msg.getMetaData().getValue(TbMsgMetaData.TYPE_CAST_DISABLED_KEYS)).isEqualTo("[\"joinEui\"]");
+ Map parsed = JsonConverter.attributesFromMsg(msg).stream()
+ .collect(Collectors.toMap(AttributeKvEntry::getKey, Function.identity()));
+ assertThat(parsed.get("joinEui").getDataType()).isEqualTo(DataType.STRING);
+ assertThat(parsed.get("joinEui").getValue()).isEqualTo("0000000000000000");
+ assertThat(parsed.get("devEui").getDataType()).isEqualTo(DataType.STRING);
+ assertThat(parsed.get("fCnt").getDataType()).isEqualTo(DataType.LONG);
+ }
+
+ @Test
+ public void givenNoNumericStringAttributes_whenAttributesUpdatedActionMsg_thenNoTypeCastDisabledKeys() {
+ List attributes = List.of(new BaseAttributeKvEntry(new LongDataEntry("fCnt", 42L), 0L));
+
+ TbMsg msg = defaultTbContext.attributesUpdatedActionMsg(TENANT_ID, RULE_NODE_ID, DataConstants.CLIENT_SCOPE, attributes);
+
+ assertThat(msg.getMetaData().getValue(TbMsgMetaData.TYPE_CAST_DISABLED_KEYS)).isNull();
+ }
+
private TbMsg getTbMsgWithQueueName() {
return TbMsg.newMsg()
.queueName(DataConstants.MAIN_QUEUE_NAME)
diff --git a/application/src/test/java/org/thingsboard/server/cf/AlarmRulesTest.java b/application/src/test/java/org/thingsboard/server/cf/AlarmRulesTest.java
index b195e76b71..c5acf4f6b9 100644
--- a/application/src/test/java/org/thingsboard/server/cf/AlarmRulesTest.java
+++ b/application/src/test/java/org/thingsboard/server/cf/AlarmRulesTest.java
@@ -70,8 +70,8 @@ import java.util.function.Consumer;
import java.util.function.Predicate;
import static org.assertj.core.api.Assertions.assertThat;
+import static org.awaitility.Awaitility.await;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
-import static org.testcontainers.shaded.org.awaitility.Awaitility.await;
@Slf4j
@DaoSqlTest
diff --git a/application/src/test/java/org/thingsboard/server/cf/CalculatedFieldIntegrationTest.java b/application/src/test/java/org/thingsboard/server/cf/CalculatedFieldIntegrationTest.java
index 01132b8004..a518a9e307 100644
--- a/application/src/test/java/org/thingsboard/server/cf/CalculatedFieldIntegrationTest.java
+++ b/application/src/test/java/org/thingsboard/server/cf/CalculatedFieldIntegrationTest.java
@@ -9,10 +9,10 @@ import com.fasterxml.jackson.databind.node.NullNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.google.common.util.concurrent.Futures;
import lombok.extern.slf4j.Slf4j;
+import org.apache.commons.lang3.RandomStringUtils;
import org.junit.Test;
import org.springframework.test.context.bean.override.mockito.MockitoSpyBean;
import org.springframework.test.context.TestPropertySource;
-import org.testcontainers.shaded.org.apache.commons.lang3.RandomStringUtils;
import org.thingsboard.common.util.JacksonUtil;
import org.thingsboard.server.common.data.AttributeScope;
import org.thingsboard.server.common.data.Device;
diff --git a/application/src/test/java/org/thingsboard/server/config/CustomOAuth2AuthorizationRequestResolverTest.java b/application/src/test/java/org/thingsboard/server/config/CustomOAuth2AuthorizationRequestResolverTest.java
new file mode 100644
index 0000000000..a8723cc54d
--- /dev/null
+++ b/application/src/test/java/org/thingsboard/server/config/CustomOAuth2AuthorizationRequestResolverTest.java
@@ -0,0 +1,57 @@
+// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc.
+// SPDX-License-Identifier: BUSL-1.1
+package org.thingsboard.server.config;
+
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.ExtendWith;
+import org.mockito.InjectMocks;
+import org.mockito.Mock;
+import org.mockito.junit.jupiter.MockitoExtension;
+import org.springframework.mock.web.MockHttpServletRequest;
+import org.springframework.security.oauth2.client.registration.ClientRegistration;
+import org.springframework.security.oauth2.client.registration.ClientRegistrationRepository;
+import org.springframework.security.oauth2.core.AuthorizationGrantType;
+import org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationRequest;
+import org.springframework.security.oauth2.core.endpoint.OAuth2ParameterNames;
+import org.thingsboard.server.dao.oauth2.OAuth2ClientService;
+import org.thingsboard.server.service.security.model.token.OAuth2AppTokenFactory;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.mockito.BDDMockito.given;
+import static org.mockito.Mockito.verifyNoInteractions;
+
+@ExtendWith(MockitoExtension.class)
+class CustomOAuth2AuthorizationRequestResolverTest {
+
+ @Mock
+ private ClientRegistrationRepository clientRegistrationRepository;
+ @Mock
+ private OAuth2ClientService oAuth2ClientService;
+ @Mock
+ private OAuth2AppTokenFactory oAuth2AppTokenFactory;
+ @InjectMocks
+ private CustomOAuth2AuthorizationRequestResolver resolver;
+
+ @Test
+ void resolvesTheRegistrationIdFromTheAuthorizationPath() {
+ given(clientRegistrationRepository.findByRegistrationId("abc-123")).willReturn(ClientRegistration.withRegistrationId("abc-123")
+ .clientId("client")
+ .authorizationGrantType(AuthorizationGrantType.AUTHORIZATION_CODE)
+ .redirectUri("{baseUrl}/login/oauth2/code/")
+ .authorizationUri("https://idp.example.com/authorize")
+ .tokenUri("https://idp.example.com/token")
+ .build());
+
+ OAuth2AuthorizationRequest request = resolver.resolve(new MockHttpServletRequest("GET", "/oauth2/authorization/abc-123"));
+
+ assertThat(request.getAttributes()).containsEntry(OAuth2ParameterNames.REGISTRATION_ID, "abc-123");
+ assertThat(request.getAuthorizationUri()).isEqualTo("https://idp.example.com/authorize");
+ }
+
+ @Test
+ void ignoresDeeperPaths() {
+ assertThat(resolver.resolve(new MockHttpServletRequest("GET", "/oauth2/authorization/abc/extra"))).isNull();
+ verifyNoInteractions(clientRegistrationRepository);
+ }
+
+}
diff --git a/application/src/test/java/org/thingsboard/server/config/JsonMapperWiringTest.java b/application/src/test/java/org/thingsboard/server/config/JsonMapperWiringTest.java
new file mode 100644
index 0000000000..a3716f7df1
--- /dev/null
+++ b/application/src/test/java/org/thingsboard/server/config/JsonMapperWiringTest.java
@@ -0,0 +1,40 @@
+// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc.
+// SPDX-License-Identifier: BUSL-1.1
+package org.thingsboard.server.config;
+
+import com.fasterxml.jackson.databind.DeserializationFeature;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import org.junit.Test;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.http.converter.HttpMessageConverter;
+import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
+import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter;
+import org.thingsboard.server.controller.AbstractControllerTest;
+import org.thingsboard.server.dao.service.DaoSqlTest;
+
+import java.util.List;
+
+import static org.assertj.core.api.Assertions.assertThat;
+
+@DaoSqlTest
+public class JsonMapperWiringTest extends AbstractControllerTest {
+
+ @Autowired
+ private RequestMappingHandlerAdapter handlerAdapter;
+
+ @Autowired
+ private ObjectMapper objectMapper;
+
+ @Test
+ public void mvcUsesJackson2() {
+ List> converters = handlerAdapter.getMessageConverters();
+ assertThat(converters).noneMatch(c -> c.getClass().getName().startsWith("org.springframework.http.converter.json.JacksonJson"));
+ MappingJackson2HttpMessageConverter json = converters.stream()
+ .filter(MappingJackson2HttpMessageConverter.class::isInstance)
+ .map(MappingJackson2HttpMessageConverter.class::cast)
+ .findFirst().orElseThrow();
+ assertThat(json.getObjectMapper()).isSameAs(objectMapper);
+ assertThat(objectMapper.isEnabled(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES)).isFalse();
+ }
+
+}
diff --git a/application/src/test/java/org/thingsboard/server/config/StaticResourceCompressionTest.java b/application/src/test/java/org/thingsboard/server/config/StaticResourceCompressionTest.java
new file mode 100644
index 0000000000..e42066f0b1
--- /dev/null
+++ b/application/src/test/java/org/thingsboard/server/config/StaticResourceCompressionTest.java
@@ -0,0 +1,117 @@
+// SPDX-FileCopyrightText: Copyright The ThingsBoard Authors
+// SPDX-FileCopyrightText: Modifications Copyright ThingsBoard, Inc.
+// SPDX-License-Identifier: Apache-2.0 AND BUSL-1.1
+package org.thingsboard.server.config;
+
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.io.TempDir;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.boot.autoconfigure.ImportAutoConfiguration;
+import org.springframework.boot.http.converter.autoconfigure.HttpMessageConvertersAutoConfiguration;
+import org.springframework.boot.test.context.SpringBootTest;
+import org.springframework.boot.webmvc.autoconfigure.DispatcherServletAutoConfiguration;
+import org.springframework.boot.webmvc.autoconfigure.WebMvcAutoConfiguration;
+import org.springframework.test.context.DynamicPropertyRegistry;
+import org.springframework.test.context.DynamicPropertySource;
+import org.springframework.test.web.servlet.MockMvc;
+import org.springframework.web.context.WebApplicationContext;
+
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+import java.io.UncheckedIOException;
+import java.nio.charset.StandardCharsets;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.util.zip.GZIPOutputStream;
+
+import static org.hamcrest.Matchers.containsString;
+import static org.springframework.http.HttpHeaders.ACCEPT_ENCODING;
+import static org.springframework.http.HttpHeaders.CONTENT_ENCODING;
+import static org.springframework.http.HttpHeaders.VARY;
+import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
+import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
+import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.header;
+import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
+import static org.springframework.test.web.servlet.setup.MockMvcBuilders.webAppContextSetup;
+
+/**
+ * Loads the real thingsboard.yml, so the test fails if its static resource chain keys stop binding again.
+ */
+@SpringBootTest(classes = StaticResourceCompressionTest.WebMvcConfig.class, properties = "spring.config.name=thingsboard")
+public class StaticResourceCompressionTest {
+
+ private static final byte[] JS = "console.log('ThingsBoard');\n".repeat(100).getBytes(StandardCharsets.UTF_8);
+ private static final byte[] JS_GZ = gzip(JS);
+ private static final byte[] CSS = "@font-face { src: url(font.woff2); }\n".getBytes(StandardCharsets.UTF_8);
+
+ @TempDir
+ static Path webRoot;
+
+ @Autowired
+ private WebApplicationContext webApplicationContext;
+
+ private MockMvc mvc;
+
+ @DynamicPropertySource
+ static void staticLocations(DynamicPropertyRegistry registry) {
+ registry.add("spring.web.resources.static-locations", () -> webRoot.toUri().toString());
+ }
+
+ @BeforeAll
+ static void createStaticFiles() throws IOException {
+ Files.write(webRoot.resolve("main.js"), JS);
+ Files.write(webRoot.resolve("main.js.gz"), JS_GZ);
+ Files.write(webRoot.resolve("styles.css"), CSS);
+ Files.write(webRoot.resolve("font.woff2"), new byte[]{1, 2, 3});
+ }
+
+ @BeforeEach
+ void setUpMockMvc() {
+ mvc = webAppContextSetup(webApplicationContext).build();
+ }
+
+ @Test
+ public void servesPrebuiltGzipWhenClientAcceptsIt() throws Exception {
+ mvc.perform(get("/main.js").header(ACCEPT_ENCODING, "gzip, deflate, br"))
+ .andExpect(status().isOk())
+ .andExpect(header().string(CONTENT_ENCODING, "gzip"))
+ .andExpect(header().string(VARY, containsString(ACCEPT_ENCODING)))
+ .andExpect(content().contentTypeCompatibleWith("text/javascript"))
+ .andExpect(content().bytes(JS_GZ));
+ }
+
+ @Test
+ public void servesRawFileWhenClientDoesNotAcceptGzip() throws Exception {
+ mvc.perform(get("/main.js"))
+ .andExpect(status().isOk())
+ .andExpect(header().doesNotExist(CONTENT_ENCODING))
+ .andExpect(content().bytes(JS));
+ }
+
+ @Test
+ public void servesStylesheetUnchanged() throws Exception {
+ // the content version strategy would rewrite url(font.woff2) to url(font-.woff2)
+ mvc.perform(get("/styles.css").header(ACCEPT_ENCODING, "gzip"))
+ .andExpect(status().isOk())
+ .andExpect(header().doesNotExist(CONTENT_ENCODING))
+ .andExpect(content().bytes(CSS));
+ }
+
+ // not @Configuration: @ComponentScan("org.thingsboard.server") in other tests would pick it up
+ @ImportAutoConfiguration({DispatcherServletAutoConfiguration.class, WebMvcAutoConfiguration.class, HttpMessageConvertersAutoConfiguration.class})
+ static class WebMvcConfig {
+ }
+
+ private static byte[] gzip(byte[] data) {
+ ByteArrayOutputStream out = new ByteArrayOutputStream();
+ try (GZIPOutputStream gzip = new GZIPOutputStream(out)) {
+ gzip.write(data);
+ } catch (IOException e) {
+ throw new UncheckedIOException(e);
+ }
+ return out.toByteArray();
+ }
+
+}
diff --git a/application/src/test/java/org/thingsboard/server/config/ThingsboardYmlDefaultsTest.java b/application/src/test/java/org/thingsboard/server/config/ThingsboardYmlDefaultsTest.java
new file mode 100644
index 0000000000..ef1f079902
--- /dev/null
+++ b/application/src/test/java/org/thingsboard/server/config/ThingsboardYmlDefaultsTest.java
@@ -0,0 +1,26 @@
+// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc.
+// SPDX-License-Identifier: BUSL-1.1
+package org.thingsboard.server.config;
+
+import org.junit.jupiter.api.Test;
+import org.springframework.boot.env.YamlPropertySourceLoader;
+import org.springframework.core.env.PropertySource;
+import org.springframework.core.env.StandardEnvironment;
+import org.springframework.core.io.ClassPathResource;
+
+import java.io.IOException;
+import java.util.List;
+
+import static org.assertj.core.api.Assertions.assertThat;
+
+class ThingsboardYmlDefaultsTest {
+
+ @Test
+ void tomcatMaxParameterCountDefaultsTo10000() throws IOException {
+ List> sources = new YamlPropertySourceLoader().load("thingsboard", new ClassPathResource("thingsboard.yml"));
+ StandardEnvironment environment = new StandardEnvironment();
+ sources.forEach(environment.getPropertySources()::addLast);
+ assertThat(environment.getProperty("server.tomcat.max-parameter-count", Integer.class)).isEqualTo(10000);
+ }
+
+}
diff --git a/application/src/test/java/org/thingsboard/server/controller/AbstractControllerTest.java b/application/src/test/java/org/thingsboard/server/controller/AbstractControllerTest.java
index 489a8b550e..84d55ea636 100644
--- a/application/src/test/java/org/thingsboard/server/controller/AbstractControllerTest.java
+++ b/application/src/test/java/org/thingsboard/server/controller/AbstractControllerTest.java
@@ -7,9 +7,9 @@ import lombok.extern.slf4j.Slf4j;
import org.junit.After;
import org.junit.Before;
import org.junit.runner.RunWith;
+import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.test.context.SpringBootContextLoader;
import org.springframework.boot.test.context.SpringBootTest;
-import org.springframework.boot.test.web.server.LocalServerPort;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.test.annotation.DirtiesContext;
@@ -63,7 +63,8 @@ public abstract class AbstractControllerTest extends AbstractNotifyEntityTest {
public static final String WS_URL = "ws://localhost:";
- @LocalServerPort
+ // This class is also the context's configuration bean, which is created before the server port is known
+ @Value("${local.server.port:0}")
protected int serverPort;
protected volatile TbTestWebSocketClient wsClient; // lazy
diff --git a/application/src/test/java/org/thingsboard/server/controller/AbstractWebTest.java b/application/src/test/java/org/thingsboard/server/controller/AbstractWebTest.java
index dc1e88d4ab..67a9aed4ad 100644
--- a/application/src/test/java/org/thingsboard/server/controller/AbstractWebTest.java
+++ b/application/src/test/java/org/thingsboard/server/controller/AbstractWebTest.java
@@ -46,12 +46,14 @@ import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult;
import org.springframework.test.web.servlet.ResultActions;
import org.springframework.test.web.servlet.ResultMatcher;
+import org.springframework.test.web.servlet.request.AbstractMockHttpServletRequestBuilder;
import org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.result.MockMvcResultHandlers;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.context.WebApplicationContext;
+import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter;
import org.thingsboard.common.util.JacksonUtil;
import org.thingsboard.rule.engine.api.MailService;
import org.thingsboard.server.actors.DefaultTbActorSystem;
@@ -334,14 +336,15 @@ public abstract class AbstractWebTest extends AbstractInMemoryStorageTest {
};
@Autowired
- void setConverters(HttpMessageConverter>[] converters) {
+ void setConverters(RequestMappingHandlerAdapter handlerAdapter) {
+ List> converters = handlerAdapter.getMessageConverters();
- this.mappingJackson2HttpMessageConverter = Arrays.stream(converters)
+ this.mappingJackson2HttpMessageConverter = converters.stream()
.filter(hmc -> hmc instanceof MappingJackson2HttpMessageConverter)
.findAny()
.get();
- this.stringHttpMessageConverter = Arrays.stream(converters)
+ this.stringHttpMessageConverter = converters.stream()
.filter(hmc -> hmc instanceof StringHttpMessageConverter)
.findAny()
.get();
@@ -761,7 +764,7 @@ public abstract class AbstractWebTest extends AbstractInMemoryStorageTest {
doPost("/api/auth/logout").andExpect(status().isOk());
}
- protected void setJwtToken(MockHttpServletRequestBuilder request) {
+ protected void setJwtToken(AbstractMockHttpServletRequestBuilder> request) {
if (this.token != null) {
request.header(ThingsboardSecurityConfiguration.AUTHORIZATION_HEADER, BEARER_HEADER_PREFIX + this.token);
}
diff --git a/application/src/test/java/org/thingsboard/server/controller/AdminControllerTest.java b/application/src/test/java/org/thingsboard/server/controller/AdminControllerTest.java
index b571440e70..76683aea2f 100644
--- a/application/src/test/java/org/thingsboard/server/controller/AdminControllerTest.java
+++ b/application/src/test/java/org/thingsboard/server/controller/AdminControllerTest.java
@@ -10,6 +10,7 @@ import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.RandomStringUtils;
import org.junit.Test;
import org.mockito.Mockito;
+import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.bean.override.mockito.MockitoBean;
import org.thingsboard.common.util.JacksonUtil;
import org.thingsboard.server.common.data.AdminSettings;
@@ -17,9 +18,11 @@ import org.thingsboard.server.common.data.id.TenantId;
import org.thingsboard.server.common.data.security.model.JwtSettings;
import org.thingsboard.server.dao.secret.SecretConfigurationService;
import org.thingsboard.server.dao.service.DaoSqlTest;
+import org.thingsboard.server.dao.settings.AdminSettingsService;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
+import java.util.Map;
import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.Matchers.containsString;
@@ -44,6 +47,9 @@ public class AdminControllerTest extends AbstractControllerTest {
@MockitoBean
private SecretConfigurationService secretConfigurationService;
+ @Autowired
+ private AdminSettingsService adminSettingsService;
+
@Test
public void testFindAdminSettingsByKey() throws Exception {
loginSysAdmin();
@@ -111,6 +117,30 @@ public class AdminControllerTest extends AbstractControllerTest {
.andExpect(statusReason(containsString("is prohibited")));
}
+ @Test
+ public void testSaveAdminSettingsRefusesVersionControlKeys() throws Exception {
+ loginTenantAdmin();
+ checkVersionControlKeysRefused(tenantId);
+
+ loginSysAdmin();
+ checkVersionControlKeysRefused(TenantId.SYS_TENANT_ID);
+ }
+
+ private void checkVersionControlKeysRefused(TenantId settingsTenantId) throws Exception {
+ Map values = Map.of(
+ "entitiesVersionControl", "{\"repositoryUri\":\"repo1\",\"defaultBranch\":\"main\"}",
+ "autoCommitSettings", "{}");
+ for (Map.Entry entry : values.entrySet()) {
+ AdminSettings settings = new AdminSettings();
+ settings.setKey(entry.getKey());
+ settings.setJsonValue(JacksonUtil.toJsonNode(entry.getValue()));
+ doPost("/api/admin/settings", settings)
+ .andExpect(status().isBadRequest())
+ .andExpect(statusReason(containsString("version control API")));
+ assertThat(adminSettingsService.findAdminSettingsByTenantIdAndKey(settingsTenantId, entry.getKey())).isNull();
+ }
+ }
+
@Test
public void testMailOAuth2AuthorizationStoresOnlyInAppPrevUri() throws Exception {
loginSysAdmin();
diff --git a/application/src/test/java/org/thingsboard/server/controller/AlarmRuleControllerTest.java b/application/src/test/java/org/thingsboard/server/controller/AlarmRuleControllerTest.java
index cec0df49ee..e0f675d3e8 100644
--- a/application/src/test/java/org/thingsboard/server/controller/AlarmRuleControllerTest.java
+++ b/application/src/test/java/org/thingsboard/server/controller/AlarmRuleControllerTest.java
@@ -98,6 +98,32 @@ public class AlarmRuleControllerTest extends AbstractControllerTest {
.andExpect(status().isOk());
}
+ @Test
+ public void testSaveAlarmRuleWithOtherTenantReference() throws Exception {
+ Device testDevice = createDevice("Test device", "1234567890");
+ AlarmRuleDefinition alarmRule = createTestAlarmRule(testDevice.getId(), "High Temperature");
+ alarmRule.getConfiguration().getArguments().get("temperature").setRefEntityId(tenantId);
+
+ doPost("/api/alarm/rule", alarmRule).andExpect(status().isForbidden());
+
+ PageData alarmRules = doGetTypedWithPageLink(
+ "/api/alarm/rules/" + EntityType.DEVICE + "/" + testDevice.getUuidId() + "?",
+ new TypeReference<>() {}, new PageLink(10));
+ assertThat(alarmRules.getData()).isEmpty();
+ }
+
+ @Test
+ public void testSaveAlarmRuleWithOwnTenantReference() throws Exception {
+ Device testDevice = createDevice("Test device", "1234567890");
+ AlarmRuleDefinition alarmRule = createTestAlarmRule(testDevice.getId(), "High Temperature");
+ alarmRule.getConfiguration().getArguments().get("temperature").setRefEntityId(savedTenant.getId());
+
+ AlarmRuleDefinition saved = saveAlarmRule(alarmRule);
+
+ assertThat(saved.getId()).isNotNull();
+ assertThat(saved.getConfiguration().getArguments().get("temperature").getRefEntityId()).isEqualTo(savedTenant.getId());
+ }
+
@Test
public void testGetAlarmRuleById() throws Exception {
Device testDevice = createDevice("Test device", "1234567890");
diff --git a/application/src/test/java/org/thingsboard/server/controller/ApiKeyControllerTest.java b/application/src/test/java/org/thingsboard/server/controller/ApiKeyControllerTest.java
index b0cca491a3..b19cb3131b 100644
--- a/application/src/test/java/org/thingsboard/server/controller/ApiKeyControllerTest.java
+++ b/application/src/test/java/org/thingsboard/server/controller/ApiKeyControllerTest.java
@@ -234,6 +234,57 @@ public class ApiKeyControllerTest extends AbstractControllerTest {
doDelete("/api/apiKey/" + savedApiKey.getId().getId()).andExpect(status().isOk());
}
+ @Test
+ public void testCustomerUserListsOwnApiKeys() throws Exception {
+ loginCustomerAdminUser();
+ ApiKeyInfo apiKeyInfo = constructApiKeyInfo("Test API key description", true);
+ apiKeyInfo.setUserId(customerAdminUserId);
+ doPost("/api/apiKey", apiKeyInfo, ApiKey.class);
+
+ PageData pageData = doGetTypedWithPageLink("/api/apiKeys/" + customerAdminUserId + "?", new TypeReference<>() {}, new PageLink(10, 0));
+ Assert.assertEquals(1, pageData.getData().size());
+ Assert.assertEquals(customerAdminUserId, pageData.getData().get(0).getUserId());
+ }
+
+ @Test
+ public void testTenantAdminListsCustomerUserApiKeys() throws Exception {
+ ApiKeyInfo apiKeyInfo = constructApiKeyInfo("Test API key description", true);
+ apiKeyInfo.setUserId(customerUserId);
+ doPost("/api/apiKey", apiKeyInfo, ApiKey.class);
+
+ PageData pageData = doGetTypedWithPageLink("/api/apiKeys/" + customerUserId + "?", new TypeReference<>() {}, new PageLink(10, 0));
+ Assert.assertEquals(1, pageData.getData().size());
+ Assert.assertEquals(customerUserId, pageData.getData().get(0).getUserId());
+ }
+
+ @Test
+ public void testCustomerUserCannotListOtherUserApiKeys() throws Exception {
+ loginCustomerAdminUser();
+ doGet("/api/user/" + customerUserId).andExpect(status().isOk());
+ doGet("/api/apiKeys/" + customerUserId + "?pageSize=10&page=0").andExpect(status().isForbidden());
+ }
+
+ @Test
+ public void testCustomerUserCannotReadOtherUserApiKeyRelations() throws Exception {
+ ApiKeyInfo apiKeyInfo = constructApiKeyInfo("Test API key description", true);
+ apiKeyInfo.setUserId(customerUserId);
+ ApiKey apiKey = doPost("/api/apiKey", apiKeyInfo, ApiKey.class);
+
+ loginCustomerAdminUser();
+ doGet("/api/relations?fromId=" + apiKey.getId().getId() + "&fromType=API_KEY").andExpect(status().isForbidden());
+ }
+
+ @Test
+ public void testCustomerUserCannotDeleteTenantAdminApiKey() throws Exception {
+ ApiKey apiKey = doPost("/api/apiKey", constructApiKeyInfo("Test API key description", true), ApiKey.class);
+
+ loginCustomerAdminUser();
+ doDelete("/api/apiKey/" + apiKey.getId().getId()).andExpect(status().isForbidden());
+
+ loginTenantAdmin();
+ doDelete("/api/apiKey/" + apiKey.getId().getId()).andExpect(status().isOk());
+ }
+
private ApiKeyInfo constructApiKeyInfo(String description, boolean enabled) {
ApiKeyInfo apiKeyInfo = new ApiKeyInfo();
apiKeyInfo.setDescription(description);
diff --git a/application/src/test/java/org/thingsboard/server/controller/AuthControllerTest.java b/application/src/test/java/org/thingsboard/server/controller/AuthControllerTest.java
index 7fd2d8e9be..78d22aec65 100644
--- a/application/src/test/java/org/thingsboard/server/controller/AuthControllerTest.java
+++ b/application/src/test/java/org/thingsboard/server/controller/AuthControllerTest.java
@@ -16,7 +16,11 @@ import org.thingsboard.server.common.data.StringUtils;
import org.thingsboard.server.common.data.User;
import org.thingsboard.server.common.data.UserActivationLink;
import org.thingsboard.server.common.data.UserInfo;
+import org.thingsboard.server.common.data.exception.ThingsboardErrorCode;
+import org.thingsboard.server.common.data.exception.ThingsboardException;
import org.thingsboard.server.common.data.id.UserId;
+import org.thingsboard.server.common.data.permission.Operation;
+import org.thingsboard.server.common.data.permission.Resource;
import org.thingsboard.server.common.data.security.Authority;
import org.thingsboard.server.common.data.security.UserCredentials;
import org.thingsboard.server.common.data.security.model.SecuritySettings;
@@ -24,6 +28,7 @@ import org.thingsboard.server.dao.service.DaoSqlTest;
import org.thingsboard.server.dao.user.UserCredentialsDao;
import org.thingsboard.server.service.security.auth.rest.LoginRequest;
import org.thingsboard.server.service.security.model.ChangePasswordRequest;
+import org.thingsboard.server.service.security.permission.AccessControlService;
import java.util.concurrent.TimeUnit;
import java.util.function.Consumer;
@@ -33,6 +38,8 @@ import static org.assertj.core.api.Assertions.within;
import static org.hamcrest.Matchers.is;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
+import static org.mockito.ArgumentMatchers.eq;
+import static org.mockito.Mockito.doThrow;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.header;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
@@ -43,6 +50,9 @@ public class AuthControllerTest extends AbstractControllerTest {
@MockitoSpyBean
private UserCredentialsDao userCredentialsDao;
+ @MockitoSpyBean
+ private AccessControlService accessControlService;
+
@After
public void tearDown() throws Exception {
loginSysAdmin();
@@ -287,6 +297,26 @@ public class AuthControllerTest extends AbstractControllerTest {
assertThat(getUser(user.getId()).getAdditionalInfo().get("userActivated").asBoolean()).isTrue();
}
+ @Test
+ public void testActivationLinkRequiresWritePermissionOnUser() throws Exception {
+ loginTenantAdmin();
+ User user = new User();
+ user.setAuthority(Authority.TENANT_ADMIN);
+ user.setEmail("pending-user@thingsboard.org");
+ user = doPost("/api/user", user, User.class);
+
+ doThrow(new ThingsboardException("You don't have permission to perform this operation!", ThingsboardErrorCode.PERMISSION_DENIED))
+ .when(accessControlService).checkPermission(any(), eq(Resource.USER), eq(Operation.WRITE), eq(user.getId()), any());
+
+ doGet("/api/user/" + user.getId() + "/activationLinkInfo").andExpect(status().isForbidden());
+ doGet("/api/user/" + user.getId() + "/activationLink").andExpect(status().isForbidden());
+ doPost("/api/user/sendActivationMail?email=" + user.getEmail()).andExpect(status().isForbidden());
+
+ Mockito.reset(accessControlService);
+ assertThat(getActivationLinkInfo(user).value()).isNotBlank();
+ doPost("/api/user/sendActivationMail?email=" + user.getEmail()).andExpect(status().isOk());
+ }
+
@Test
public void testGetPageWithoutRedirect() throws Exception {
doGet("/login").andExpect(status().isOk());
diff --git a/application/src/test/java/org/thingsboard/server/controller/CalculatedFieldControllerTest.java b/application/src/test/java/org/thingsboard/server/controller/CalculatedFieldControllerTest.java
index 55d3930fec..34ba0d1cf8 100644
--- a/application/src/test/java/org/thingsboard/server/controller/CalculatedFieldControllerTest.java
+++ b/application/src/test/java/org/thingsboard/server/controller/CalculatedFieldControllerTest.java
@@ -2,6 +2,7 @@
// SPDX-License-Identifier: Apache-2.0
package org.thingsboard.server.controller;
+import com.fasterxml.jackson.core.type.TypeReference;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
@@ -41,6 +42,7 @@ import org.thingsboard.server.common.data.security.Authority;
import org.thingsboard.server.dao.service.DaoSqlTest;
import java.util.Comparator;
+import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
@@ -298,6 +300,48 @@ public class CalculatedFieldControllerTest extends AbstractControllerTest {
doGet("/api/calculatedField/" + savedCalculatedField.getId().getId()).andExpect(status().isNotFound());
}
+ @Test
+ public void testSaveCalculatedFieldWithOtherTenantReference() throws Exception {
+ Device testDevice = createDevice("Test device", "1234567890");
+ CalculatedField calculatedField = getSimpleCalculatedField(testDevice.getId(), Map.of("T", getArgument(tenantId)));
+
+ doPost("/api/calculatedField", calculatedField).andExpect(status().isForbidden());
+
+ PageData calculatedFields = doGetTyped("/api/DEVICE/" + testDevice.getId().getId() + "/calculatedFields?pageSize=10&page=0",
+ new TypeReference<>() {});
+ assertThat(calculatedFields.getData()).isEmpty();
+ }
+
+ @Test
+ public void testSaveCalculatedFieldWithOwnTenantReference() throws Exception {
+ Device testDevice = createDevice("Test device", "1234567890");
+ CalculatedField calculatedField = getSimpleCalculatedField(testDevice.getId(), Map.of("T", getArgument(savedTenant.getId())));
+
+ CalculatedField savedCalculatedField = doPost("/api/calculatedField", calculatedField, CalculatedField.class);
+
+ assertThat(savedCalculatedField.getId()).isNotNull();
+ assertThat(savedCalculatedField.getConfiguration().getReferencedEntities()).containsExactly(savedTenant.getId());
+ }
+
+ @Test
+ public void testSaveCalculatedFieldChecksEveryReference() throws Exception {
+ loginTenantAdmin();
+ Device otherTenantDevice = createDevice("Other device", "0987654321");
+ login("tenant2@thingsboard.org", "testPassword1");
+
+ Device testDevice = createDevice("Test device", "1234567890");
+ Map arguments = new LinkedHashMap<>();
+ arguments.put("T", getArgument(savedTenant.getId()));
+ arguments.put("H", getArgument(otherTenantDevice.getId()));
+ CalculatedField calculatedField = getSimpleCalculatedField(testDevice.getId(), arguments);
+
+ doPost("/api/calculatedField", calculatedField).andExpect(status().isNotFound());
+ }
+
+ private CalculatedField getSimpleCalculatedField(EntityId entityId, Map arguments) {
+ return getCalculatedField(entityId, CalculatedFieldType.SIMPLE, getSimpleCalculatedFieldConfig(arguments));
+ }
+
private CalculatedField getSimpleCalculatedField(EntityId entityId) {
return getCalculatedField(entityId, CalculatedFieldType.SIMPLE);
}
@@ -385,14 +429,13 @@ public class CalculatedFieldControllerTest extends AbstractControllerTest {
}
private CalculatedFieldConfiguration getSimpleCalculatedFieldConfig() {
- SimpleCalculatedFieldConfiguration config = new SimpleCalculatedFieldConfiguration();
+ return getSimpleCalculatedFieldConfig(Map.of("T", getArgument(null)));
+ }
- Argument argument = new Argument();
- argument.setRefEntityId(null);
- ReferencedEntityKey refEntityKey = new ReferencedEntityKey("temperature", ArgumentType.TS_LATEST, null);
- argument.setRefEntityKey(refEntityKey);
+ private CalculatedFieldConfiguration getSimpleCalculatedFieldConfig(Map arguments) {
+ SimpleCalculatedFieldConfiguration config = new SimpleCalculatedFieldConfiguration();
- config.setArguments(Map.of("T", argument));
+ config.setArguments(arguments);
config.setExpression("T - (100 - H) / 5");
@@ -404,4 +447,11 @@ public class CalculatedFieldControllerTest extends AbstractControllerTest {
return config;
}
+ private Argument getArgument(EntityId refEntityId) {
+ Argument argument = new Argument();
+ argument.setRefEntityId(refEntityId);
+ argument.setRefEntityKey(new ReferencedEntityKey("temperature", ArgumentType.TS_LATEST, null));
+ return argument;
+ }
+
}
diff --git a/application/src/test/java/org/thingsboard/server/controller/CustomMenuControllerTest.java b/application/src/test/java/org/thingsboard/server/controller/CustomMenuControllerTest.java
index 48d5a691f6..083b94e183 100644
--- a/application/src/test/java/org/thingsboard/server/controller/CustomMenuControllerTest.java
+++ b/application/src/test/java/org/thingsboard/server/controller/CustomMenuControllerTest.java
@@ -5,6 +5,7 @@ package org.thingsboard.server.controller;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonNode;
import lombok.extern.slf4j.Slf4j;
+import org.apache.commons.lang3.RandomStringUtils;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
@@ -12,7 +13,6 @@ import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.test.web.servlet.MvcResult;
-import org.testcontainers.shaded.org.apache.commons.lang3.RandomStringUtils;
import org.thingsboard.common.util.JacksonUtil;
import org.thingsboard.server.common.data.Customer;
import org.thingsboard.server.common.data.EntityInfo;
@@ -657,6 +657,120 @@ public class CustomMenuControllerTest extends AbstractControllerTest {
assertThat(currentMenu.get("items")).isEmpty();
}
+ @Test
+ public void testCustomerUserMenuIgnoresMenuOfOtherTenant() throws Exception {
+ loginDifferentTenant();
+ CustomMenu otherTenantMenu = new CustomMenu();
+ otherTenantMenu.setName(RandomStringUtils.randomAlphabetic(10));
+ otherTenantMenu.setScope(CMScope.CUSTOMER);
+ otherTenantMenu.setAssigneeType(CMAssigneeType.NO_ASSIGN);
+ otherTenantMenu = doPost("/api/customMenu", otherTenantMenu, CustomMenu.class);
+ idsToRemove.add(otherTenantMenu.getUuidId());
+ CustomMenuConfig otherTenantMenuConfig = putRandomMenuConfig(otherTenantMenu.getId());
+ String otherTenantMenuUrl = ((CustomMenuItem) otherTenantMenuConfig.getItems().get(2)).getUrl();
+
+ loginTenantAdmin();
+ Customer customer = doGet("/api/customer/" + customerId.getId(), Customer.class);
+ customer.setCustomMenuId(otherTenantMenu.getId());
+ doPost("/api/customer", customer).andExpect(status().isOk());
+
+ loginCustomerUser();
+ JsonNode customerUserMenu = doGet("/api/customMenu", JsonNode.class);
+ assertThat(customerUserMenu.toString()).doesNotContain(otherTenantMenuUrl);
+ }
+
+ @Test
+ public void testTenantUserMenuIgnoresMenuOfOtherTenant() throws Exception {
+ loginDifferentTenant();
+ CustomMenu otherTenantMenu = new CustomMenu();
+ otherTenantMenu.setName(RandomStringUtils.randomAlphabetic(10));
+ otherTenantMenu.setScope(CMScope.TENANT);
+ otherTenantMenu.setAssigneeType(CMAssigneeType.NO_ASSIGN);
+ otherTenantMenu = doPost("/api/customMenu", otherTenantMenu, CustomMenu.class);
+ idsToRemove.add(otherTenantMenu.getUuidId());
+ CustomMenuConfig otherTenantMenuConfig = putRandomMenuConfig(otherTenantMenu.getId());
+ String otherTenantMenuUrl = ((CustomMenuItem) otherTenantMenuConfig.getItems().get(2)).getUrl();
+
+ loginTenantAdmin();
+ User tenantAdmin = doGet("/api/user/" + tenantAdminUserId.getId(), User.class);
+ tenantAdmin.setCustomMenuId(otherTenantMenu.getId());
+ doPost("/api/user", tenantAdmin).andExpect(status().isOk());
+ assertThat(doGet("/api/user/" + tenantAdminUserId.getId(), User.class).getCustomMenuId()).isEqualTo(otherTenantMenu.getId());
+
+ JsonNode tenantAdminMenu = doGet("/api/customMenu", JsonNode.class);
+ assertThat(tenantAdminMenu.toString()).doesNotContain(otherTenantMenuUrl);
+ }
+
+ @Test
+ public void testCustomMenuAssigneeListContainsOnlyCustomersOfMenuTenant() throws Exception {
+ loginTenantAdmin();
+ CustomMenu customerMenu = new CustomMenu();
+ customerMenu.setName(RandomStringUtils.randomAlphabetic(10));
+ customerMenu.setScope(CMScope.CUSTOMER);
+ customerMenu.setAssigneeType(CMAssigneeType.CUSTOMERS);
+ customerMenu = doPost("/api/customMenu?assignToList=" + customerId, customerMenu, CustomMenu.class);
+
+ loginDifferentTenant();
+ Customer otherTenantCustomer = new Customer();
+ otherTenantCustomer.setTitle("Other Tenant Customer");
+ otherTenantCustomer.setCustomMenuId(customerMenu.getId());
+ otherTenantCustomer = doPost("/api/customer", otherTenantCustomer, Customer.class);
+
+ loginTenantAdmin();
+ List assigneeList = doGetTyped("/api/customMenu/" + customerMenu.getId() + "/assigneeList", new TypeReference<>() {});
+ assertThat(assigneeList).extracting(EntityInfo::getId).containsExactly(customerId);
+ doDelete("/api/customMenu/" + customerMenu.getId() + "?force=true").andExpect(status().isOk());
+
+ loginDifferentTenant();
+ Customer otherTenantCustomerAfterDelete = doGet("/api/customer/" + otherTenantCustomer.getId(), Customer.class);
+ assertThat(otherTenantCustomerAfterDelete.getCustomMenuId()).isEqualTo(customerMenu.getId());
+ }
+
+ @Test
+ public void testCustomMenuAssigneeListContainsOnlyUsersOfMenuTenant() throws Exception {
+ loginTenantAdmin();
+ CustomMenu userMenu = new CustomMenu();
+ userMenu.setName(RandomStringUtils.randomAlphabetic(10));
+ userMenu.setScope(CMScope.TENANT);
+ userMenu.setAssigneeType(CMAssigneeType.USERS);
+ userMenu = doPost("/api/customMenu?assignToList=" + tenantAdminUserId, userMenu, CustomMenu.class);
+
+ loginDifferentTenant();
+ User otherTenantUser = new User();
+ otherTenantUser.setAuthority(Authority.TENANT_ADMIN);
+ otherTenantUser.setTenantId(differentTenantId);
+ otherTenantUser.setEmail("othertenantuser@thingsboard.org");
+ otherTenantUser.setCustomMenuId(userMenu.getId());
+ otherTenantUser = doPost("/api/user", otherTenantUser, User.class);
+ assertThat(otherTenantUser.getCustomMenuId()).isEqualTo(userMenu.getId());
+
+ loginTenantAdmin();
+ List assigneeList = doGetTyped("/api/customMenu/" + userMenu.getId() + "/assigneeList", new TypeReference<>() {});
+ assertThat(assigneeList).extracting(EntityInfo::getId).containsExactly(tenantAdminUserId);
+ doDelete("/api/customMenu/" + userMenu.getId() + "?force=true").andExpect(status().isOk());
+
+ loginDifferentTenant();
+ User otherTenantUserAfterDelete = doGet("/api/user/" + otherTenantUser.getId(), User.class);
+ assertThat(otherTenantUserAfterDelete.getCustomMenuId()).isEqualTo(userMenu.getId());
+ }
+
+ @Test
+ public void testTenantUserGetsAssignedSystemMenu() throws Exception {
+ loginSysAdmin();
+ CustomMenu systemMenu = new CustomMenu();
+ systemMenu.setName(RandomStringUtils.randomAlphabetic(10));
+ systemMenu.setScope(CMScope.TENANT);
+ systemMenu.setAssigneeType(CMAssigneeType.NO_ASSIGN);
+ systemMenu = doPost("/api/customMenu", systemMenu, CustomMenu.class);
+ idsToRemove.add(systemMenu.getUuidId());
+ CustomMenuConfig systemMenuConfig = putRandomMenuConfig(systemMenu.getId());
+ doPut("/api/customMenu/" + systemMenu.getId() + "/assign/USERS", List.of(tenantAdminUserId.getId()));
+
+ loginTenantAdmin();
+ JsonNode tenantAdminMenu = doGet("/api/customMenu", JsonNode.class);
+ assertCustomMenuConfig(tenantAdminMenu, systemMenuConfig);
+ }
+
private MvcResult getUserCustomMenu() throws Exception {
return getUserCustomMenu(null);
}
diff --git a/application/src/test/java/org/thingsboard/server/controller/DashboardReportControllerTest.java b/application/src/test/java/org/thingsboard/server/controller/DashboardReportControllerTest.java
new file mode 100644
index 0000000000..a54efa04ab
--- /dev/null
+++ b/application/src/test/java/org/thingsboard/server/controller/DashboardReportControllerTest.java
@@ -0,0 +1,195 @@
+// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc.
+// SPDX-License-Identifier: BUSL-1.1
+package org.thingsboard.server.controller;
+
+import org.junit.Before;
+import org.junit.Test;
+import org.springframework.test.context.bean.override.mockito.MockitoSpyBean;
+import org.springframework.test.web.servlet.ResultActions;
+import org.thingsboard.common.util.JacksonUtil;
+import org.thingsboard.rule.engine.api.DashboardReportService;
+import org.thingsboard.server.common.data.Dashboard;
+import org.thingsboard.server.common.data.EntityType;
+import org.thingsboard.server.common.data.User;
+import org.thingsboard.server.common.data.dashboardreport.DashboardReportConfig;
+import org.thingsboard.server.common.data.dashboardreport.DashboardReportData;
+import org.thingsboard.server.common.data.group.EntityGroup;
+import org.thingsboard.server.common.data.id.UserId;
+import org.thingsboard.server.common.data.permission.GroupPermission;
+import org.thingsboard.server.common.data.role.Role;
+import org.thingsboard.server.common.data.role.RoleType;
+import org.thingsboard.server.common.data.security.Authority;
+import org.thingsboard.server.dao.service.DaoSqlTest;
+
+import java.util.concurrent.TimeUnit;
+import java.util.function.Consumer;
+
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.argThat;
+import static org.mockito.ArgumentMatchers.eq;
+import static org.mockito.ArgumentMatchers.isNull;
+import static org.mockito.Mockito.doAnswer;
+import static org.mockito.Mockito.never;
+import static org.mockito.Mockito.verify;
+import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
+
+@DaoSqlTest
+public class DashboardReportControllerTest extends AbstractControllerTest {
+
+ private static final String DASHBOARD_VIEWER_EMAIL = "dashboard.viewer@thingsboard.org";
+ private static final String DASHBOARD_VIEWER_PASSWORD = "viewer";
+ private static final String REPORTS_SERVER_URL = "http://localhost:8383";
+ private static final String REPORT_BASE_URL = "http://localhost:8081";
+
+ @MockitoSpyBean
+ private DashboardReportService dashboardReportService;
+
+ private Dashboard dashboard;
+
+ @Before
+ public void beforeTest() throws Exception {
+ loginSubCustomerAdminUser();
+ Dashboard dashboard = new Dashboard();
+ dashboard.setTitle("Sub-customer dashboard");
+ this.dashboard = doPost("/api/dashboard", dashboard, Dashboard.class);
+
+ doAnswer(invocation -> {
+ Consumer onSuccess = invocation.getArgument(3);
+ DashboardReportData reportData = new DashboardReportData();
+ reportData.setData(new byte[]{1});
+ reportData.setName("report.pdf");
+ reportData.setContentType("application/pdf");
+ onSuccess.accept(reportData);
+ return null;
+ }).when(dashboardReportService).generateReport(any(), any(), any(), any(), any());
+ }
+
+ @Test
+ public void testDownloadTestReportRequiresPermissionOverReportUser() throws Exception {
+ loginDifferentTenant();
+ UserId otherTenantUserId = savedDifferentTenantUser.getId();
+ loginDifferentCustomer();
+
+ loginCustomerAdminUser();
+ doPostTestReport(tenantAdminUserId.toString()).andExpect(status().isForbidden());
+ doPostTestReport(differentCustomerUserId.toString()).andExpect(status().isForbidden());
+ doPostTestReport(otherTenantUserId.toString()).andExpect(status().isForbidden());
+
+ loginSubCustomerAdminUser();
+ doPostTestReport(customerAdminUserId.toString()).andExpect(status().isForbidden());
+
+ loginTenantAdmin();
+ doPostTestReport(otherTenantUserId.toString()).andExpect(status().isForbidden());
+
+ createDashboardViewer();
+ login(DASHBOARD_VIEWER_EMAIL, DASHBOARD_VIEWER_PASSWORD);
+ doPostTestReport(customerAdminUserId.toString()).andExpect(status().isForbidden());
+ doPostTestReport(customerUserId.toString()).andExpect(status().isForbidden());
+
+ verify(dashboardReportService, never()).generateReport(any(), any(), any(), any(), any());
+ }
+
+ @Test
+ public void testDownloadTestReportAllowedForOwnUser() throws Exception {
+ loginCustomerAdminUser();
+ doPostTestReport(customerAdminUserId.toString()).andExpect(status().isOk());
+ verifyReportGenerated(customerAdminUserId);
+
+ UserId dashboardViewerId = createDashboardViewer();
+ login(DASHBOARD_VIEWER_EMAIL, DASHBOARD_VIEWER_PASSWORD);
+ doPostTestReport(dashboardViewerId.toString()).andExpect(status().isOk());
+ verifyReportGenerated(dashboardViewerId);
+ }
+
+ @Test
+ public void testDownloadTestReportAllowedForOwnedUser() throws Exception {
+ loginTenantAdmin();
+ doPostTestReport(customerUserId.toString()).andExpect(status().isOk());
+ verifyReportGenerated(customerUserId);
+
+ loginCustomerAdminUser();
+ doPostTestReport(subCustomerAdminUserId.toString()).andExpect(status().isOk());
+ verifyReportGenerated(subCustomerAdminUserId);
+ doPostTestReport(customerUserId.toString()).andExpect(status().isOk());
+ }
+
+ @Test
+ public void testDownloadTestReportWithCurrentUserCredentialsUsesCurrentUserWhenReportUserNotAccessible() throws Exception {
+ loginCustomerAdminUser();
+ doPostTestReport(tenantAdminUserId.toString(), null, true).andExpect(status().isOk());
+ verifyReportGenerated(customerAdminUserId);
+ }
+
+ @Test
+ public void testDownloadTestReportRequiresUserId() throws Exception {
+ loginCustomerAdminUser();
+ doPostTestReport(null).andExpect(status().isBadRequest());
+ doPostTestReport("not-a-uuid").andExpect(status().isBadRequest());
+ verify(dashboardReportService, never()).generateReport(any(), any(), any(), any(), any());
+ }
+
+ @Test
+ public void testDownloadTestReportUsesSystemReportServerForCustomerUser() throws Exception {
+ loginCustomerAdminUser();
+ doPostTestReport(customerAdminUserId.toString(), REPORTS_SERVER_URL).andExpect(status().isOk());
+ verify(dashboardReportService).generateReport(eq(tenantId), any(), isNull(), any(), any());
+
+ loginTenantAdmin();
+ doPostTestReport(tenantAdminUserId.toString(), REPORTS_SERVER_URL).andExpect(status().isOk());
+ verify(dashboardReportService).generateReport(eq(tenantId), any(), eq(REPORTS_SERVER_URL), any(), any());
+ }
+
+ private UserId createDashboardViewer() throws Exception {
+ loginTenantAdmin();
+ Role role = new Role();
+ role.setTenantId(tenantId);
+ role.setCustomerId(customerId);
+ role.setType(RoleType.GENERIC);
+ role.setName("Dashboard viewer");
+ role.setPermissions(JacksonUtil.toJsonNode("{\"DASHBOARD\":[\"READ\"]}"));
+ role = doPost("/api/role", role, Role.class);
+
+ EntityGroup userGroup = new EntityGroup();
+ userGroup.setName("Dashboard viewers");
+ userGroup.setType(EntityType.USER);
+ userGroup.setOwnerId(customerId);
+ userGroup = doPost("/api/entityGroup", userGroup, EntityGroup.class);
+ doPost("/api/groupPermission", new GroupPermission(tenantId, userGroup.getId(), role.getId(), null, null, false), GroupPermission.class);
+
+ User user = new User();
+ user.setAuthority(Authority.CUSTOMER_USER);
+ user.setTenantId(tenantId);
+ user.setCustomerId(customerId);
+ user.setEmail(DASHBOARD_VIEWER_EMAIL);
+ return createUser(user, DASHBOARD_VIEWER_PASSWORD, userGroup.getId()).getId();
+ }
+
+ private ResultActions doPostTestReport(String userId) throws Exception {
+ return doPostTestReport(userId, null);
+ }
+
+ private ResultActions doPostTestReport(String userId, String reportsServerEndpointUrl) throws Exception {
+ return doPostTestReport(userId, reportsServerEndpointUrl, false);
+ }
+
+ private ResultActions doPostTestReport(String userId, String reportsServerEndpointUrl, boolean useCurrentUserCredentials) throws Exception {
+ DashboardReportConfig reportConfig = new DashboardReportConfig();
+ reportConfig.setBaseUrl(REPORT_BASE_URL);
+ reportConfig.setDashboardId(dashboard.getId().toString());
+ reportConfig.setTimezone("UTC");
+ reportConfig.setNamePattern("report");
+ reportConfig.setType("pdf");
+ reportConfig.setUserId(userId);
+ reportConfig.setUseCurrentUserCredentials(useCurrentUserCredentials);
+ String url = "/api/report/test";
+ if (reportsServerEndpointUrl != null) {
+ url += "?reportsServerEndpointUrl=" + reportsServerEndpointUrl;
+ }
+ return doPostAsync(url, reportConfig, TimeUnit.SECONDS.toMillis(30));
+ }
+
+ private void verifyReportGenerated(UserId userId) throws Exception {
+ verify(dashboardReportService).generateReport(eq(tenantId), argThat(config -> userId.toString().equals(config.getUserId())), any(), any(), any());
+ }
+
+}
diff --git a/application/src/test/java/org/thingsboard/server/controller/DevelopmentNoticeCaptureStampTest.java b/application/src/test/java/org/thingsboard/server/controller/DevelopmentNoticeCaptureStampTest.java
index 6a0631fd98..bf401d10fe 100644
--- a/application/src/test/java/org/thingsboard/server/controller/DevelopmentNoticeCaptureStampTest.java
+++ b/application/src/test/java/org/thingsboard/server/controller/DevelopmentNoticeCaptureStampTest.java
@@ -62,7 +62,7 @@ public class DevelopmentNoticeCaptureStampTest {
.as("no subscribing call to %s in the capture path to order against", STAMP_METHOD)
.isTrue();
- int captured = capture.indexOf("html2canvas(");
+ int captured = capture.indexOf("domToCanvas(");
int serialised = capture.indexOf("toDataURL");
assertThat(captured).as("no capture call found to order against").isNotNegative();
assertThat(serialised).as("no serialisation call found to order against").isNotNegative();
diff --git a/application/src/test/java/org/thingsboard/server/controller/DeviceControllerTest.java b/application/src/test/java/org/thingsboard/server/controller/DeviceControllerTest.java
index bf39aa94ce..63423a1bdb 100644
--- a/application/src/test/java/org/thingsboard/server/controller/DeviceControllerTest.java
+++ b/application/src/test/java/org/thingsboard/server/controller/DeviceControllerTest.java
@@ -10,6 +10,7 @@ import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.ListenableFuture;
import com.google.common.util.concurrent.ListeningExecutorService;
import com.google.common.util.concurrent.MoreExecutors;
+import org.awaitility.Awaitility;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
@@ -23,7 +24,6 @@ import org.springframework.test.context.bean.override.mockito.MockitoSpyBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Primary;
import org.springframework.test.context.ContextConfiguration;
-import org.testcontainers.shaded.org.awaitility.Awaitility;
import org.thingsboard.common.util.JacksonUtil;
import org.thingsboard.common.util.ThingsBoardExecutors;
import org.thingsboard.server.common.data.AttributeScope;
diff --git a/application/src/test/java/org/thingsboard/server/controller/EntityGroupControllerTest.java b/application/src/test/java/org/thingsboard/server/controller/EntityGroupControllerTest.java
index 99fa4a51a6..2fb378e9b7 100644
--- a/application/src/test/java/org/thingsboard/server/controller/EntityGroupControllerTest.java
+++ b/application/src/test/java/org/thingsboard/server/controller/EntityGroupControllerTest.java
@@ -3,40 +3,52 @@
package org.thingsboard.server.controller;
import com.fasterxml.jackson.core.type.TypeReference;
+import org.apache.commons.lang3.RandomStringUtils;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
-import org.testcontainers.shaded.org.apache.commons.lang3.RandomStringUtils;
+import org.springframework.test.web.servlet.ResultActions;
import org.thingsboard.common.util.JacksonUtil;
import org.thingsboard.server.common.data.Dashboard;
import org.thingsboard.server.common.data.Device;
+import org.thingsboard.server.common.data.EntityInfo;
import org.thingsboard.server.common.data.EntityType;
import org.thingsboard.server.common.data.Tenant;
import org.thingsboard.server.common.data.User;
import org.thingsboard.server.common.data.edge.Edge;
import org.thingsboard.server.common.data.group.EntityGroup;
import org.thingsboard.server.common.data.group.EntityGroupInfo;
+import org.thingsboard.server.common.data.id.CustomerId;
import org.thingsboard.server.common.data.id.EntityGroupId;
+import org.thingsboard.server.common.data.id.EntityId;
import org.thingsboard.server.common.data.id.IdBased;
+import org.thingsboard.server.common.data.id.RoleId;
+import org.thingsboard.server.common.data.id.TenantId;
import org.thingsboard.server.common.data.page.PageData;
import org.thingsboard.server.common.data.page.PageLink;
+import org.thingsboard.server.common.data.permission.GroupPermission;
import org.thingsboard.server.common.data.permission.GroupPermissionInfo;
+import org.thingsboard.server.common.data.permission.Operation;
import org.thingsboard.server.common.data.permission.ShareGroupRequest;
import org.thingsboard.server.common.data.role.Role;
import org.thingsboard.server.common.data.role.RoleType;
import org.thingsboard.server.common.data.security.Authority;
+import org.thingsboard.server.dao.grouppermission.GroupPermissionService;
import org.thingsboard.server.dao.role.RoleService;
import org.thingsboard.server.dao.service.DaoSqlTest;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
+import java.util.UUID;
import java.util.stream.Collectors;
import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.Matchers.containsString;
+import static org.hamcrest.Matchers.is;
+import static org.hamcrest.Matchers.not;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
@DaoSqlTest
@@ -45,6 +57,12 @@ public class EntityGroupControllerTest extends AbstractControllerTest {
@Autowired
private RoleService roleService;
+ @Autowired
+ private GroupPermissionService groupPermissionService;
+
+ private static final String GROUP_MANAGER_PERMISSIONS =
+ "{\"DEVICE_GROUP\":[\"READ\",\"WRITE\"],\"USER_GROUP\":[\"READ\",\"WRITE\"],\"GROUP_PERMISSION\":[\"CREATE\"],\"ROLE\":[\"READ\"]}";
+
private Tenant savedTenant;
private User tenantAdmin;
@@ -89,6 +107,300 @@ public class EntityGroupControllerTest extends AbstractControllerTest {
Assert.assertEquals(savedEntityGroup.getName(), foundEntityGroup.getName());
}
+ @Test
+ public void testShouldNotChangeEntityGroupOwnerAsGroupOwner() throws Exception {
+ loginTenantAdmin();
+ EntityGroup entityGroup = new EntityGroup();
+ entityGroup.setName("Device Group");
+ entityGroup.setType(EntityType.DEVICE);
+ EntityGroup savedEntityGroup = doPost("/api/entityGroup", entityGroup, EntityGroup.class);
+
+ savedEntityGroup.setOwnerId(customerId);
+ doPost("/api/entityGroup", savedEntityGroup)
+ .andExpect(status().isBadRequest())
+ .andExpect(statusReason(containsString("Entity group owner can't be changed!")));
+
+ assertThat(entityGroupService.findEntityGroupById(tenantId, savedEntityGroup.getId()).getOwnerId()).isEqualTo(tenantId);
+ }
+
+ @Test
+ public void testShouldNotChangeEntityGroupType() throws Exception {
+ loginTenantAdmin();
+ EntityGroup entityGroup = new EntityGroup();
+ entityGroup.setName("Device Group");
+ entityGroup.setType(EntityType.DEVICE);
+ EntityGroup savedEntityGroup = doPost("/api/entityGroup", entityGroup, EntityGroup.class);
+
+ savedEntityGroup.setType(EntityType.USER);
+ doPost("/api/entityGroup", savedEntityGroup)
+ .andExpect(status().isBadRequest())
+ .andExpect(statusReason(containsString("Entity group type can't be changed!")));
+
+ assertThat(entityGroupService.findEntityGroupById(tenantId, savedEntityGroup.getId()).getType()).isEqualTo(EntityType.DEVICE);
+ }
+
+ @Test
+ public void testShouldNotMoveTenantEntityGroupToCustomerAsCustomerAdmin() throws Exception {
+ EntityGroup tenantAdministratorsGroup = entityGroupService.findEntityGroupByTypeAndName(tenantId, tenantId,
+ EntityType.USER, EntityGroup.GROUP_TENANT_ADMINS_NAME).get();
+
+ loginCustomerAdminUser();
+ EntityGroup movedEntityGroup = new EntityGroup(tenantAdministratorsGroup);
+ movedEntityGroup.setOwnerId(customerId);
+ doPost("/api/entityGroup", movedEntityGroup)
+ .andExpect(status().isForbidden());
+
+ assertThat(entityGroupService.findEntityGroupById(tenantId, tenantAdministratorsGroup.getId()).getOwnerId()).isEqualTo(tenantId);
+ }
+
+ @Test
+ public void testShouldNotMoveEntityGroupSharedWithWriteAccess() throws Exception {
+ loginTenantAdmin();
+ EntityGroup entityGroup = new EntityGroup();
+ entityGroup.setName("Shared Device Group");
+ entityGroup.setType(EntityType.DEVICE);
+ EntityGroup savedEntityGroup = doPost("/api/entityGroup", entityGroup, EntityGroup.class);
+ var shareGroupRequest = new ShareGroupRequest(customerId, true, null, false, Collections.emptyList());
+ doPost("/api/entityGroup/{entityGroupId}/share", shareGroupRequest, savedEntityGroup.getId().toString())
+ .andExpect(status().isOk());
+
+ loginCustomerAdminUser();
+ EntityGroup sharedEntityGroup = doGet("/api/entityGroup/" + savedEntityGroup.getId().getId(), EntityGroup.class);
+ sharedEntityGroup.setOwnerId(customerId);
+ doPost("/api/entityGroup", sharedEntityGroup)
+ .andExpect(status().isForbidden());
+
+ assertThat(entityGroupService.findEntityGroupById(tenantId, savedEntityGroup.getId()).getOwnerId()).isEqualTo(tenantId);
+ }
+
+ @Test
+ public void testShouldNotMoveOtherTenantEntityGroup() throws Exception {
+ loginDifferentTenant();
+ EntityGroup entityGroup = new EntityGroup();
+ entityGroup.setName("Other Tenant Device Group");
+ entityGroup.setType(EntityType.DEVICE);
+ EntityGroup otherTenantEntityGroup = doPost("/api/entityGroup", entityGroup, EntityGroup.class);
+
+ loginCustomerAdminUser();
+ otherTenantEntityGroup.setOwnerId(customerId);
+ doPost("/api/entityGroup", otherTenantEntityGroup)
+ .andExpect(status().isNotFound());
+
+ assertThat(entityGroupService.findEntityGroupById(differentTenantId, otherTenantEntityGroup.getId()).getOwnerId()).isEqualTo(differentTenantId);
+ }
+
+ @Test
+ public void testGetEntityGroupInfosByIdsReturnsOnlyOwnTenantGroups() throws Exception {
+ loginTenantAdmin();
+ EntityGroup ownGroup = new EntityGroup();
+ ownGroup.setName("Own Device Group");
+ ownGroup.setType(EntityType.DEVICE);
+ ownGroup = doPost("/api/entityGroup", ownGroup, EntityGroup.class);
+
+ loginDifferentTenant();
+ EntityGroup otherTenantGroup = new EntityGroup();
+ otherTenantGroup.setName("Other Tenant Device Group");
+ otherTenantGroup.setType(EntityType.DEVICE);
+ otherTenantGroup = doPost("/api/entityGroup", otherTenantGroup, EntityGroup.class);
+
+ loginTenantAdmin();
+ List entityInfos = doGetTyped("/api/entityGroupInfos?entityGroupIds=" + ownGroup.getId().getId() + "," + otherTenantGroup.getId().getId(),
+ new TypeReference<>() {});
+ assertThat(entityInfos).extracting(EntityInfo::getId).containsExactly(ownGroup.getId());
+ }
+
+ @Test
+ public void testGetEntityGroupInfosByIdsReturnsOnlyReadableGroups() throws Exception {
+ loginTenantAdmin();
+ EntityGroup tenantGroup = new EntityGroup();
+ tenantGroup.setName("Tenant Device Group");
+ tenantGroup.setType(EntityType.DEVICE);
+ tenantGroup = doPost("/api/entityGroup", tenantGroup, EntityGroup.class);
+
+ loginCustomerAdminUser();
+ EntityGroup customerGroup = new EntityGroup();
+ customerGroup.setName("Customer Device Group");
+ customerGroup.setType(EntityType.DEVICE);
+ customerGroup.setOwnerId(customerId);
+ customerGroup = doPost("/api/entityGroup", customerGroup, EntityGroup.class);
+
+ List entityInfos = doGetTyped("/api/entityGroupInfos?entityGroupIds=" + customerGroup.getId().getId() + "," + tenantGroup.getId().getId(),
+ new TypeReference<>() {});
+ assertThat(entityInfos).extracting(EntityInfo::getId).containsExactly(customerGroup.getId());
+ }
+
+ @Test
+ public void testShareGroupWithUserGroupOfOtherTenantReturnsNotFound() throws Exception {
+ loginDifferentTenant();
+ EntityGroup otherTenantUserGroup = new EntityGroup();
+ otherTenantUserGroup.setName("Other Tenant User Group");
+ otherTenantUserGroup.setType(EntityType.USER);
+ otherTenantUserGroup = doPost("/api/entityGroup", otherTenantUserGroup, EntityGroup.class);
+
+ loginTenantAdmin();
+ EntityGroup deviceGroup = new EntityGroup();
+ deviceGroup.setName("Shared Device Group");
+ deviceGroup.setType(EntityType.DEVICE);
+ deviceGroup = doPost("/api/entityGroup", deviceGroup, EntityGroup.class);
+
+ ShareGroupRequest shareGroupRequest = new ShareGroupRequest(tenantId, false, otherTenantUserGroup.getId(), true, null);
+ doPost("/api/entityGroup/" + deviceGroup.getId().getId() + "/share", shareGroupRequest)
+ .andExpect(status().isNotFound())
+ .andExpect(statusReason(not(containsString(otherTenantUserGroup.getName()))));
+ }
+
+ @Test
+ public void testShareGroupV2WithUserGroupOfOtherTenantReturnsNotFound() throws Exception {
+ loginDifferentTenant();
+ EntityGroup otherTenantUserGroup = new EntityGroup();
+ otherTenantUserGroup.setName("Other Tenant User Group");
+ otherTenantUserGroup.setType(EntityType.USER);
+ otherTenantUserGroup = doPost("/api/entityGroup", otherTenantUserGroup, EntityGroup.class);
+
+ loginTenantAdmin();
+ EntityGroup deviceGroup = new EntityGroup();
+ deviceGroup.setName("Shared Device Group");
+ deviceGroup.setType(EntityType.DEVICE);
+ deviceGroup = doPost("/api/entityGroup", deviceGroup, EntityGroup.class);
+
+ ShareGroupRequest shareGroupRequest = new ShareGroupRequest(tenantId, false, otherTenantUserGroup.getId(), true, null);
+ doPost("/api/v2/entityGroup/" + deviceGroup.getId().getId() + "/share", shareGroupRequest)
+ .andExpect(status().isNotFound())
+ .andExpect(statusReason(not(containsString(otherTenantUserGroup.getName()))));
+ }
+
+ @Test
+ public void testShareGroupWithAllUsersGroupOfOtherTenantReturnsNotFound() throws Exception {
+ loginDifferentTenant();
+ loginTenantAdmin();
+ EntityGroup deviceGroup = createDeviceGroup("Shared Device Group", tenantId);
+
+ ShareGroupRequest unknownOwnerRequest = new ShareGroupRequest(TenantId.fromUUID(UUID.randomUUID()), true, null, true, null);
+ doPost("/api/entityGroup/{entityGroupId}/share", unknownOwnerRequest, deviceGroup.getId().toString())
+ .andExpect(status().isNotFound())
+ .andExpect(statusReason(is(msgErrorNotFound)));
+ ShareGroupRequest otherTenantRequest = new ShareGroupRequest(differentTenantId, true, null, true, null);
+ doPost("/api/entityGroup/{entityGroupId}/share", otherTenantRequest, deviceGroup.getId().toString())
+ .andExpect(status().isNotFound())
+ .andExpect(statusReason(is(msgErrorNotFound)));
+ assertThat(findSharedUserGroupIds(deviceGroup)).isEmpty();
+ }
+
+ @Test
+ public void testShareGroupWithAllUsersGroupOfOwnCustomerSharesWithThatGroup() throws Exception {
+ loginTenantAdmin();
+ EntityGroup deviceGroup = createDeviceGroup("Shared Device Group", tenantId);
+ EntityGroup customerAllUsersGroup = entityGroupService.findEntityGroupByTypeAndName(tenantId, customerId,
+ EntityType.USER, EntityGroup.GROUP_ALL_NAME).get();
+
+ ShareGroupRequest shareGroupRequest = new ShareGroupRequest(customerId, true, null, true, null);
+ doPost("/api/entityGroup/{entityGroupId}/share", shareGroupRequest, deviceGroup.getId().toString())
+ .andExpect(status().isOk());
+ assertThat(findSharedUserGroupIds(deviceGroup)).containsExactly(customerAllUsersGroup.getId());
+ }
+
+ @Test
+ public void testShareGroupV2WithAllUsersGroupOfOtherTenantReturnsNotFound() throws Exception {
+ loginDifferentTenant();
+ loginTenantAdmin();
+ EntityGroup deviceGroup = createDeviceGroup("Shared Device Group", tenantId);
+
+ ShareGroupRequest unknownOwnerRequest = new ShareGroupRequest(TenantId.fromUUID(UUID.randomUUID()), true, null, true, null);
+ doPost("/api/v2/entityGroup/{entityGroupId}/share", unknownOwnerRequest, deviceGroup.getId().toString())
+ .andExpect(status().isNotFound())
+ .andExpect(statusReason(is(msgErrorNotFound)));
+ ShareGroupRequest otherTenantRequest = new ShareGroupRequest(differentTenantId, true, null, true, null);
+ doPost("/api/v2/entityGroup/{entityGroupId}/share", otherTenantRequest, deviceGroup.getId().toString())
+ .andExpect(status().isNotFound())
+ .andExpect(statusReason(is(msgErrorNotFound)));
+ assertThat(findSharedUserGroupIds(deviceGroup)).isEmpty();
+ }
+
+ @Test
+ public void testShareGroupV2WithAllUsersGroupOfOwnCustomerSharesWithThatGroup() throws Exception {
+ loginTenantAdmin();
+ EntityGroup deviceGroup = createDeviceGroup("Shared Device Group", tenantId);
+ EntityGroup customerAllUsersGroup = entityGroupService.findEntityGroupByTypeAndName(tenantId, customerId,
+ EntityType.USER, EntityGroup.GROUP_ALL_NAME).get();
+
+ ShareGroupRequest shareGroupRequest = new ShareGroupRequest(customerId, true, null, true, null);
+ doPost("/api/v2/entityGroup/{entityGroupId}/share", shareGroupRequest, deviceGroup.getId().toString())
+ .andExpect(status().isOk());
+ assertThat(findSharedUserGroupIds(deviceGroup)).containsExactly(customerAllUsersGroup.getId());
+ }
+
+ @Test
+ public void testShareGroupToChildOwnerUserGroupWithGroupsOfOtherTenantReturnsNotFound() throws Exception {
+ loginDifferentTenant();
+ EntityGroup otherTenantUserGroup = new EntityGroup();
+ otherTenantUserGroup.setName("Other Tenant User Group");
+ otherTenantUserGroup.setType(EntityType.USER);
+ otherTenantUserGroup = doPost("/api/entityGroup", otherTenantUserGroup, EntityGroup.class);
+ EntityGroup otherTenantDeviceGroup = new EntityGroup();
+ otherTenantDeviceGroup.setName("Other Tenant Device Group");
+ otherTenantDeviceGroup.setType(EntityType.DEVICE);
+ otherTenantDeviceGroup = doPost("/api/entityGroup", otherTenantDeviceGroup, EntityGroup.class);
+
+ loginTenantAdmin();
+ EntityGroup deviceGroup = new EntityGroup();
+ deviceGroup.setName("Shared Device Group");
+ deviceGroup.setType(EntityType.DEVICE);
+ deviceGroup = doPost("/api/entityGroup", deviceGroup, EntityGroup.class);
+ EntityGroup userGroup = new EntityGroup();
+ userGroup.setName("Own User Group");
+ userGroup.setType(EntityType.USER);
+ userGroup = doPost("/api/entityGroup", userGroup, EntityGroup.class);
+ Role role = new Role();
+ role.setName("Read Group Role");
+ role.setType(RoleType.GROUP);
+ role.setPermissions(JacksonUtil.valueToTree(List.of(Operation.READ)));
+ role = doPost("/api/role", role, Role.class);
+
+ doPost("/api/entityGroup/" + deviceGroup.getId().getId() + "/" + otherTenantUserGroup.getId().getId() + "/" + role.getId().getId() + "/share")
+ .andExpect(status().isNotFound());
+ doPost("/api/entityGroup/" + otherTenantDeviceGroup.getId().getId() + "/" + userGroup.getId().getId() + "/" + role.getId().getId() + "/share")
+ .andExpect(status().isNotFound());
+ }
+
+ @Test
+ public void testGetAttributesOfEntityGroupOfOtherTenantReturnsNotFound() throws Exception {
+ loginDifferentTenant();
+ EntityGroup otherTenantGroup = new EntityGroup();
+ otherTenantGroup.setName("Other Tenant Asset Group");
+ otherTenantGroup.setType(EntityType.ASSET);
+ otherTenantGroup = doPost("/api/entityGroup", otherTenantGroup, EntityGroup.class);
+
+ loginTenantAdmin();
+ doGetAsync("/api/plugins/telemetry/ENTITY_GROUP/" + otherTenantGroup.getId().getId() + "/values/attributes")
+ .andExpect(status().isNotFound());
+ }
+
+ @Test
+ public void testGetEntityGroupOfOtherTenantReturnsNotFound() throws Exception {
+ loginDifferentTenant();
+ EntityGroup otherTenantGroup = new EntityGroup();
+ otherTenantGroup.setName("Other Tenant Asset Group");
+ otherTenantGroup.setType(EntityType.ASSET);
+ otherTenantGroup = doPost("/api/entityGroup", otherTenantGroup, EntityGroup.class);
+
+ loginTenantAdmin();
+ doGet("/api/entityGroup/" + otherTenantGroup.getId().getId())
+ .andExpect(status().isNotFound())
+ .andExpect(statusReason(not(containsString(otherTenantGroup.getName()))));
+ }
+
+ @Test
+ public void testShouldNotUpdateNonExistingEntityGroup() throws Exception {
+ loginTenantAdmin();
+ EntityGroup entityGroup = new EntityGroup();
+ entityGroup.setId(new EntityGroupId(UUID.randomUUID()));
+ entityGroup.setName("Non-existing Device Group");
+ entityGroup.setType(EntityType.DEVICE);
+ entityGroup.setOwnerId(tenantId);
+ doPost("/api/entityGroup", entityGroup)
+ .andExpect(status().isNotFound());
+ }
+
@Test
public void testSaveEntityGroupWithSameName() throws Exception {
EntityGroup entityGroup = new EntityGroup();
@@ -314,4 +626,164 @@ public class EntityGroupControllerTest extends AbstractControllerTest {
Assert.assertNotNull(foundDashboard2);
}
+ @Test
+ public void testShareEntityGroupWithGroupRole() throws Exception {
+ loginTenantAdmin();
+ EntityGroup deviceGroup = createDeviceGroup("Device Group", tenantId);
+ Role groupRole = createRole(tenantId, null, "Read role", RoleType.GROUP, "[\"READ\"]");
+
+ shareWithRoles(deviceGroup, customerId, groupRole.getId())
+ .andExpect(status().isOk());
+
+ assertThat(findSharedRoleIds(deviceGroup)).containsExactly(groupRole.getId());
+ }
+
+ @Test
+ public void testShareEntityGroupRejectsGenericRole() throws Exception {
+ loginTenantAdmin();
+ EntityGroup deviceGroup = createDeviceGroup("Device Group", tenantId);
+ Role genericRole = createRole(tenantId, null, "Generic role", RoleType.GENERIC, "{\"DEVICE\":[\"READ\"]}");
+
+ shareWithRoles(deviceGroup, customerId, genericRole.getId())
+ .andExpect(status().isBadRequest());
+
+ assertThat(findSharedRoleIds(deviceGroup)).isEmpty();
+ }
+
+ @Test
+ public void testShareEntityGroupRequiresReadableRole() throws Exception {
+ createDifferentTenant();
+ Role otherTenantRole = createRole(differentTenantId, null, "Read role", RoleType.GROUP, "[\"READ\"]");
+
+ loginTenantAdmin();
+ EntityGroup deviceGroup = createDeviceGroup("Device Group", tenantId);
+
+ shareWithRoles(deviceGroup, customerId, otherTenantRole.getId())
+ .andExpect(status().isForbidden());
+
+ assertThat(findSharedRoleIds(deviceGroup)).isEmpty();
+ }
+
+ @Test
+ public void testShareEntityGroupSavesNothingWhenAnyRoleRejected() throws Exception {
+ loginTenantAdmin();
+ EntityGroup deviceGroup = createDeviceGroup("Device Group", tenantId);
+ Role groupRole = createRole(tenantId, null, "Read role", RoleType.GROUP, "[\"READ\"]");
+ Role genericRole = createRole(tenantId, null, "Generic role", RoleType.GENERIC, "{\"DEVICE\":[\"READ\"]}");
+
+ shareWithRoles(deviceGroup, customerId, groupRole.getId(), genericRole.getId())
+ .andExpect(status().isBadRequest());
+
+ assertThat(findSharedRoleIds(deviceGroup)).isEmpty();
+ }
+
+ @Test
+ public void testShareEntityGroupRequiresRoleOperationsHeldByUser() throws Exception {
+ loginTenantAdmin();
+ User manager = createGroupManager(createCustomerUserGroup(), GROUP_MANAGER_PERMISSIONS);
+ EntityGroup deviceGroup = createDeviceGroup("Customer Device Group", customerId);
+ Role readRole = createRole(tenantId, customerId, "Read role", RoleType.GROUP, "[\"READ\"]");
+ Role rpcRole = createRole(tenantId, customerId, "Read and RPC role", RoleType.GROUP, "[\"READ\",\"RPC_CALL\"]");
+
+ login(manager.getEmail(), "manager");
+ shareWithRoles(deviceGroup, customerId, rpcRole.getId())
+ .andExpect(status().isForbidden());
+ assertThat(findSharedRoleIds(deviceGroup)).isEmpty();
+
+ shareWithRoles(deviceGroup, customerId, readRole.getId())
+ .andExpect(status().isOk());
+ assertThat(findSharedRoleIds(deviceGroup)).containsExactly(readRole.getId());
+ }
+
+ @Test
+ public void testShareEntityGroupAllowsRoleOperationsHeldOnEntities() throws Exception {
+ loginTenantAdmin();
+ User manager = createGroupManager(createCustomerUserGroup(),
+ "{\"DEVICE_GROUP\":[\"READ\",\"WRITE\"],\"DEVICE\":[\"RPC_CALL\"],\"USER_GROUP\":[\"READ\",\"WRITE\"],\"GROUP_PERMISSION\":[\"CREATE\"],\"ROLE\":[\"READ\"]}");
+ EntityGroup deviceGroup = createDeviceGroup("Customer Device Group", customerId);
+ Role rpcRole = createRole(tenantId, customerId, "Read and RPC role", RoleType.GROUP, "[\"READ\",\"RPC_CALL\"]");
+
+ login(manager.getEmail(), "manager");
+ shareWithRoles(deviceGroup, customerId, rpcRole.getId())
+ .andExpect(status().isOk());
+ assertThat(findSharedRoleIds(deviceGroup)).containsExactly(rpcRole.getId());
+ }
+
+ @Test
+ public void testShareEntityGroupAllowsRoleOperationsHeldOnSharedGroup() throws Exception {
+ loginTenantAdmin();
+ EntityGroup managers = createCustomerUserGroup();
+ User manager = createGroupManager(managers, GROUP_MANAGER_PERMISSIONS);
+ EntityGroup deviceGroup = createDeviceGroup("Customer Device Group", customerId);
+ Role groupRpcRole = createRole(tenantId, customerId, "RPC role", RoleType.GROUP, "[\"RPC_CALL\"]");
+ GroupPermission groupRpcPermission = new GroupPermission();
+ groupRpcPermission.setRoleId(groupRpcRole.getId());
+ groupRpcPermission.setUserGroupId(managers.getId());
+ groupRpcPermission.setEntityGroupId(deviceGroup.getId());
+ groupRpcPermission.setEntityGroupType(deviceGroup.getType());
+ doPost("/api/groupPermission", groupRpcPermission, GroupPermission.class);
+ Role rpcRole = createRole(tenantId, customerId, "Read and RPC role", RoleType.GROUP, "[\"READ\",\"RPC_CALL\"]");
+
+ login(manager.getEmail(), "manager");
+ shareWithRoles(deviceGroup, customerId, rpcRole.getId())
+ .andExpect(status().isOk());
+ assertThat(findSharedRoleIds(deviceGroup)).contains(rpcRole.getId());
+ }
+
+ private EntityGroup createCustomerUserGroup() throws Exception {
+ EntityGroup userGroup = new EntityGroup();
+ userGroup.setType(EntityType.USER);
+ userGroup.setName("Group managers");
+ userGroup.setOwnerId(customerId);
+ return doPost("/api/entityGroup", userGroup, EntityGroup.class);
+ }
+
+ private User createGroupManager(EntityGroup userGroup, String permissions) throws Exception {
+ Role managerRole = createRole(tenantId, customerId, "Group manager", RoleType.GENERIC, permissions);
+ GroupPermission managerPermission = new GroupPermission();
+ managerPermission.setRoleId(managerRole.getId());
+ managerPermission.setUserGroupId(userGroup.getId());
+ doPost("/api/groupPermission", managerPermission, GroupPermission.class);
+
+ User manager = new User();
+ manager.setAuthority(Authority.CUSTOMER_USER);
+ manager.setTenantId(tenantId);
+ manager.setCustomerId(customerId);
+ manager.setEmail("groupmanager@thingsboard.org");
+ return createUser(manager, "manager", userGroup.getId());
+ }
+
+ private EntityGroup createDeviceGroup(String name, EntityId ownerId) throws Exception {
+ EntityGroup entityGroup = new EntityGroup();
+ entityGroup.setType(EntityType.DEVICE);
+ entityGroup.setName(name);
+ entityGroup.setOwnerId(ownerId);
+ return doPost("/api/entityGroup", entityGroup, EntityGroup.class);
+ }
+
+ private Role createRole(TenantId roleTenantId, CustomerId roleCustomerId, String name, RoleType type, String permissions) {
+ Role role = new Role();
+ role.setTenantId(roleTenantId);
+ role.setCustomerId(roleCustomerId);
+ role.setType(type);
+ role.setName(name);
+ role.setPermissions(JacksonUtil.toJsonNode(permissions));
+ return roleService.saveRole(roleTenantId, role);
+ }
+
+ private ResultActions shareWithRoles(EntityGroup entityGroup, CustomerId targetCustomerId, RoleId... roleIds) throws Exception {
+ var shareGroupRequest = new ShareGroupRequest(targetCustomerId, true, null, false, List.of(roleIds));
+ return doPost("/api/entityGroup/{entityGroupId}/share", shareGroupRequest, entityGroup.getId().toString());
+ }
+
+ private List findSharedRoleIds(EntityGroup entityGroup) {
+ return groupPermissionService.findGroupPermissionByTenantIdAndEntityGroupId(tenantId, entityGroup.getId(), new PageLink(100))
+ .getData().stream().map(GroupPermission::getRoleId).collect(Collectors.toList());
+ }
+
+ private List findSharedUserGroupIds(EntityGroup entityGroup) {
+ return groupPermissionService.findGroupPermissionByTenantIdAndEntityGroupId(tenantId, entityGroup.getId(), new PageLink(100))
+ .getData().stream().map(GroupPermission::getUserGroupId).collect(Collectors.toList());
+ }
+
}
diff --git a/application/src/test/java/org/thingsboard/server/controller/EntityViewControllerTest.java b/application/src/test/java/org/thingsboard/server/controller/EntityViewControllerTest.java
index 12561a35d2..48c508f43f 100644
--- a/application/src/test/java/org/thingsboard/server/controller/EntityViewControllerTest.java
+++ b/application/src/test/java/org/thingsboard/server/controller/EntityViewControllerTest.java
@@ -353,6 +353,94 @@ public class EntityViewControllerTest extends AbstractControllerTest {
deleteDifferentTenant();
}
+ @Test
+ public void testSaveEntityViewWithEntityOfOtherTenant() throws Exception {
+ loginDifferentTenant();
+
+ String name = "Entity view of other tenant device";
+ EntityView entityView = createEntityView(name, 0, 0);
+ doPost("/api/entityView", entityView)
+ .andExpect(status().is4xxClientError());
+
+ doGet("/api/tenant/entityViews?entityViewName=" + name)
+ .andExpect(status().isNotFound());
+
+ deleteDifferentTenant();
+ }
+
+ @Test
+ public void testUpdateEntityViewByCustomerUserToEntityNotAssignedToCustomer() throws Exception {
+ EntityView savedView = getNewSavedEntityView("Customer entity view");
+ doPost("/api/owner/CUSTOMER/" + customerId.getId() + "/ENTITY_VIEW/" + savedView.getId().getId()).andExpect(status().isOk());
+ doPost("/api/owner/CUSTOMER/" + customerId.getId() + "/DEVICE/" + testDevice.getId().getId()).andExpect(status().isOk());
+
+ Device otherDevice = new Device();
+ otherDevice.setName("Device not assigned to customer");
+ otherDevice.setType("default");
+ otherDevice = doPost("/api/device", otherDevice, Device.class);
+
+ loginCustomerAdminUser();
+
+ EntityView customerView = doGet("/api/entityView/" + savedView.getId().getId(), EntityView.class);
+ customerView.setEntityId(otherDevice.getId());
+ doPost("/api/entityView", customerView)
+ .andExpect(status().isForbidden());
+
+ EntityView foundView = doGet("/api/entityView/" + savedView.getId().getId(), EntityView.class);
+ assertEquals(testDevice.getId(), foundView.getEntityId());
+ }
+
+ @Test
+ public void testUpdateEntityViewByCustomerUserKeepingEntity() throws Exception {
+ EntityView savedView = getNewSavedEntityView("Customer entity view");
+ doPost("/api/owner/CUSTOMER/" + customerId.getId() + "/ENTITY_VIEW/" + savedView.getId().getId()).andExpect(status().isOk());
+
+ loginCustomerAdminUser();
+
+ EntityView customerView = doGet("/api/entityView/" + savedView.getId().getId(), EntityView.class);
+ customerView.setName("Customer entity view renamed");
+ EntityView updatedView = doPost("/api/entityView", customerView, EntityView.class);
+
+ assertEquals("Customer entity view renamed", updatedView.getName());
+ assertEquals(testDevice.getId(), updatedView.getEntityId());
+ }
+
+ @Test
+ public void testUpdateEntityViewKeysByCustomerUserWithEntityNotAssignedToCustomer() throws Exception {
+ EntityView savedView = getNewSavedEntityView("Customer entity view");
+ doPost("/api/owner/CUSTOMER/" + customerId.getId() + "/ENTITY_VIEW/" + savedView.getId().getId()).andExpect(status().isOk());
+
+ loginCustomerAdminUser();
+
+ EntityView customerView = doGet("/api/entityView/" + savedView.getId().getId(), EntityView.class);
+ customerView.setKeys(new TelemetryEntityView(List.of("tsKey1"), new AttributesEntityView()));
+ doPost("/api/entityView", customerView)
+ .andExpect(status().isForbidden());
+
+ customerView = doGet("/api/entityView/" + savedView.getId().getId(), EntityView.class);
+ customerView.setStartTimeMs(1L);
+ doPost("/api/entityView", customerView)
+ .andExpect(status().isForbidden());
+
+ EntityView foundView = doGet("/api/entityView/" + savedView.getId().getId(), EntityView.class);
+ assertEquals(telemetry, foundView.getKeys());
+ assertEquals(0L, foundView.getStartTimeMs());
+ }
+
+ @Test
+ public void testFindEntityViewByOldNameAfterRename() throws Exception {
+ String oldName = "Entity view old name";
+ EntityView savedView = getNewSavedEntityView(oldName);
+ doGet("/api/tenant/entityViews?entityViewName=" + oldName)
+ .andExpect(status().isOk());
+
+ savedView.setName("Entity view new name");
+ doPost("/api/entityView", savedView, EntityView.class);
+
+ doGet("/api/tenant/entityViews?entityViewName=" + oldName)
+ .andExpect(status().isNotFound());
+ }
+
@Test
public void testDeleteEntityView() throws Exception {
Customer customer = doPost("/api/customer", getNewCustomer("My customer"), Customer.class);
@@ -380,6 +468,7 @@ public class EntityViewControllerTest extends AbstractControllerTest {
public void testSaveEntityViewWithEmptyName() throws Exception {
EntityView entityView = new EntityView();
entityView.setType("default");
+ entityView.setEntityId(testDevice.getId());
Mockito.reset(tbClusterService, auditLogService);
diff --git a/application/src/test/java/org/thingsboard/server/controller/GroupPermissionControllerTest.java b/application/src/test/java/org/thingsboard/server/controller/GroupPermissionControllerTest.java
index 342151bee4..dd16575a86 100644
--- a/application/src/test/java/org/thingsboard/server/controller/GroupPermissionControllerTest.java
+++ b/application/src/test/java/org/thingsboard/server/controller/GroupPermissionControllerTest.java
@@ -3,23 +3,27 @@
package org.thingsboard.server.controller;
import com.fasterxml.jackson.core.type.TypeReference;
+import org.apache.commons.lang3.RandomStringUtils;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
-import org.testcontainers.shaded.org.apache.commons.lang3.RandomStringUtils;
+import org.springframework.beans.factory.annotation.Autowired;
import org.thingsboard.server.common.data.Customer;
import org.thingsboard.server.common.data.EntityType;
import org.thingsboard.server.common.data.Tenant;
import org.thingsboard.server.common.data.User;
import org.thingsboard.server.common.data.group.EntityGroup;
import org.thingsboard.server.common.data.id.EntityId;
+import org.thingsboard.server.common.data.page.PageLink;
import org.thingsboard.server.common.data.permission.AllowedPermissionsInfo;
import org.thingsboard.server.common.data.permission.GroupPermission;
import org.thingsboard.server.common.data.permission.GroupPermissionInfo;
+import org.thingsboard.server.common.data.permission.ShareGroupRequest;
import org.thingsboard.server.common.data.role.Role;
import org.thingsboard.server.common.data.role.RoleType;
import org.thingsboard.server.common.data.security.Authority;
+import org.thingsboard.server.dao.grouppermission.GroupPermissionService;
import org.thingsboard.server.dao.service.DaoSqlTest;
import java.util.ArrayList;
@@ -35,6 +39,9 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.
@DaoSqlTest
public class GroupPermissionControllerTest extends AbstractControllerTest {
+ @Autowired
+ private GroupPermissionService groupPermissionService;
+
private IdComparator idComparator;
private Tenant savedTenant;
private User tenantAdmin;
@@ -278,6 +285,222 @@ public class GroupPermissionControllerTest extends AbstractControllerTest {
checkPermissionOwners(loadedGroupPermissionsInfo, List.of(subCustomerId));
}
+ @Test
+ public void testLoadUserGroupPermissionInfosReturnsOnlyOwnTenantData() throws Exception {
+ loginDifferentTenant();
+ Role otherTenantRole = doPost("/api/role", newRole("Other Tenant Role", RoleType.GROUP), Role.class);
+ EntityGroup otherTenantGroup = new EntityGroup();
+ otherTenantGroup.setType(EntityType.DEVICE);
+ otherTenantGroup.setName("Other Tenant Device Group");
+ otherTenantGroup = doPost("/api/entityGroup", otherTenantGroup, EntityGroup.class);
+
+ loginTenantAdmin();
+ Role ownRole = doPost("/api/role", newRole("Own Role", RoleType.GROUP), Role.class);
+
+ GroupPermission otherTenantRolePermission = new GroupPermission();
+ otherTenantRolePermission.setRoleId(otherTenantRole.getId());
+ GroupPermission otherTenantGroupPermission = new GroupPermission();
+ otherTenantGroupPermission.setRoleId(ownRole.getId());
+ otherTenantGroupPermission.setEntityGroupId(otherTenantGroup.getId());
+
+ List infos = doPostWithTypedResponse("/api/userGroup/groupPermissions/info",
+ List.of(otherTenantRolePermission, otherTenantGroupPermission), new TypeReference<>() {});
+ assertThat(infos).isEmpty();
+ }
+
+ @Test
+ public void testLoadUserGroupPermissionInfosReturnsOnlyReadableGroups() throws Exception {
+ loginTenantAdmin();
+ Role role = doPost("/api/role", newRole("Group Role", RoleType.GROUP), Role.class);
+ EntityGroup tenantGroup = new EntityGroup();
+ tenantGroup.setType(EntityType.DEVICE);
+ tenantGroup.setName("Tenant Device Group");
+ tenantGroup = doPost("/api/entityGroup", tenantGroup, EntityGroup.class);
+
+ loginCustomerAdminUser();
+ EntityGroup customerGroup = new EntityGroup();
+ customerGroup.setType(EntityType.DEVICE);
+ customerGroup.setName("Customer Device Group");
+ customerGroup.setOwnerId(customerId);
+ customerGroup = doPost("/api/entityGroup", customerGroup, EntityGroup.class);
+
+ GroupPermission tenantGroupPermission = new GroupPermission();
+ tenantGroupPermission.setRoleId(role.getId());
+ tenantGroupPermission.setEntityGroupId(tenantGroup.getId());
+ GroupPermission customerGroupPermission = new GroupPermission();
+ customerGroupPermission.setRoleId(role.getId());
+ customerGroupPermission.setEntityGroupId(customerGroup.getId());
+
+ List infos = doPostWithTypedResponse("/api/userGroup/groupPermissions/info",
+ List.of(tenantGroupPermission, customerGroupPermission), new TypeReference<>() {});
+ assertThat(infos).extracting(GroupPermissionInfo::getEntityGroupId).containsExactly(customerGroup.getId());
+ }
+
+ @Test
+ public void testLoadUserGroupPermissionInfosKeepsSystemRoles() throws Exception {
+ loginTenantAdmin();
+ EntityGroup tenantAdminsGroup = findGroupByOwnerIdTypeAndName(tenantId, EntityType.USER, EntityGroup.GROUP_TENANT_ADMINS_NAME);
+ List storedInfos = doGetTyped("/api/userGroup/" + tenantAdminsGroup.getId() + "/groupPermissions",
+ new TypeReference<>() {});
+ assertThat(storedInfos).isNotEmpty();
+ assertThat(storedInfos).allSatisfy(info -> assertThat(info.getRole().getTenantId().isSysTenantId()).isTrue());
+
+ List permissions = storedInfos.stream().map(GroupPermission::new).toList();
+ List infos = doPostWithTypedResponse("/api/userGroup/groupPermissions/info", permissions, new TypeReference<>() {});
+ assertThat(infos).hasSameSizeAs(permissions);
+ assertThat(infos).allSatisfy(info -> assertThat(info.getRole()).isNotNull());
+ }
+
+ @Test
+ public void testShareGroupWithRoleOfOtherTenantIsRejected() throws Exception {
+ loginDifferentTenant();
+ Role otherTenantRole = doPost("/api/role", newRole("Other Tenant Role", RoleType.GROUP), Role.class);
+
+ loginTenantAdmin();
+ EntityGroup deviceGroup = new EntityGroup();
+ deviceGroup.setType(EntityType.DEVICE);
+ deviceGroup.setName("Shared Device Group");
+ deviceGroup = doPost("/api/entityGroup", deviceGroup, EntityGroup.class);
+
+ ShareGroupRequest shareGroupRequest = new ShareGroupRequest(tenantId, true, null, false, List.of(otherTenantRole.getId()));
+ doPost("/api/entityGroup/{entityGroupId}/share", shareGroupRequest, deviceGroup.getId().toString())
+ .andExpect(status().isForbidden());
+
+ assertThat(groupPermissionService.findGroupPermissionByTenantIdAndRoleId(tenantId, otherTenantRole.getId(), new PageLink(10)).getData()).isEmpty();
+ }
+
+ private Role newRole(String roleName, RoleType roleType) {
+ Role role = new Role();
+ role.setName(roleName);
+ role.setType(roleType);
+ return role;
+ }
+
+ @Test
+ public void testCustomerAdminCannotUpdateTenantGroupPermission() throws Exception {
+ loginTenantAdmin();
+ EntityGroup tenantUserGroup = saveUserGroup("Tenant users");
+ Role tenantRole = doPost("/api/role", createRole("Tenant role", RoleType.GENERIC), Role.class);
+ GroupPermission groupPermission = new GroupPermission();
+ groupPermission.setRoleId(tenantRole.getId());
+ groupPermission.setUserGroupId(tenantUserGroup.getId());
+ groupPermission = doPost("/api/groupPermission", groupPermission, GroupPermission.class);
+
+ loginCustomerAdminUser();
+ Role customerRole = doPost("/api/role", createRole("Customer role", RoleType.GENERIC), Role.class);
+ GroupPermission update = new GroupPermission(groupPermission);
+ update.setUserGroupId(findCustomerAdminsGroup(customerId).getId());
+ update.setRoleId(customerRole.getId());
+ doPost("/api/groupPermission", update).andExpect(status().isForbidden());
+
+ loginTenantAdmin();
+ GroupPermission stored = doGet("/api/groupPermission/" + groupPermission.getUuidId(), GroupPermission.class);
+ assertEquals(tenantUserGroup.getId(), stored.getUserGroupId());
+ assertEquals(tenantRole.getId(), stored.getRoleId());
+ }
+
+ @Test
+ public void testCustomerAdminCannotMoveGroupPermissionFromTenantUserGroup() throws Exception {
+ loginCustomerAdminUser();
+ Role customerRole = doPost("/api/role", createRole("Customer role", RoleType.GENERIC), Role.class);
+ EntityGroup customerUserGroup = saveUserGroup("Customer users");
+
+ loginTenantAdmin();
+ EntityGroup tenantUserGroup = saveUserGroup("Tenant users");
+ GroupPermission groupPermission = new GroupPermission();
+ groupPermission.setRoleId(customerRole.getId());
+ groupPermission.setUserGroupId(tenantUserGroup.getId());
+ groupPermission = doPost("/api/groupPermission", groupPermission, GroupPermission.class);
+
+ loginCustomerAdminUser();
+ GroupPermission update = new GroupPermission(groupPermission);
+ update.setUserGroupId(customerUserGroup.getId());
+ doPost("/api/groupPermission", update).andExpect(status().isForbidden());
+
+ loginTenantAdmin();
+ GroupPermission stored = doGet("/api/groupPermission/" + groupPermission.getUuidId(), GroupPermission.class);
+ assertEquals(tenantUserGroup.getId(), stored.getUserGroupId());
+ }
+
+ @Test
+ public void testCustomerAdminCannotUpdateGroupPermissionOfTenantEntityGroup() throws Exception {
+ loginCustomerAdminUser();
+ Role customerRole = doPost("/api/role", createRole("Customer group role", RoleType.GROUP), Role.class);
+ EntityGroup customerUserGroup = saveUserGroup("Customer users");
+ EntityGroup customerDeviceGroup = saveDeviceGroup("Customer devices");
+
+ loginTenantAdmin();
+ EntityGroup tenantDeviceGroup = saveDeviceGroup("Tenant devices");
+ GroupPermission groupPermission = new GroupPermission();
+ groupPermission.setRoleId(customerRole.getId());
+ groupPermission.setUserGroupId(customerUserGroup.getId());
+ groupPermission.setEntityGroupId(tenantDeviceGroup.getId());
+ groupPermission = doPost("/api/groupPermission", groupPermission, GroupPermission.class);
+
+ loginCustomerAdminUser();
+ GroupPermission update = new GroupPermission(groupPermission);
+ update.setEntityGroupId(customerDeviceGroup.getId());
+ doPost("/api/groupPermission", update).andExpect(status().isForbidden());
+
+ loginTenantAdmin();
+ GroupPermission stored = doGet("/api/groupPermission/" + groupPermission.getUuidId(), GroupPermission.class);
+ assertEquals(tenantDeviceGroup.getId(), stored.getEntityGroupId());
+ }
+
+ @Test
+ public void testPublicGroupPermissionIsNotUpdatable() throws Exception {
+ loginTenantAdmin();
+ EntityGroup deviceGroup = saveDeviceGroup("Public devices");
+ doPost("/api/entityGroup/" + deviceGroup.getUuidId() + "/makePublic").andExpect(status().isOk());
+ List permissions = doGetTyped("/api/entityGroup/" + deviceGroup.getUuidId() + "/groupPermissions",
+ new TypeReference<>() {});
+ assertEquals(1, permissions.size());
+ GroupPermission publicPermission = doGet("/api/groupPermission/" + permissions.get(0).getUuidId(), GroupPermission.class);
+ assertTrue(publicPermission.isPublic());
+
+ EntityGroup userGroup = saveUserGroup("Other users");
+ GroupPermission update = new GroupPermission(publicPermission);
+ update.setPublic(false);
+ update.setUserGroupId(userGroup.getId());
+ doPost("/api/groupPermission", update).andExpect(status().isForbidden());
+
+ GroupPermission stored = doGet("/api/groupPermission/" + publicPermission.getUuidId(), GroupPermission.class);
+ assertTrue(stored.isPublic());
+ assertEquals(publicPermission.getUserGroupId(), stored.getUserGroupId());
+ }
+
+ @Test
+ public void testCustomerAdminUpdatesOwnGroupPermission() throws Exception {
+ loginCustomerAdminUser();
+ EntityGroup firstUserGroup = saveUserGroup("First customer users");
+ EntityGroup secondUserGroup = saveUserGroup("Second customer users");
+ Role role = doPost("/api/role", createRole("Customer role", RoleType.GENERIC), Role.class);
+ GroupPermission groupPermission = new GroupPermission();
+ groupPermission.setRoleId(role.getId());
+ groupPermission.setUserGroupId(firstUserGroup.getId());
+ groupPermission = doPost("/api/groupPermission", groupPermission, GroupPermission.class);
+
+ groupPermission.setUserGroupId(secondUserGroup.getId());
+ doPost("/api/groupPermission", groupPermission).andExpect(status().isOk());
+
+ GroupPermission stored = doGet("/api/groupPermission/" + groupPermission.getUuidId(), GroupPermission.class);
+ assertEquals(secondUserGroup.getId(), stored.getUserGroupId());
+ }
+
+ private EntityGroup saveUserGroup(String name) throws Exception {
+ EntityGroup userGroup = new EntityGroup();
+ userGroup.setType(EntityType.USER);
+ userGroup.setName(name);
+ return doPost("/api/entityGroup", userGroup, EntityGroup.class);
+ }
+
+ private EntityGroup saveDeviceGroup(String name) throws Exception {
+ EntityGroup deviceGroup = new EntityGroup();
+ deviceGroup.setType(EntityType.DEVICE);
+ deviceGroup.setName(name);
+ return doPost("/api/entityGroup", deviceGroup, EntityGroup.class);
+ }
+
private void checkPermissionOwners(List groupPermissionsInfos, List extends EntityId> ownerIds) {
for (GroupPermissionInfo groupPermissionInfo : groupPermissionsInfos) {
assertTrue(ownerIds.contains(groupPermissionInfo.getUserGroupOwnerId()));
diff --git a/application/src/test/java/org/thingsboard/server/controller/ImageControllerTest.java b/application/src/test/java/org/thingsboard/server/controller/ImageControllerTest.java
index d37121847d..eff12bf015 100644
--- a/application/src/test/java/org/thingsboard/server/controller/ImageControllerTest.java
+++ b/application/src/test/java/org/thingsboard/server/controller/ImageControllerTest.java
@@ -307,7 +307,7 @@ public class ImageControllerTest extends AbstractControllerTest {
Map expectedHeaders = Map.of(
"Baker Street, 221B.png", "attachment; filename=\"Baker Street, 221B.png\"",
"\"Baker Street\", 221B.png", "attachment; filename=\"\\\"Baker Street\\\", 221B.png\"",
- "Хрещатик, 22.png", "attachment; filename=\"=?UTF-8?Q?=D0=A5=D1=80=D0=B5=D1=89=D0=B0=D1=82=D0=B8=D0=BA,_22.png?=\"; " +
+ "Хрещатик, 22.png", "attachment; filename=\"________, 22.png\"; " +
"filename*=UTF-8''%D0%A5%D1%80%D0%B5%D1%89%D0%B0%D1%82%D0%B8%D0%BA%2C%2022.png"
);
diff --git a/application/src/test/java/org/thingsboard/server/controller/IntegrationControllerTest.java b/application/src/test/java/org/thingsboard/server/controller/IntegrationControllerTest.java
index b23ddbc671..f74f782f5b 100644
--- a/application/src/test/java/org/thingsboard/server/controller/IntegrationControllerTest.java
+++ b/application/src/test/java/org/thingsboard/server/controller/IntegrationControllerTest.java
@@ -5,13 +5,13 @@ package org.thingsboard.server.controller;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
+import org.awaitility.Awaitility;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.TestPropertySource;
-import org.testcontainers.shaded.org.awaitility.Awaitility;
import org.thingsboard.common.util.JacksonUtil;
import org.thingsboard.server.common.data.EntityInfo;
import org.thingsboard.server.common.data.IntegrationConvertersInfo;
diff --git a/application/src/test/java/org/thingsboard/server/controller/ReportControllerTest.java b/application/src/test/java/org/thingsboard/server/controller/ReportControllerTest.java
index c5f9695396..1de79b3f5d 100644
--- a/application/src/test/java/org/thingsboard/server/controller/ReportControllerTest.java
+++ b/application/src/test/java/org/thingsboard/server/controller/ReportControllerTest.java
@@ -25,6 +25,7 @@ import org.thingsboard.server.common.data.alarm.Alarm;
import org.thingsboard.server.common.data.alarm.AlarmSeverity;
import org.thingsboard.server.common.data.asset.Asset;
import org.thingsboard.server.common.data.id.ReportTemplateId;
+import org.thingsboard.server.common.data.id.UserId;
import org.thingsboard.server.common.data.job.Job;
import org.thingsboard.server.common.data.job.JobStatus;
import org.thingsboard.server.common.data.job.JobType;
@@ -101,6 +102,8 @@ import java.util.stream.Collectors;
import static org.assertj.core.api.Assertions.assertThat;
import static org.awaitility.Awaitility.await;
import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.Mockito.never;
+import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
@@ -826,6 +829,35 @@ public class ReportControllerTest extends AbstractControllerTest {
doPost("/api/v2/report/test", request).andExpect(status().isOk());
}
+ @Test
+ public void testTestReportRequiresPermissionOverReportUser() throws Exception {
+ loginDifferentTenant();
+ UserId otherTenantUserId = savedDifferentTenantUser.getId();
+ loginTenantAdmin();
+
+ ReportRequest request = new ReportRequest();
+ request.setReportTemplateConfig(buildReportTemplate(TbReportFormat.CSV).getConfiguration());
+ request.setUserId(otherTenantUserId.toString());
+ doPost("/api/v2/report/test", request).andExpect(status().isForbidden());
+
+ verify(tbReportService, never()).generateTestReport(any());
+ }
+
+ @Test
+ public void testRequestReportRequiresPermissionOverReportUser() throws Exception {
+ loginDifferentTenant();
+ UserId otherTenantUserId = savedDifferentTenantUser.getId();
+ loginTenantAdmin();
+
+ ReportTemplate reportTemplate = doPost("/api/reportTemplate", buildReportTemplate(TbReportFormat.CSV), ReportTemplate.class);
+ ReportRequest request = new ReportRequest();
+ request.setReportTemplateId(reportTemplate.getId());
+ request.setUserId(otherTenantUserId.toString());
+ doPost("/api/v2/report/request", request).andExpect(status().isForbidden());
+
+ assertThat(findJobs(List.of(JobType.REPORT), List.of(reportTemplate.getId().getId()))).isEmpty();
+ }
+
private TimeseriesTableComponent buildTimeseriesTableComponent(String devicesAliasId) {
return buildTimeseriesTableComponent(devicesAliasId, buildCurrentDateTimeWindow());
}
diff --git a/application/src/test/java/org/thingsboard/server/controller/RuleEngineControllerTest.java b/application/src/test/java/org/thingsboard/server/controller/RuleEngineControllerTest.java
index c468f3fd55..273b7b9910 100644
--- a/application/src/test/java/org/thingsboard/server/controller/RuleEngineControllerTest.java
+++ b/application/src/test/java/org/thingsboard/server/controller/RuleEngineControllerTest.java
@@ -16,6 +16,7 @@ import org.thingsboard.server.common.data.id.CustomerId;
import org.thingsboard.server.common.data.id.DeviceId;
import org.thingsboard.server.common.data.id.EntityId;
import org.thingsboard.server.common.data.id.TenantId;
+import org.thingsboard.server.common.data.id.UserId;
import org.thingsboard.server.common.data.msg.TbMsgType;
import org.thingsboard.server.common.msg.TbMsg;
import org.thingsboard.server.common.msg.TbMsgMetaData;
@@ -242,6 +243,32 @@ public class RuleEngineControllerTest extends AbstractControllerTest {
verifyNoInteractions(ruleEngineCallService);
}
+ @Test
+ public void testHandleRuleEngineRequestRequiresPermissionOverReportUser() throws Exception {
+ loginCustomerAdminUser();
+
+ doPost("/api/rule-engine/", (Object) reportRequestBody(tenantAdminUserId))
+ .andExpect(status().isForbidden());
+ doPost("/api/rule-engine/", (Object) reportConfigRequestBody(tenantAdminUserId))
+ .andExpect(status().isForbidden());
+ verifyNoInteractions(ruleEngineCallService);
+
+ TbMsg responseMsg = TbMsg.newMsg()
+ .type(TbMsgType.REST_API_REQUEST)
+ .originator(customerAdminUserId)
+ .copyMetaData(TbMsgMetaData.EMPTY)
+ .data(RESPONSE_BODY)
+ .build();
+ mockRestApiCallToRuleEngine(responseMsg);
+
+ String ownReportRequestBody = reportRequestBody(customerAdminUserId);
+ doPostAsyncWithTypedResponse("/api/rule-engine/", ownReportRequestBody, new TypeReference() {
+ }, status().isOk());
+ ArgumentCaptor requestMsgCaptor = ArgumentCaptor.forClass(TbMsg.class);
+ verify(ruleEngineCallService).processRestApiCallToRuleEngine(eq(tenantId), any(UUID.class), requestMsgCaptor.capture(), eq(false), any(Consumer.class));
+ assertThat(requestMsgCaptor.getValue().getData()).isEqualTo(ownReportRequestBody);
+ }
+
@Test
public void testHandleRuleEngineRequestUnauthorized() throws Exception {
doPost("/api/rule-engine/", (Object) REQUEST_BODY)
@@ -249,6 +276,14 @@ public class RuleEngineControllerTest extends AbstractControllerTest {
.andExpect(statusReason(containsString("Authentication failed")));
}
+ private String reportRequestBody(UserId userId) {
+ return "{\"reportConfig\":{\"userId\":\"" + userId.getId() + "\"}}";
+ }
+
+ private String reportConfigRequestBody(UserId userId) {
+ return "{\"userId\":{\"id\":\"" + userId.getId() + "\"}}";
+ }
+
private void mockRestApiCallToRuleEngine(TbMsg responseMsg) {
doAnswer(invocation -> {
Consumer consumer = invocation.getArgument(4);
diff --git a/application/src/test/java/org/thingsboard/server/controller/SchedulerEventControllerTest.java b/application/src/test/java/org/thingsboard/server/controller/SchedulerEventControllerTest.java
index 00c25ef349..4d52fd804d 100644
--- a/application/src/test/java/org/thingsboard/server/controller/SchedulerEventControllerTest.java
+++ b/application/src/test/java/org/thingsboard/server/controller/SchedulerEventControllerTest.java
@@ -276,6 +276,48 @@ public class SchedulerEventControllerTest extends AbstractControllerTest {
assertThat(reportInfos.getData()).hasSize(0);
}
+ @Test
+ public void testSaveReportEventRequiresPermissionOverReportUser() throws Exception {
+ ReportTemplate template = doPost("/api/reportTemplate", buildTemplate("CSV report template", ReportTemplateType.REPORT, TbReportFormat.CSV), ReportTemplate.class);
+
+ loginCustomerAdminUser();
+ doPost("/api/schedulerEvent", createReportSchedulerEvent(template.getId(), tenantAdminUserId)).andExpect(status().isForbidden());
+ doPost("/api/schedulerEvent", createDashboardReportSchedulerEvent(tenantAdminUserId)).andExpect(status().isForbidden());
+ doPost("/api/schedulerEvent", createReportConfigMsgSchedulerEvent(tenantAdminUserId)).andExpect(status().isForbidden());
+ assertThat(findSchedulerEvents(null, null)).isEmpty();
+
+ SchedulerEvent reportEvent = createReportSchedulerEvent(template.getId(), customerAdminUserId);
+ ((ObjectNode) reportEvent.getSchedule()).put("startTime", System.currentTimeMillis() + TimeUnit.DAYS.toMillis(1));
+ assertThat(saveSchedulerEvent(reportEvent).getId()).isNotNull();
+ assertThat(saveSchedulerEvent(createDashboardReportSchedulerEvent(customerAdminUserId)).getId()).isNotNull();
+
+ loginTenantAdmin();
+ assertThat(saveSchedulerEvent(createDashboardReportSchedulerEvent(customerUserId)).getId()).isNotNull();
+ }
+
+ @Test
+ public void testSaveDashboardReportEventWithCurrentUserCredentialsUsesSaverWhenReportUserNotAccessible() throws Exception {
+ loginCustomerAdminUser();
+ SchedulerEvent saved = saveSchedulerEvent(createDashboardReportSchedulerEvent(tenantAdminUserId, true));
+ assertThat(saved.getConfiguration().get("msgBody").get("reportConfig").get("userId").asText()).isEqualTo(customerAdminUserId.toString());
+ }
+
+ @Test
+ public void testSaveDashboardReportEventWithCurrentUserCredentialsKeepsAccessibleReportUser() throws Exception {
+ SchedulerEvent saved = saveSchedulerEvent(createDashboardReportSchedulerEvent(customerAdminUserId, true));
+ assertThat(saved.getConfiguration().get("msgBody").get("reportConfig").get("userId").asText()).isEqualTo(customerAdminUserId.toString());
+ }
+
+ @Test
+ public void testSaveReportEventRequiresReportUser() throws Exception {
+ ReportTemplate template = doPost("/api/reportTemplate", buildTemplate("CSV report template", ReportTemplateType.REPORT, TbReportFormat.CSV), ReportTemplate.class);
+ doPost("/api/schedulerEvent", createReportSchedulerEvent(template.getId(), null)).andExpect(status().isBadRequest());
+
+ SchedulerEvent noConfigurationEvent = createReportSchedulerEvent(template.getId(), tenantAdminUserId);
+ noConfigurationEvent.setConfiguration(null);
+ doPost("/api/schedulerEvent", noConfigurationEvent).andExpect(status().isBadRequest());
+ }
+
private ReportTemplate buildTemplate(String templateName, ReportTemplateType report, TbReportFormat format) {
ReportTemplate template = new ReportTemplate();
template.setName(templateName);
@@ -310,6 +352,39 @@ public class SchedulerEventControllerTest extends AbstractControllerTest {
return schedulerEvent;
}
+ private SchedulerEvent createDashboardReportSchedulerEvent(UserId userId) {
+ return createDashboardReportSchedulerEvent(userId, false);
+ }
+
+ private SchedulerEvent createDashboardReportSchedulerEvent(UserId userId, boolean useCurrentUserCredentials) {
+ SchedulerEvent schedulerEvent = createSchedulerEvent();
+ schedulerEvent.setType("generateDashboardReport");
+ ObjectNode reportConfig = JacksonUtil.newObjectNode();
+ reportConfig.put("namePattern", "report-%d{yyyy-MM-dd_HH:mm:ss}");
+ reportConfig.put("type", "pdf");
+ reportConfig.put("useCurrentUserCredentials", useCurrentUserCredentials);
+ reportConfig.put("userId", userId.toString());
+ ObjectNode msgBody = JacksonUtil.newObjectNode();
+ msgBody.set("reportConfig", reportConfig);
+ msgBody.put("sendEmail", false);
+ ObjectNode configuration = JacksonUtil.newObjectNode();
+ configuration.put("msgType", "generateDashboardReport");
+ configuration.set("msgBody", msgBody);
+ schedulerEvent.setConfiguration(configuration);
+ return schedulerEvent;
+ }
+
+ private SchedulerEvent createReportConfigMsgSchedulerEvent(UserId userId) {
+ SchedulerEvent schedulerEvent = createSchedulerEvent();
+ ObjectNode msgBody = JacksonUtil.newObjectNode();
+ msgBody.set("userId", JacksonUtil.valueToTree(userId));
+ ObjectNode configuration = JacksonUtil.newObjectNode();
+ configuration.put("msgType", "Custom Msg");
+ configuration.set("msgBody", msgBody);
+ schedulerEvent.setConfiguration(configuration);
+ return schedulerEvent;
+ }
+
private SchedulerEvent saveSchedulerEvent(SchedulerEvent schedulerEvent) {
return doPost("/api/schedulerEvent", schedulerEvent, SchedulerEvent.class);
}
diff --git a/application/src/test/java/org/thingsboard/server/controller/SignUpControllerSqlTest.java b/application/src/test/java/org/thingsboard/server/controller/SignUpControllerSqlTest.java
index b100aa38c6..333f291b66 100644
--- a/application/src/test/java/org/thingsboard/server/controller/SignUpControllerSqlTest.java
+++ b/application/src/test/java/org/thingsboard/server/controller/SignUpControllerSqlTest.java
@@ -4,16 +4,20 @@ package org.thingsboard.server.controller;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.node.ObjectNode;
+import org.apache.commons.lang3.RandomStringUtils;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.mockito.ArgumentCaptor;
+import org.mockito.Mockito;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.test.context.bean.override.mockito.MockitoSpyBean;
-import org.testcontainers.shaded.org.apache.commons.lang3.RandomStringUtils;
+import org.thingsboard.common.util.JacksonUtil;
+import org.thingsboard.server.common.data.AdminSettings;
import org.thingsboard.server.common.data.Customer;
import org.thingsboard.server.common.data.CustomerInfo;
import org.thingsboard.server.common.data.Dashboard;
@@ -26,6 +30,7 @@ import org.thingsboard.server.common.data.audit.ActionType;
import org.thingsboard.server.common.data.domain.Domain;
import org.thingsboard.server.common.data.group.EntityGroup;
import org.thingsboard.server.common.data.id.DashboardId;
+import org.thingsboard.server.common.data.id.TenantId;
import org.thingsboard.server.common.data.menu.CMAssigneeType;
import org.thingsboard.server.common.data.menu.CMScope;
import org.thingsboard.server.common.data.menu.CustomMenu;
@@ -37,6 +42,12 @@ import org.thingsboard.server.common.data.notification.NotificationDeliveryMetho
import org.thingsboard.server.common.data.notification.NotificationType;
import org.thingsboard.server.common.data.oauth2.PlatformType;
import org.thingsboard.server.common.data.page.PageLink;
+import org.thingsboard.server.common.data.permission.GroupPermission;
+import org.thingsboard.server.common.data.permission.GroupPermissionInfo;
+import org.thingsboard.server.common.data.role.Role;
+import org.thingsboard.server.common.data.role.RoleType;
+import org.thingsboard.server.common.data.security.Authority;
+import org.thingsboard.server.common.data.security.UserCredentials;
import org.thingsboard.server.common.data.selfregistration.DefaultDashboardParams;
import org.thingsboard.server.common.data.selfregistration.HomeDashboardParams;
import org.thingsboard.server.common.data.selfregistration.MobileRedirectParams;
@@ -47,8 +58,10 @@ import org.thingsboard.server.common.data.selfregistration.V2CaptchaParams;
import org.thingsboard.server.common.data.selfregistration.WebSelfRegistrationParams;
import org.thingsboard.server.common.data.signup.SignUpRequest;
import org.thingsboard.server.common.data.signup.SignUpResult;
+import org.thingsboard.server.common.data.wl.WhiteLabelingType;
import org.thingsboard.server.dao.customer.CustomerService;
import org.thingsboard.server.dao.group.EntityGroupService;
+import org.thingsboard.server.dao.grouppermission.GroupPermissionService;
import org.thingsboard.server.dao.menu.CustomMenuDao;
import org.thingsboard.server.dao.service.DaoSqlTest;
import org.thingsboard.server.dao.settings.AdminSettingsService;
@@ -57,6 +70,7 @@ import org.thingsboard.server.dao.user.UserService;
import org.thingsboard.server.dao.wl.WhiteLabelingService;
import org.thingsboard.server.service.entitiy.TbLogEntityActionService;
+import java.net.URI;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
@@ -68,10 +82,14 @@ import java.util.concurrent.TimeUnit;
import static org.assertj.core.api.Assertions.assertThat;
import static org.awaitility.Awaitility.await;
import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.anyLong;
+import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.argThat;
import static org.mockito.ArgumentMatchers.eq;
+import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
+import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.header;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
@@ -87,6 +105,8 @@ public class SignUpControllerSqlTest extends AbstractControllerTest {
public static final String CUSTOMER_TEST_EMAIL = "signup-customer@thingsboard.org";
public static final String CUSTOMER_TITLE_PREFIX = "Prefix-";
+ public static final String CONFIGURED_BASE_URL = "https://configured.example.com";
+ public static final String OTHER_HOST = "other.example.com";
private static List idsToRemove = new ArrayList<>();
private EntityGroup customerGroup;
@@ -116,6 +136,9 @@ public class SignUpControllerSqlTest extends AbstractControllerTest {
@Autowired
protected WhiteLabelingService whiteLabelingService;
+ @Autowired
+ private GroupPermissionService groupPermissionService;
+
@Before
public void beforeTest() throws Exception {
loginTenantAdmin();
@@ -167,6 +190,41 @@ public class SignUpControllerSqlTest extends AbstractControllerTest {
removeCreatedUser(user);
}
+ @Test
+ public void testSelfRegisterUserCreatesNewGroupPermissions() throws Exception {
+ EntityGroup userGroup = new EntityGroup();
+ userGroup.setType(EntityType.USER);
+ userGroup.setName("Existing permission users");
+ userGroup = doPost("/api/entityGroup", userGroup, EntityGroup.class);
+ Role role = new Role();
+ role.setName("Existing permission role");
+ role.setType(RoleType.GENERIC);
+ role = doPost("/api/role", role, Role.class);
+ GroupPermission existingPermission = new GroupPermission();
+ existingPermission.setUserGroupId(userGroup.getId());
+ existingPermission.setRoleId(role.getId());
+ existingPermission = doPost("/api/groupPermission", existingPermission, GroupPermission.class);
+
+ GroupPermission selfRegistrationPermission = new GroupPermission(existingPermission);
+ createWebSelfRegistrationSettings(List.of(selfRegistrationPermission));
+ String email = "signup-permissions@thingsboard.org";
+ doSignUp(createWebSignUpRequest(email));
+
+ GroupPermission storedPermission = doGet("/api/groupPermission/" + existingPermission.getUuidId(), GroupPermission.class);
+ assertThat(storedPermission.getUserGroupId()).isEqualTo(userGroup.getId());
+
+ User user = userService.findUserByEmail(tenantId, email);
+ EntityGroup selfRegistrationGroup = entityGroupService.findEntityGroupByTypeAndName(tenantId, user.getCustomerId(), EntityType.USER,
+ "Self Registration Users").orElseThrow();
+ List selfRegistrationPermissions = doGetTyped("/api/userGroup/" + selfRegistrationGroup.getUuidId() + "/groupPermissions",
+ new TypeReference<>() {});
+ assertThat(selfRegistrationPermissions).hasSize(1);
+ assertThat(selfRegistrationPermissions.get(0).getId()).isNotEqualTo(existingPermission.getId());
+ assertThat(selfRegistrationPermissions.get(0).getRoleId()).isEqualTo(role.getId());
+
+ removeCreatedUser(user);
+ }
+
@Test
public void testSelfRegisterUserFromMobileApp() throws Exception {
String appSecret = StringUtils.randomAlphanumeric(24);
@@ -320,6 +378,223 @@ public class SignUpControllerSqlTest extends AbstractControllerTest {
removeCreatedUser(user);
}
+ @Test
+ public void testSelfRegisterUserSkipsPermissionForGroupOfOtherTenant() throws Exception {
+ loginDifferentTenant();
+ EntityGroup otherTenantGroup = new EntityGroup();
+ otherTenantGroup.setName("Other Tenant Device Group");
+ otherTenantGroup.setType(EntityType.DEVICE);
+ otherTenantGroup = doPost("/api/entityGroup", otherTenantGroup, EntityGroup.class);
+
+ loginTenantAdmin();
+ Role role = new Role();
+ role.setName("Self Registration Group Role");
+ role.setType(RoleType.GROUP);
+ role.setPermissions(JacksonUtil.toJsonNode("[\"READ\"]"));
+ role = doPost("/api/role", role, Role.class);
+ GroupPermission permission = new GroupPermission();
+ permission.setRoleId(role.getId());
+ permission.setEntityGroupId(otherTenantGroup.getId());
+ createWebSelfRegistrationSettings(List.of(permission));
+
+ doSignUp(createWebSignUpRequest(CUSTOMER_TEST_EMAIL));
+
+ assertThat(groupPermissionService.findGroupPermissionByTenantIdAndRoleId(tenantId, role.getId(), new PageLink(10)).getData()).isEmpty();
+ removeCreatedUser(userService.findUserByEmail(tenantId, CUSTOMER_TEST_EMAIL));
+ }
+
+ @Test
+ public void testResendEmailActivationForPendingSignUpUser() throws Exception {
+ createWebSelfRegistrationSettings();
+ doSignUp(createWebSignUpRequest(CUSTOMER_TEST_EMAIL));
+
+ Mockito.clearInvocations(mailService);
+ doPost("/api/noauth/resendEmailActivation?email=" + CUSTOMER_TEST_EMAIL).andExpect(status().isOk());
+
+ verify(mailService, times(1)).sendActivationEmail(eq(tenantId), anyString(), anyLong(), eq(CUSTOMER_TEST_EMAIL));
+
+ removeCreatedUser(userService.findUserByEmail(tenantId, CUSTOMER_TEST_EMAIL));
+ }
+
+ @Test
+ public void testResendEmailActivationSendsNothingForUserOfOtherTenant() throws Exception {
+ createWebSelfRegistrationSettings();
+ createDifferentTenant();
+
+ User otherUser = new User();
+ otherUser.setAuthority(Authority.TENANT_ADMIN);
+ otherUser.setTenantId(differentTenantId);
+ otherUser.setEmail("other.tenant.user@thingsboard.org");
+ otherUser = doPost("/api/user?sendActivationMail=false", otherUser, User.class);
+
+ UserCredentials credentials = userService.findUserCredentialsByUserId(differentTenantId, otherUser.getId());
+ credentials.setPassword("abcdef123");
+ credentials = userService.saveUserCredentials(differentTenantId, credentials);
+
+ Mockito.clearInvocations(mailService);
+ doPost("/api/noauth/resendEmailActivation?email=" + otherUser.getEmail()).andExpect(status().isBadRequest());
+
+ verify(mailService, never()).sendActivationEmail(any(), anyString(), anyLong(), anyString());
+ UserCredentials credentialsAfter = userService.findUserCredentialsByUserId(differentTenantId, otherUser.getId());
+ assertThat(credentialsAfter.getActivateToken()).isEqualTo(credentials.getActivateToken());
+ assertThat(credentialsAfter.getActivateTokenExpTime()).isEqualTo(credentials.getActivateTokenExpTime());
+
+ deleteDifferentTenant();
+ }
+
+ @Test
+ public void testResendEmailActivationSendsNothingForDisabledActivatedUser() throws Exception {
+ createWebSelfRegistrationSettings();
+ doSignUp(createWebSignUpRequest(CUSTOMER_TEST_EMAIL));
+
+ User user = userService.findUserByEmail(tenantId, CUSTOMER_TEST_EMAIL);
+ UserCredentials credentials = userService.findUserCredentialsByUserId(tenantId, user.getId());
+ userService.activateUserCredentials(tenantId, credentials.getActivateToken(), credentials.getPassword());
+ userService.setUserCredentialsEnabled(tenantId, user.getId(), false);
+
+ Mockito.clearInvocations(mailService);
+ doPost("/api/noauth/resendEmailActivation?email=" + CUSTOMER_TEST_EMAIL).andExpect(status().isBadRequest());
+
+ verify(mailService, never()).sendActivationEmail(any(), anyString(), anyLong(), anyString());
+ assertThat(userService.findUserCredentialsByUserId(tenantId, user.getId()).getActivateToken()).isNull();
+
+ removeCreatedUser(user);
+ }
+
+ @Test
+ public void testActivationEmailLinkUsesConfiguredBaseUrl() throws Exception {
+ createWebSelfRegistrationSettings();
+ AdminSettings generalSettings = setGeneralBaseUrl(CONFIGURED_BASE_URL);
+ try {
+ Mockito.clearInvocations(mailService);
+ doSignUp(createWebSignUpRequest(CUSTOMER_TEST_EMAIL));
+
+ assertThat(captureActivationLink()).startsWith(CONFIGURED_BASE_URL + "/api/noauth/activateEmail?emailCode=");
+ } finally {
+ adminSettingsService.saveAdminSettings(TenantId.SYS_TENANT_ID, generalSettings);
+ }
+ removeCreatedUser(userService.findUserByEmail(tenantId, CUSTOMER_TEST_EMAIL));
+ }
+
+ @Test
+ public void testActivationEmailLinkUsesRequestBaseUrlWhenGeneralBaseUrlIsMissing() throws Exception {
+ createWebSelfRegistrationSettings();
+ AdminSettings generalSettings = setGeneralBaseUrl(null);
+ try {
+ Mockito.clearInvocations(mailService);
+ doSignUp(createWebSignUpRequest(CUSTOMER_TEST_EMAIL));
+
+ assertThat(captureActivationLink()).startsWith("http://localhost:80/api/noauth/activateEmail?emailCode=");
+ } finally {
+ adminSettingsService.saveAdminSettings(TenantId.SYS_TENANT_ID, generalSettings);
+ }
+ removeCreatedUser(userService.findUserByEmail(tenantId, CUSTOMER_TEST_EMAIL));
+ }
+
+ @Test
+ public void testResendActivationEmailLinkUsesConfiguredBaseUrl() throws Exception {
+ String appSecret = StringUtils.randomAlphanumeric(24);
+ String mobilePkgName = "my.test.android.app";
+ createMobileSelfRegistrationSettings(mobilePkgName, appSecret, PlatformType.ANDROID, createDashboard(), createDashboard());
+ AdminSettings generalSettings = setGeneralBaseUrl(CONFIGURED_BASE_URL);
+ try {
+ doSignUp(createMobileSignUpRequest(CUSTOMER_TEST_EMAIL, mobilePkgName, appSecret, PlatformType.ANDROID));
+
+ Mockito.clearInvocations(mailService);
+ mockMvc.perform(post("/api/noauth/resendEmailActivation")
+ .param("email", CUSTOMER_TEST_EMAIL)
+ .param("pkgName", mobilePkgName)
+ .param("platform", PlatformType.ANDROID.name())
+ .header("Host", OTHER_HOST))
+ .andExpect(status().isOk());
+
+ assertThat(captureActivationLink()).startsWith(CONFIGURED_BASE_URL + "/api/noauth/activateEmail?emailCode=");
+ } finally {
+ adminSettingsService.saveAdminSettings(TenantId.SYS_TENANT_ID, generalSettings);
+ }
+ removeCreatedUser(userService.findUserByEmail(tenantId, CUSTOMER_TEST_EMAIL));
+ }
+
+ @Test
+ public void testAccountActivatedEmailLinkUsesConfiguredBaseUrl() throws Exception {
+ createWebSelfRegistrationSettings();
+ AdminSettings generalSettings = setGeneralBaseUrl(CONFIGURED_BASE_URL);
+ User user;
+ try {
+ doSignUp(createWebSignUpRequest(CUSTOMER_TEST_EMAIL));
+ user = userService.findUserByEmail(tenantId, CUSTOMER_TEST_EMAIL);
+ String activateToken = userService.findUserCredentialsByUserId(tenantId, user.getId()).getActivateToken();
+
+ Mockito.clearInvocations(mailService);
+ doPost("/api/noauth/activateByEmailCode?emailCode=" + activateToken).andExpect(status().isOk());
+
+ verify(mailService, times(1)).sendAccountActivatedEmail(eq(tenantId), eq(CONFIGURED_BASE_URL + "/login"), eq(CUSTOMER_TEST_EMAIL));
+ } finally {
+ adminSettingsService.saveAdminSettings(TenantId.SYS_TENANT_ID, generalSettings);
+ }
+ removeCreatedUser(user);
+ }
+
+ @Test
+ public void testActivationEmailLinkUsesHttpSchemeForNonHttpForwardedProto() throws Exception {
+ createWebSelfRegistrationSettings();
+
+ Mockito.clearInvocations(mailService);
+ mockMvc.perform(post("/api/noauth/signup")
+ .contentType(contentType)
+ .content(json(createWebSignUpRequest(CUSTOMER_TEST_EMAIL)))
+ .header("X-Forwarded-Proto", "ftp"))
+ .andExpect(status().isOk());
+
+ URI activationLink = URI.create(captureActivationLink());
+ assertThat(activationLink.getScheme()).isEqualTo("http");
+ assertThat(activationLink.getHost()).isEqualTo("localhost");
+
+ removeCreatedUser(userService.findUserByEmail(tenantId, CUSTOMER_TEST_EMAIL));
+ }
+
+ @Test
+ public void testActivationByEmailCodeOnOtherTenantSettingsIsRejected() throws Exception {
+ createWebSelfRegistrationSettings();
+ doSignUp(createWebSignUpRequest(CUSTOMER_TEST_EMAIL));
+ User user = userService.findUserByEmail(tenantId, CUSTOMER_TEST_EMAIL);
+ String activateToken = userService.findUserCredentialsByUserId(tenantId, user.getId()).getActivateToken();
+
+ createDifferentTenant();
+ createWebSelfRegistrationParams(OTHER_HOST, Collections.emptyList());
+
+ mockMvc.perform(post("/api/noauth/activateByEmailCode")
+ .param("emailCode", activateToken)
+ .header("Host", OTHER_HOST))
+ .andExpect(status().isBadRequest());
+
+ assertThat(userService.findUserCredentialsByUserId(tenantId, user.getId()).isEnabled()).isFalse();
+
+ deleteDifferentTenant();
+ removeCreatedUser(user);
+ }
+
+ @Test
+ public void testSaveSelfRegistrationParamsWithDomainOfOtherTenantIsForbidden() throws Exception {
+ String domainName = "signup-other-tenant.example.com";
+ Domain savedDomain = doPost("/api/domain", constructDomain(domainName), Domain.class);
+
+ loginDifferentTenant();
+ WebSelfRegistrationParams selfRegistrationParams = new WebSelfRegistrationParams();
+ selfRegistrationParams.setTitle("Please sign up");
+ selfRegistrationParams.setPrivacyPolicy("Privacy policy");
+ selfRegistrationParams.setTermsOfUse("Terms of use");
+ selfRegistrationParams.setDomainId(savedDomain.getId());
+ selfRegistrationParams.setPermissions(Collections.emptyList());
+
+ doPost("/api/selfRegistration/selfRegistrationParams", selfRegistrationParams)
+ .andExpect(status().isForbidden());
+
+ assertThat(whiteLabelingService.findWhiteLabelingByDomainAndType(domainName, WhiteLabelingType.SELF_REGISTRATION)).isNull();
+ assertThat(whiteLabelingService.findWhiteLabelingByDomainAndType(domainName, WhiteLabelingType.PRIVACY_POLICY)).isNull();
+ assertThat(whiteLabelingService.findWhiteLabelingByDomainAndType(domainName, WhiteLabelingType.TERMS_OF_USE)).isNull();
+ }
+
protected SignUpRequest createWebSignUpRequest(String email) {
var signUpRequest = new SignUpRequest();
signUpRequest.setFields(Map.of(SignUpFieldId.EMAIL, email,
@@ -388,8 +663,39 @@ public class SignUpControllerSqlTest extends AbstractControllerTest {
Assert.assertNull("Expected that created user is deleted but one found!", found);
}
+ private String captureActivationLink() throws Exception {
+ ArgumentCaptor activationLink = ArgumentCaptor.forClass(String.class);
+ verify(mailService, times(1)).sendActivationEmail(eq(tenantId), activationLink.capture(), anyLong(), eq(CUSTOMER_TEST_EMAIL));
+ return activationLink.getValue();
+ }
+
+ private AdminSettings setGeneralBaseUrl(String baseUrl) {
+ AdminSettings generalSettings = adminSettingsService.findAdminSettingsByKey(TenantId.SYS_TENANT_ID, "general");
+ AdminSettings updatedSettings = new AdminSettings(generalSettings);
+ ObjectNode jsonValue = generalSettings.getJsonValue().deepCopy();
+ if (baseUrl != null) {
+ jsonValue.put("baseUrl", baseUrl);
+ } else {
+ jsonValue.remove("baseUrl");
+ }
+ jsonValue.put("prohibitDifferentUrl", true);
+ updatedSettings.setJsonValue(jsonValue);
+ adminSettingsService.saveAdminSettings(TenantId.SYS_TENANT_ID, updatedSettings);
+ return generalSettings;
+ }
+
private void createWebSelfRegistrationSettings() {
- Domain domain = constructDomain("localhost");
+ createWebSelfRegistrationSettings(Collections.emptyList());
+ }
+
+ private void createWebSelfRegistrationSettings(List permissions) {
+ createWebSelfRegistrationParams("localhost", permissions);
+ createNotificationTemplate(NotificationType.USER_ACTIVATED, "User activated", "User ${userEmail} was activated", NotificationDeliveryMethod.WEB);
+ createNotificationTemplate(NotificationType.USER_REGISTERED, "User registered", "User ${userEmail} was registered", NotificationDeliveryMethod.WEB);
+ }
+
+ private void createWebSelfRegistrationParams(String domainName, List permissions) {
+ Domain domain = constructDomain(domainName);
Domain savedDomain = doPost("/api/domain", domain, Domain.class);
WebSelfRegistrationParams selfRegistrationParams = new WebSelfRegistrationParams();
@@ -402,13 +708,10 @@ public class SignUpControllerSqlTest extends AbstractControllerTest {
selfRegistrationParams.setShowPrivacyPolicy(true);
selfRegistrationParams.setDomainId(savedDomain.getId());
selfRegistrationParams.setNotificationRecipient(createNotificationTarget(currentUserId).getId());
- selfRegistrationParams.setPermissions(Collections.emptyList());
+ selfRegistrationParams.setPermissions(permissions);
doPost("/api/selfRegistration/selfRegistrationParams",
selfRegistrationParams, JsonNode.class);
-
- createNotificationTemplate(NotificationType.USER_ACTIVATED, "User activated", "User ${userEmail} was activated", NotificationDeliveryMethod.WEB);
- createNotificationTemplate(NotificationType.USER_REGISTERED, "User registered", "User ${userEmail} was registered", NotificationDeliveryMethod.WEB);
}
private void createMobileSelfRegistrationSettings(String mobilePkgName, String appSecret, PlatformType platformType,
diff --git a/application/src/test/java/org/thingsboard/server/controller/TbResourceControllerTest.java b/application/src/test/java/org/thingsboard/server/controller/TbResourceControllerTest.java
index 1aae2d7fa5..fec9f9cb4d 100644
--- a/application/src/test/java/org/thingsboard/server/controller/TbResourceControllerTest.java
+++ b/application/src/test/java/org/thingsboard/server/controller/TbResourceControllerTest.java
@@ -22,6 +22,7 @@ import org.thingsboard.server.common.data.Customer;
import org.thingsboard.server.common.data.Dashboard;
import org.thingsboard.server.common.data.EntityInfo;
import org.thingsboard.server.common.data.EntityType;
+import org.thingsboard.server.common.data.ResourceSubType;
import org.thingsboard.server.common.data.ResourceType;
import org.thingsboard.server.common.data.StringUtils;
import org.thingsboard.server.common.data.TbResource;
@@ -32,6 +33,7 @@ import org.thingsboard.server.common.data.audit.ActionType;
import org.thingsboard.server.common.data.group.EntityGroup;
import org.thingsboard.server.common.data.group.EntityGroupInfo;
import org.thingsboard.server.common.data.id.TbResourceId;
+import org.thingsboard.server.common.data.id.TenantId;
import org.thingsboard.server.common.data.lwm2m.LwM2mObject;
import org.thingsboard.server.common.data.page.PageData;
import org.thingsboard.server.common.data.page.PageLink;
@@ -926,6 +928,160 @@ public class TbResourceControllerTest extends AbstractControllerTest {
assertThat(download(savedResource.getId())).asBase64Encoded().isEqualTo(newData);
}
+ @Test
+ public void testUpdateResourceInfoKeepsStoredTenant() throws Exception {
+ TbResourceInfo savedResource = saveJsModule();
+
+ TbResourceInfo resourceInfo = findResourceInfo(savedResource.getId());
+ resourceInfo.setTenantId(null);
+ resourceInfo.setTitle("Updated title");
+ Mockito.reset(tbClusterService, auditLogService);
+ TbResourceInfo updatedResource = doPut("/api/resource/" + savedResource.getUuidId() + "/info", resourceInfo, TbResourceInfo.class);
+ assertThat(updatedResource.getTenantId()).isEqualTo(savedTenant.getId());
+ assertThat(updatedResource.getTitle()).isEqualTo("Updated title");
+ testNotifyEntityAllOneTimeLogEntityActionEntityEqClass(updatedResource, updatedResource.getId(), updatedResource.getId(),
+ savedTenant.getId(), tenantAdmin.getCustomerId(), tenantAdmin.getId(), tenantAdmin.getEmail(),
+ ActionType.UPDATED, ActionType.UPDATED);
+ resourceInfo = findResourceInfo(savedResource.getId());
+ assertThat(resourceInfo.getTenantId()).isEqualTo(savedTenant.getId());
+ assertThat(resourceInfo.getTitle()).isEqualTo("Updated title");
+
+ resourceInfo.setTenantId(TenantId.SYS_TENANT_ID);
+ doPut("/api/resource/" + savedResource.getUuidId() + "/info", resourceInfo, TbResourceInfo.class);
+ assertThat(findResourceInfo(savedResource.getId()).getTenantId()).isEqualTo(savedTenant.getId());
+
+ loginDifferentTenant();
+ login(tenantAdmin.getEmail(), "testPassword1");
+ resourceInfo.setTenantId(savedDifferentTenant.getId());
+ doPut("/api/resource/" + savedResource.getUuidId() + "/info", resourceInfo, TbResourceInfo.class);
+ assertThat(findResourceInfo(savedResource.getId()).getTenantId()).isEqualTo(savedTenant.getId());
+
+ deleteDifferentTenant();
+ }
+
+ @Test
+ public void testUpdateResourceInfoKeepsStoredKeyAndEtag() throws Exception {
+ TbResourceInfo savedResource = saveJsModule();
+
+ TbResourceInfo resourceInfo = findResourceInfo(savedResource.getId());
+ resourceInfo.setTitle("Updated title");
+ resourceInfo.setResourceKey("other-key");
+ resourceInfo.setEtag("0");
+ resourceInfo.setCreatedTime(1);
+ TbResourceInfo updatedResource = doPut("/api/resource/" + savedResource.getUuidId() + "/info", resourceInfo, TbResourceInfo.class);
+ assertThat(updatedResource.getTitle()).isEqualTo("Updated title");
+ assertThat(updatedResource.getResourceKey()).isEqualTo(savedResource.getResourceKey());
+ assertThat(updatedResource.getEtag()).isEqualTo(savedResource.getEtag());
+ assertThat(updatedResource.getCreatedTime()).isEqualTo(savedResource.getCreatedTime());
+
+ resourceInfo = findResourceInfo(savedResource.getId());
+ assertThat(resourceInfo.getResourceKey()).isEqualTo(savedResource.getResourceKey());
+ assertThat(resourceInfo.getEtag()).isEqualTo(savedResource.getEtag());
+ }
+
+ @Test
+ public void testUpdateResourceInfoRefusesTypeChange() throws Exception {
+ TbResourceInfo savedResource = saveJsModule();
+
+ TbResourceInfo resourceInfo = findResourceInfo(savedResource.getId());
+ resourceInfo.setResourceType(ResourceType.GENERAL);
+ doPut("/api/resource/" + savedResource.getUuidId() + "/info", resourceInfo)
+ .andExpect(status().isBadRequest())
+ .andExpect(statusReason(containsString("can't be changed")));
+
+ resourceInfo = findResourceInfo(savedResource.getId());
+ resourceInfo.setResourceSubType(ResourceSubType.MODULE);
+ doPut("/api/resource/" + savedResource.getUuidId() + "/info", resourceInfo)
+ .andExpect(status().isBadRequest())
+ .andExpect(statusReason(containsString("can't be changed")));
+
+ resourceInfo = findResourceInfo(savedResource.getId());
+ assertThat(resourceInfo.getResourceType()).isEqualTo(ResourceType.JS_MODULE);
+ assertThat(resourceInfo.getResourceSubType()).isEqualTo(ResourceSubType.EXTENSION);
+
+ resourceInfo.setTitle("Updated title");
+ ObjectNode request = (ObjectNode) JacksonUtil.valueToTree(resourceInfo);
+ request.putNull("resourceType");
+ request.putNull("resourceSubType");
+ TbResourceInfo updatedResource = doPut("/api/resource/" + savedResource.getUuidId() + "/info", request, TbResourceInfo.class);
+ assertThat(updatedResource.getTitle()).isEqualTo("Updated title");
+ resourceInfo = findResourceInfo(savedResource.getId());
+ assertThat(resourceInfo.getResourceType()).isEqualTo(ResourceType.JS_MODULE);
+ assertThat(resourceInfo.getResourceSubType()).isEqualTo(ResourceSubType.EXTENSION);
+ }
+
+ @Test
+ public void testSaveResourceWithIdKeepsStoredTypeKeyAndEtag() throws Exception {
+ TbResourceInfo savedResource = saveJsModule();
+
+ TbResource resource = new TbResource(findResourceInfo(savedResource.getId()));
+ resource.setResourceType(ResourceType.GENERAL);
+ doPost("/api/resource", resource)
+ .andExpect(status().isBadRequest())
+ .andExpect(statusReason(containsString("can't be changed")));
+
+ resource.setResourceType(ResourceType.JS_MODULE);
+ resource.setTitle("Updated title");
+ resource.setResourceKey("other-key");
+ resource.setEtag("0");
+ TbResourceInfo updatedResource = doPost("/api/resource", resource, TbResourceInfo.class);
+ assertThat(updatedResource.getTitle()).isEqualTo("Updated title");
+ assertThat(updatedResource.getResourceKey()).isEqualTo(savedResource.getResourceKey());
+ assertThat(updatedResource.getEtag()).isEqualTo(savedResource.getEtag());
+
+ TbResourceInfo resourceInfo = findResourceInfo(savedResource.getId());
+ assertThat(resourceInfo.getResourceType()).isEqualTo(ResourceType.JS_MODULE);
+ assertThat(resourceInfo.getResourceKey()).isEqualTo(savedResource.getResourceKey());
+ assertThat(resourceInfo.getEtag()).isEqualTo(savedResource.getEtag());
+ }
+
+ @Test
+ public void testSysAdminUpdateResourceInfoKeepsSystemTenant() throws Exception {
+ loginSysAdmin();
+ TbResourceInfo savedResource = saveJsModule();
+ assertThat(savedResource.getTenantId()).isEqualTo(TenantId.SYS_TENANT_ID);
+
+ TbResourceInfo resourceInfo = findResourceInfo(savedResource.getId());
+ resourceInfo.setTenantId(savedTenant.getId());
+ TbResourceInfo updatedResource = doPut("/api/resource/" + savedResource.getUuidId() + "/info", resourceInfo, TbResourceInfo.class);
+ assertThat(updatedResource.getTenantId()).isEqualTo(TenantId.SYS_TENANT_ID);
+ assertThat(findResourceInfo(savedResource.getId()).getTenantId()).isEqualTo(TenantId.SYS_TENANT_ID);
+
+ doDelete("/api/resource/" + savedResource.getUuidId()).andExpect(status().isOk());
+ }
+
+ @Test
+ public void testUpdateResourceInfoKeepsStoredCustomer() throws Exception {
+ Customer storedCustomer = saveCustomer("Stored resource customer");
+ Customer otherCustomer = saveCustomer("Other resource customer");
+
+ TbResource resource = new TbResource();
+ resource.setResourceType(ResourceType.JS_MODULE);
+ resource.setResourceSubType(ResourceSubType.EXTENSION);
+ resource.setTitle("Js resource");
+ resource.setFileName(JS_TEST_FILE_NAME);
+ resource.setEncodedData(TEST_DATA);
+ resource.setCustomerId(storedCustomer.getId());
+ TbResourceInfo savedResource = doPost("/api/resource", resource, TbResourceInfo.class);
+ assertThat(savedResource.getCustomerId()).isEqualTo(storedCustomer.getId());
+
+ TbResourceInfo resourceInfo = findResourceInfo(savedResource.getId());
+ resourceInfo.setCustomerId(otherCustomer.getId());
+ TbResourceInfo updatedResource = doPut("/api/resource/" + savedResource.getUuidId() + "/info", resourceInfo, TbResourceInfo.class);
+ assertThat(updatedResource.getCustomerId()).isEqualTo(storedCustomer.getId());
+
+ resourceInfo.setCustomerId(null);
+ updatedResource = doPut("/api/resource/" + savedResource.getUuidId() + "/info", resourceInfo, TbResourceInfo.class);
+ assertThat(updatedResource.getCustomerId()).isEqualTo(storedCustomer.getId());
+ assertThat(findResourceInfo(savedResource.getId()).getCustomerId()).isEqualTo(storedCustomer.getId());
+ }
+
+ private Customer saveCustomer(String title) throws Exception {
+ Customer customer = new Customer();
+ customer.setTitle(title);
+ return doPost("/api/customer", customer, Customer.class);
+ }
+
@Test
public void testGetLwm2mListObjectsPage() throws Exception {
loginTenantAdmin();
@@ -1087,6 +1243,16 @@ public class TbResourceControllerTest extends AbstractControllerTest {
return uploadResource(HttpMethod.POST, "/api/resource/upload", tbResource.getFileName(), tbResource.getResourceType().getMediaType(), data, parts);
}
+ private TbResourceInfo saveJsModule() throws Exception {
+ TbResource resource = new TbResource();
+ resource.setResourceType(ResourceType.JS_MODULE);
+ resource.setResourceSubType(ResourceSubType.EXTENSION);
+ resource.setTitle("Js resource");
+ resource.setFileName(JS_TEST_FILE_NAME);
+ resource.setEncodedData(TEST_DATA);
+ return save(resource);
+ }
+
private TbResourceInfo findResourceInfo(TbResourceId id) throws Exception {
return doGet("/api/resource/info/" + id, TbResourceInfo.class);
}
diff --git a/application/src/test/java/org/thingsboard/server/controller/TrendzApiControllerTest.java b/application/src/test/java/org/thingsboard/server/controller/TrendzApiControllerTest.java
index 99dddc6ae4..b7b19952b7 100644
--- a/application/src/test/java/org/thingsboard/server/controller/TrendzApiControllerTest.java
+++ b/application/src/test/java/org/thingsboard/server/controller/TrendzApiControllerTest.java
@@ -2,11 +2,11 @@
// SPDX-License-Identifier: BUSL-1.1
package org.thingsboard.server.controller;
+import com.fasterxml.jackson.core.type.TypeReference;
+import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.Test;
import org.springframework.test.context.bean.override.mockito.MockitoBean;
import org.springframework.test.web.servlet.MvcResult;
-import org.testcontainers.shaded.com.fasterxml.jackson.core.type.TypeReference;
-import org.testcontainers.shaded.com.fasterxml.jackson.databind.ObjectMapper;
import org.thingsboard.server.common.data.page.PageData;
import org.thingsboard.server.common.data.page.PageLink;
import org.thingsboard.server.common.data.page.SortOrder;
diff --git a/application/src/test/java/org/thingsboard/server/controller/WhiteLabelingControllerTest.java b/application/src/test/java/org/thingsboard/server/controller/WhiteLabelingControllerTest.java
index 8574bd7bd0..04ccbcc671 100644
--- a/application/src/test/java/org/thingsboard/server/controller/WhiteLabelingControllerTest.java
+++ b/application/src/test/java/org/thingsboard/server/controller/WhiteLabelingControllerTest.java
@@ -4,11 +4,11 @@ package org.thingsboard.server.controller;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
+import org.awaitility.Awaitility;
import org.junit.After;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.web.servlet.MvcResult;
-import org.testcontainers.shaded.org.awaitility.Awaitility;
import org.thingsboard.common.util.JacksonUtil;
import org.thingsboard.server.common.data.AdminSettings;
import org.thingsboard.server.common.data.StringUtils;
diff --git a/application/src/test/java/org/thingsboard/server/controller/WidgetTypeControllerTest.java b/application/src/test/java/org/thingsboard/server/controller/WidgetTypeControllerTest.java
index 777d720d3d..77f318036b 100644
--- a/application/src/test/java/org/thingsboard/server/controller/WidgetTypeControllerTest.java
+++ b/application/src/test/java/org/thingsboard/server/controller/WidgetTypeControllerTest.java
@@ -6,11 +6,11 @@ package org.thingsboard.server.controller;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ArrayNode;
+import org.apache.commons.lang3.RandomStringUtils;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
-import org.testcontainers.shaded.org.apache.commons.lang3.RandomStringUtils;
import org.thingsboard.common.util.JacksonUtil;
import org.thingsboard.server.common.data.Customer;
import org.thingsboard.server.common.data.EntityType;
diff --git a/application/src/test/java/org/thingsboard/server/edge/CalculatedFieldEdgeTest.java b/application/src/test/java/org/thingsboard/server/edge/CalculatedFieldEdgeTest.java
index f6c34f1ffa..e4a78643f5 100644
--- a/application/src/test/java/org/thingsboard/server/edge/CalculatedFieldEdgeTest.java
+++ b/application/src/test/java/org/thingsboard/server/edge/CalculatedFieldEdgeTest.java
@@ -20,6 +20,7 @@ import org.thingsboard.server.common.data.cf.configuration.TimeSeriesOutput;
import org.thingsboard.server.common.data.debug.DebugSettings;
import org.thingsboard.server.common.data.id.CalculatedFieldId;
import org.thingsboard.server.common.data.id.EntityId;
+import org.thingsboard.server.common.data.id.TenantId;
import org.thingsboard.server.dao.cf.CalculatedFieldService;
import org.thingsboard.server.dao.service.DaoSqlTest;
import org.thingsboard.server.gen.edge.v1.CalculatedFieldRequestMsg;
@@ -109,6 +110,40 @@ public class CalculatedFieldEdgeTest extends AbstractEdgeTest {
checkCalculatedFieldOnCloud(uplinkMsg, uuid, calculatedField.getName());
}
+ @Test
+ public void testSendCalculatedFieldToCloudSavesItUnderEdgeTenant() throws Exception {
+ Device savedDevice = saveDeviceOnCloudAndVerifyDeliveryToEdge();
+
+ SimpleCalculatedFieldConfiguration config = new SimpleCalculatedFieldConfiguration();
+ CalculatedField calculatedField = createSimpleCalculatedField(savedDevice.getId(), config);
+ calculatedField.setTenantId(TenantId.fromUUID(UUID.randomUUID()));
+ UUID uuid = Uuids.timeBased();
+ UplinkMsg uplinkMsg = getUplinkMsg(uuid, calculatedField, UpdateMsgType.ENTITY_CREATED_RPC_MESSAGE);
+
+ checkCalculatedFieldOnCloud(uplinkMsg, uuid, calculatedField.getName());
+
+ CalculatedField calculatedFieldFromCloud = doGet("/api/calculatedField/" + uuid, CalculatedField.class);
+ Assert.assertEquals(tenantId, calculatedFieldFromCloud.getTenantId());
+ }
+
+ @Test
+ public void testSendCalculatedFieldWithOtherTenantReferenceToCloud() throws Exception {
+ Device savedDevice = saveDeviceOnCloudAndVerifyDeliveryToEdge();
+
+ SimpleCalculatedFieldConfiguration config = new SimpleCalculatedFieldConfiguration();
+ CalculatedField calculatedField = createSimpleCalculatedField(savedDevice.getId(), config);
+ config.getArguments().get("T").setRefEntityId(TenantId.fromUUID(UUID.randomUUID()));
+ UUID uuid = Uuids.timeBased();
+ UplinkMsg uplinkMsg = getUplinkMsg(uuid, calculatedField, UpdateMsgType.ENTITY_CREATED_RPC_MESSAGE);
+
+ edgeImitator.expectResponsesAmount(1);
+ edgeImitator.sendUplinkMsg(uplinkMsg);
+ Assert.assertTrue(edgeImitator.waitForResponses());
+
+ Assert.assertFalse(edgeImitator.getLatestResponseMsg().getSuccess());
+ doGet("/api/calculatedField/" + uuid).andExpect(status().isNotFound());
+ }
+
@Test
public void testSendCalculatedFieldRequestToCloud() throws Exception {
Device savedDevice = saveDeviceOnCloudAndVerifyDeliveryToEdge();
diff --git a/application/src/test/java/org/thingsboard/server/edge/DeviceEdgeTest.java b/application/src/test/java/org/thingsboard/server/edge/DeviceEdgeTest.java
index db600a0d17..49736cdb3d 100644
--- a/application/src/test/java/org/thingsboard/server/edge/DeviceEdgeTest.java
+++ b/application/src/test/java/org/thingsboard/server/edge/DeviceEdgeTest.java
@@ -679,6 +679,61 @@ public class DeviceEdgeTest extends AbstractEdgeTest {
Assert.assertEquals(deviceName + " Updated", device.getName());
}
+ @Test
+ public void testSendDeviceToCloudAddsDeviceOnlyToGroupOfEdgeTenant() throws Exception {
+ loginDifferentTenant();
+ EntityGroup otherTenantGroup = new EntityGroup();
+ otherTenantGroup.setType(EntityType.DEVICE);
+ otherTenantGroup.setName("Other Tenant Device Group");
+ otherTenantGroup = doPost("/api/entityGroup", otherTenantGroup, EntityGroup.class);
+ loginTenantAdmin();
+
+ Device deviceMsg = buildDeviceForUplinkMsg("Edge Device In Group", "test");
+ UplinkMsg.Builder uplinkMsgBuilder = UplinkMsg.newBuilder();
+ DeviceUpdateMsg.Builder deviceUpdateMsgBuilder = DeviceUpdateMsg.newBuilder();
+ deviceUpdateMsgBuilder.setIdMSB(deviceMsg.getUuidId().getMostSignificantBits());
+ deviceUpdateMsgBuilder.setIdLSB(deviceMsg.getUuidId().getLeastSignificantBits());
+ deviceUpdateMsgBuilder.setEntityGroupIdMSB(otherTenantGroup.getUuidId().getMostSignificantBits());
+ deviceUpdateMsgBuilder.setEntityGroupIdLSB(otherTenantGroup.getUuidId().getLeastSignificantBits());
+ deviceUpdateMsgBuilder.setEntity(JacksonUtil.toString(deviceMsg));
+ deviceUpdateMsgBuilder.setMsgType(UpdateMsgType.ENTITY_CREATED_RPC_MESSAGE);
+ uplinkMsgBuilder.addDeviceUpdateMsg(deviceUpdateMsgBuilder.build());
+
+ edgeImitator.expectResponsesAmount(1);
+ edgeImitator.sendUplinkMsg(uplinkMsgBuilder.build());
+ Assert.assertTrue(edgeImitator.waitForResponses());
+
+ Device device = doGet("/api/device/" + deviceMsg.getId().getId(), Device.class);
+ Assert.assertNotNull(device);
+ Assert.assertFalse(entityGroupService.isEntityInGroup(differentTenantId, device.getId(), otherTenantGroup.getId()));
+ }
+
+ @Test
+ public void testDeleteDeviceFromGroupOnCloudKeepsGroupsOfOtherTenant() throws Exception {
+ loginDifferentTenant();
+ EntityGroup otherTenantGroup = new EntityGroup();
+ otherTenantGroup.setType(EntityType.DEVICE);
+ otherTenantGroup.setName("Other Tenant Device Group");
+ otherTenantGroup = doPost("/api/entityGroup", otherTenantGroup, EntityGroup.class);
+ Device otherTenantDevice = saveDevice("Other Tenant Device", "test", otherTenantGroup.getId());
+ loginTenantAdmin();
+
+ UplinkMsg.Builder uplinkMsgBuilder = UplinkMsg.newBuilder();
+ DeviceUpdateMsg.Builder deviceUpdateMsgBuilder = DeviceUpdateMsg.newBuilder();
+ deviceUpdateMsgBuilder.setIdMSB(otherTenantDevice.getUuidId().getMostSignificantBits());
+ deviceUpdateMsgBuilder.setIdLSB(otherTenantDevice.getUuidId().getLeastSignificantBits());
+ deviceUpdateMsgBuilder.setEntityGroupIdMSB(otherTenantGroup.getUuidId().getMostSignificantBits());
+ deviceUpdateMsgBuilder.setEntityGroupIdLSB(otherTenantGroup.getUuidId().getLeastSignificantBits());
+ deviceUpdateMsgBuilder.setMsgType(UpdateMsgType.ENTITY_DELETED_RPC_MESSAGE);
+ uplinkMsgBuilder.addDeviceUpdateMsg(deviceUpdateMsgBuilder.build());
+
+ edgeImitator.expectResponsesAmount(1);
+ edgeImitator.sendUplinkMsg(uplinkMsgBuilder.build());
+ Assert.assertTrue(edgeImitator.waitForResponses());
+
+ Assert.assertTrue(entityGroupService.isEntityInGroup(differentTenantId, otherTenantDevice.getId(), otherTenantGroup.getId()));
+ }
+
@Test
public void testRpcCall() throws Exception {
Device device = saveDeviceOnCloudAndVerifyDeliveryToEdge();
diff --git a/application/src/test/java/org/thingsboard/server/edge/EntityViewEdgeTest.java b/application/src/test/java/org/thingsboard/server/edge/EntityViewEdgeTest.java
index 176481a248..4bb40b6a87 100644
--- a/application/src/test/java/org/thingsboard/server/edge/EntityViewEdgeTest.java
+++ b/application/src/test/java/org/thingsboard/server/edge/EntityViewEdgeTest.java
@@ -18,6 +18,7 @@ import org.thingsboard.server.common.data.group.EntityGroup;
import org.thingsboard.server.common.data.id.DeviceId;
import org.thingsboard.server.common.data.id.EntityGroupId;
import org.thingsboard.server.common.data.id.EntityViewId;
+import org.thingsboard.server.common.data.id.TenantId;
import org.thingsboard.server.common.data.page.PageData;
import org.thingsboard.server.common.data.page.PageLink;
import org.thingsboard.server.dao.service.DaoSqlTest;
@@ -191,6 +192,69 @@ public class EntityViewEdgeTest extends AbstractEdgeTest {
Assert.assertNotEquals(entityViewOnCloudName, entityView.getName());
}
+ @Test
+ public void testEntityViewFromEdgeSavedInEdgeTenant() throws Exception {
+ Device device = saveDeviceOnCloudAndVerifyDeliveryToEdge();
+
+ EntityView entityViewMsg = buildEntityViewForUplinkMsg(device, "Edge EntityView 3");
+ entityViewMsg.setTenantId(TenantId.fromUUID(UUID.randomUUID()));
+
+ UplinkMsg.Builder uplinkMsgBuilder = UplinkMsg.newBuilder();
+ EntityViewUpdateMsg.Builder entityViewUpdateMsgBuilder = EntityViewUpdateMsg.newBuilder();
+ entityViewUpdateMsgBuilder.setIdMSB(entityViewMsg.getUuidId().getMostSignificantBits());
+ entityViewUpdateMsgBuilder.setIdLSB(entityViewMsg.getUuidId().getLeastSignificantBits());
+ entityViewUpdateMsgBuilder.setEntity(JacksonUtil.toString(entityViewMsg));
+ entityViewUpdateMsgBuilder.setMsgType(UpdateMsgType.ENTITY_CREATED_RPC_MESSAGE);
+ uplinkMsgBuilder.addEntityViewUpdateMsg(entityViewUpdateMsgBuilder.build());
+
+ edgeImitator.expectResponsesAmount(1);
+ edgeImitator.expectMessageAmount(1);
+ edgeImitator.sendUplinkMsg(uplinkMsgBuilder.build());
+ Assert.assertTrue(edgeImitator.waitForResponses());
+ Assert.assertTrue(edgeImitator.getLatestResponseMsg().getSuccess());
+
+ EntityView entityView = doGet("/api/entityView/" + entityViewMsg.getUuidId(), EntityView.class);
+ Assert.assertEquals(tenantId, entityView.getTenantId());
+ }
+
+ @Test
+ public void testEntityViewFromEdgeWithIdOfOtherTenantViewNotSaved() throws Exception {
+ Device edgeDevice = saveDeviceOnCloudAndVerifyDeliveryToEdge();
+
+ loginDifferentTenant();
+ Device otherTenantDevice = new Device();
+ otherTenantDevice.setName("Other tenant device");
+ otherTenantDevice.setType("default");
+ otherTenantDevice = doPost("/api/device", otherTenantDevice, Device.class);
+ EntityView otherTenantView = saveEntityView("Other tenant EntityView", otherTenantDevice.getId(), null);
+ loginTenantAdmin();
+
+ EntityView entityViewMsg = buildEntityViewForUplinkMsg(edgeDevice, "Edge EntityView 4");
+ entityViewMsg.setId(otherTenantView.getId());
+
+ UplinkMsg.Builder uplinkMsgBuilder = UplinkMsg.newBuilder();
+ EntityViewUpdateMsg.Builder entityViewUpdateMsgBuilder = EntityViewUpdateMsg.newBuilder();
+ entityViewUpdateMsgBuilder.setIdMSB(entityViewMsg.getUuidId().getMostSignificantBits());
+ entityViewUpdateMsgBuilder.setIdLSB(entityViewMsg.getUuidId().getLeastSignificantBits());
+ entityViewUpdateMsgBuilder.setEntity(JacksonUtil.toString(entityViewMsg));
+ entityViewUpdateMsgBuilder.setMsgType(UpdateMsgType.ENTITY_UPDATED_RPC_MESSAGE);
+ uplinkMsgBuilder.addEntityViewUpdateMsg(entityViewUpdateMsgBuilder.build());
+
+ edgeImitator.expectResponsesAmount(1);
+ edgeImitator.sendUplinkMsg(uplinkMsgBuilder.build());
+ Assert.assertTrue(edgeImitator.waitForResponses());
+ Assert.assertFalse(edgeImitator.getLatestResponseMsg().getSuccess());
+
+ loginDifferentTenant();
+ EntityView storedView = doGet("/api/entityView/" + otherTenantView.getUuidId(), EntityView.class);
+ Assert.assertEquals(differentTenantId, storedView.getTenantId());
+ Assert.assertEquals("Other tenant EntityView", storedView.getName());
+ Assert.assertEquals(otherTenantDevice.getId(), storedView.getEntityId());
+ Assert.assertEquals(otherTenantView.getCustomerId(), storedView.getCustomerId());
+ Assert.assertEquals(otherTenantView.getOwnerId(), storedView.getOwnerId());
+ loginTenantAdmin();
+ }
+
@Test
public void testSendUnassignEntityViewFromGroupOnEdgeToCloud() throws Exception {
Device device = saveDeviceOnCloudAndVerifyDeliveryToEdge();
diff --git a/application/src/test/java/org/thingsboard/server/edge/OtaPackageEdgeTest.java b/application/src/test/java/org/thingsboard/server/edge/OtaPackageEdgeTest.java
index eb856e854a..3be9b81c81 100644
--- a/application/src/test/java/org/thingsboard/server/edge/OtaPackageEdgeTest.java
+++ b/application/src/test/java/org/thingsboard/server/edge/OtaPackageEdgeTest.java
@@ -4,12 +4,12 @@
package org.thingsboard.server.edge;
import com.google.protobuf.AbstractMessage;
+import org.awaitility.Awaitility;
import org.junit.Assert;
import org.junit.Test;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.test.web.servlet.request.MockMultipartHttpServletRequestBuilder;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
-import org.testcontainers.shaded.org.awaitility.Awaitility;
import org.thingsboard.common.util.JacksonUtil;
import org.thingsboard.server.common.data.Device;
import org.thingsboard.server.common.data.EntityType;
diff --git a/application/src/test/java/org/thingsboard/server/edge/TelemetryEdgeTest.java b/application/src/test/java/org/thingsboard/server/edge/TelemetryEdgeTest.java
index 031b646b00..c4f4e25942 100644
--- a/application/src/test/java/org/thingsboard/server/edge/TelemetryEdgeTest.java
+++ b/application/src/test/java/org/thingsboard/server/edge/TelemetryEdgeTest.java
@@ -390,4 +390,49 @@ public class TelemetryEdgeTest extends AbstractEdgeTest {
});
}
+ @Test
+ public void testSendEntityGroupAttributesAndTelemetryForGroupOfDifferentTenantToCloud() throws Exception {
+ loginDifferentTenant();
+ EntityGroup entityGroup = new EntityGroup();
+ entityGroup.setType(EntityType.DEVICE);
+ entityGroup.setName("Different Tenant Device Group");
+ EntityGroup savedEntityGroup = doPost("/api/entityGroup", entityGroup, EntityGroup.class);
+ loginTenantAdmin();
+
+ EntityDataProto entityData = EntityDataProto.newBuilder()
+ .setEntityIdMSB(savedEntityGroup.getUuidId().getMostSignificantBits())
+ .setEntityIdLSB(savedEntityGroup.getUuidId().getLeastSignificantBits())
+ .setEntityType(EntityType.ENTITY_GROUP.name())
+ .setAttributesUpdatedMsg(TransportProtos.PostAttributeMsg.newBuilder()
+ .addKv(TransportProtos.KeyValueProto.newBuilder()
+ .setKey("groupKey")
+ .setType(TransportProtos.KeyValueType.STRING_V)
+ .setStringV("groupValue").build())
+ .build())
+ .setPostAttributeScope(DataConstants.SERVER_SCOPE)
+ .setPostTelemetryMsg(TransportProtos.PostTelemetryMsg.newBuilder()
+ .addTsKvList(TransportProtos.TsKvListProto.newBuilder()
+ .setTs(System.currentTimeMillis())
+ .addKv(TransportProtos.KeyValueProto.newBuilder()
+ .setKey("groupTemperature")
+ .setType(TransportProtos.KeyValueType.LONG_V)
+ .setLongV(25).build())
+ .build())
+ .build())
+ .build();
+ sendUplinkMsgAndWaitForResponse(uplinkMsgBuilder -> uplinkMsgBuilder.addEntityData(entityData));
+
+ loginDifferentTenant();
+ String keysUrl = "/api/plugins/telemetry/ENTITY_GROUP/" + savedEntityGroup.getUuidId() + "/keys/";
+ Awaitility.await()
+ .pollDelay(3, TimeUnit.SECONDS)
+ .atMost(10, TimeUnit.SECONDS)
+ .untilAsserted(() -> {
+ List attributeKeys = doGetAsyncTyped(keysUrl + "attributes/" + DataConstants.SERVER_SCOPE, new TypeReference<>() {});
+ Assert.assertTrue(attributeKeys.isEmpty());
+ List timeseriesKeys = doGetAsyncTyped(keysUrl + "timeseries", new TypeReference<>() {});
+ Assert.assertTrue(timeseriesKeys.isEmpty());
+ });
+ }
+
}
diff --git a/application/src/test/java/org/thingsboard/server/edge/UserEdgeTest.java b/application/src/test/java/org/thingsboard/server/edge/UserEdgeTest.java
index 629e6f9f15..b00b9f5380 100644
--- a/application/src/test/java/org/thingsboard/server/edge/UserEdgeTest.java
+++ b/application/src/test/java/org/thingsboard/server/edge/UserEdgeTest.java
@@ -5,11 +5,11 @@ package org.thingsboard.server.edge;
import com.fasterxml.jackson.databind.JsonNode;
import com.google.protobuf.AbstractMessage;
+import org.awaitility.Awaitility;
import org.junit.Assert;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
-import org.testcontainers.shaded.org.awaitility.Awaitility;
import org.thingsboard.common.util.JacksonUtil;
import org.thingsboard.server.common.data.Customer;
import org.thingsboard.server.common.data.EdgeUtils;
diff --git a/application/src/test/java/org/thingsboard/server/install/ThingsboardInstallServiceTest.java b/application/src/test/java/org/thingsboard/server/install/ThingsboardInstallServiceTest.java
index d45fdf064d..e74f41f643 100644
--- a/application/src/test/java/org/thingsboard/server/install/ThingsboardInstallServiceTest.java
+++ b/application/src/test/java/org/thingsboard/server/install/ThingsboardInstallServiceTest.java
@@ -3,6 +3,10 @@
// SPDX-License-Identifier: Apache-2.0 AND BUSL-1.1
package org.thingsboard.server.install;
+import ch.qos.logback.classic.Level;
+import ch.qos.logback.classic.Logger;
+import ch.qos.logback.classic.spi.ILoggingEvent;
+import ch.qos.logback.core.read.ListAppender;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
@@ -11,6 +15,7 @@ import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.mockito.junit.jupiter.MockitoSettings;
import org.mockito.quality.Strictness;
+import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.test.util.ReflectionTestUtils;
import org.thingsboard.server.dao.sql.citus.CitusSchemaService;
@@ -26,6 +31,7 @@ import org.thingsboard.server.service.install.TsDatabaseSchemaService;
import org.thingsboard.server.service.install.update.CacheCleanupService;
import org.thingsboard.server.service.install.update.DataUpdateService;
+import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.ArgumentMatchers.anyBoolean;
import static org.mockito.Mockito.doThrow;
@@ -189,6 +195,34 @@ class ThingsboardInstallServiceTest {
verify(databaseEntitiesUpgradeService, never()).upgradeDatabase(anyBoolean());
}
+ @Test
+ void anErrorDuringAFreshInstallIsReportedAsAnInstallFailure() throws Exception {
+ ReflectionTestUtils.setField(installService, "isUpgrade", false);
+ ExceptionInInitializerError error = new ExceptionInInitializerError("Fontconfig head is null");
+ doThrow(error).when(systemDataLoaderService).loadSystemWidgets();
+ Logger logger = (Logger) LoggerFactory.getLogger(ThingsboardInstallService.class);
+ ListAppender appender = new ListAppender<>();
+ appender.start();
+ logger.addAppender(appender);
+ try {
+ assertThatThrownBy(() -> installService.performInstall())
+ .isInstanceOf(ThingsboardInstallException.class)
+ .hasCause(error);
+
+ assertThat(appender.list)
+ .filteredOn(e -> e.getLevel() == Level.ERROR)
+ .singleElement()
+ .satisfies(e -> {
+ assertThat(e.getFormattedMessage()).isEqualTo("Unexpected error during ThingsBoard installation!");
+ assertThat(e.getThrowableProxy().getClassName()).isEqualTo(ExceptionInInitializerError.class.getName());
+ assertThat(e.getThrowableProxy().getMessage()).isEqualTo("Fontconfig head is null");
+ assertThat(e.getThrowableProxy().getStackTraceElementProxyArray()).isNotEmpty();
+ });
+ } finally {
+ logger.detachAppender(appender);
+ }
+ }
+
@Test
void postgresToCitusUpgradeFailsWhenCitusSchemaServiceMissing() {
ReflectionTestUtils.setField(installService, "isUpgrade", true);
diff --git a/application/src/test/java/org/thingsboard/server/service/ai/DefaultTbAiServiceTest.java b/application/src/test/java/org/thingsboard/server/service/ai/DefaultTbAiServiceTest.java
index 4f48e5c6c2..245760f276 100644
--- a/application/src/test/java/org/thingsboard/server/service/ai/DefaultTbAiServiceTest.java
+++ b/application/src/test/java/org/thingsboard/server/service/ai/DefaultTbAiServiceTest.java
@@ -4,6 +4,7 @@ package org.thingsboard.server.service.ai;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
+import org.springframework.http.HttpStatus;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
@@ -170,8 +171,9 @@ class DefaultTbAiServiceTest {
}
@ParameterizedTest
- @CsvSource({"400, BAD_REQUEST_PARAMS", "413, BAD_REQUEST_PARAMS", "403, GENERAL", "404, ITEM_NOT_FOUND",
- "409, VERSION_CONFLICT", "429, TOO_MANY_REQUESTS", "401, GENERAL", "500, GENERAL", "0, GENERAL"})
+ @CsvSource({"400, BAD_REQUEST_PARAMS", "413, BAD_REQUEST_PARAMS", "403, PERMISSION_DENIED", "404, ITEM_NOT_FOUND",
+ "409, VERSION_CONFLICT", "429, TOO_MANY_REQUESTS", "401, PERMISSION_DENIED", "500, GENERAL", "0, GENERAL",
+ "502, SERVICE_UNAVAILABLE", "503, SERVICE_UNAVAILABLE", "504, SERVICE_UNAVAILABLE"})
void shouldKeepTheStatusOfTheAiService_whenProcessAndResponseIsFailure(int status, ThingsboardErrorCode errorCode) {
// GIVEN
given(apiUsageStateService.getApiUsageState(tenantId)).willReturn(enabledApiUsageState());
@@ -189,7 +191,7 @@ class DefaultTbAiServiceTest {
void shouldReportCreditsThenThrowGeneral_whenProcessAndResponseIsFailure() {
// GIVEN
given(apiUsageStateService.getApiUsageState(tenantId)).willReturn(enabledApiUsageState());
- given(call.apply(any())).willReturn(TbAiResponse.builder().success(false).error("Upstream rejected").creditsUsed(42).build());
+ given(call.apply(any())).willReturn(TbAiResponse.builder().success(false).status(500).error("Upstream rejected").creditsUsed(42).build());
// WHEN
Throwable thrown = catchThrowable(() -> service.process(call, user, true));
@@ -493,12 +495,12 @@ class DefaultTbAiServiceTest {
static List upstreamErrors() {
return List.of(
// PE-side inactivity timeout from the .timeout(...) operator
- arguments(new TimeoutException("inactivity"), "Request timed out"),
+ arguments(new TimeoutException("inactivity"), TbAiOperations.TIMED_OUT_MESSAGE),
// the AI channel cannot be opened or closed before the turn started
- arguments(new TbAiChannelUnavailableException("Connection refused", null), "Service unavailable"),
+ arguments(new TbAiChannelUnavailableException("Connection refused", null), TbAiOperations.UNAVAILABLE_MESSAGE),
// the channel handshake was refused: the reason phrase is shown
- arguments(new TbAiChannelRejectedException("Unauthorized"), "Unauthorized"),
- arguments(new TbAiChannelRejectedException("Forbidden"), "Forbidden"),
+ arguments(new TbAiChannelRejectedException(HttpStatus.UNAUTHORIZED), "Unauthorized"),
+ arguments(new TbAiChannelRejectedException(HttpStatus.FORBIDDEN), "Forbidden"),
// any other unexpected throwable
arguments(new RuntimeException("boom"), "Internal error")
);
diff --git a/application/src/test/java/org/thingsboard/server/service/ai/chat/DefaultAiChatServiceTest.java b/application/src/test/java/org/thingsboard/server/service/ai/chat/DefaultAiChatServiceTest.java
index a5606a95bf..1ea3dcd21c 100644
--- a/application/src/test/java/org/thingsboard/server/service/ai/chat/DefaultAiChatServiceTest.java
+++ b/application/src/test/java/org/thingsboard/server/service/ai/chat/DefaultAiChatServiceTest.java
@@ -17,6 +17,9 @@ import org.thingsboard.ai.common.channel.ChannelProtocol;
import org.thingsboard.ai.common.channel.ChatOperationRequest;
import org.thingsboard.ai.common.client.TbAiClient;
import org.thingsboard.common.util.JacksonUtil;
+import org.thingsboard.server.cache.limits.RateLimitService;
+import org.thingsboard.server.common.data.id.TenantId;
+import org.thingsboard.server.common.data.limit.LimitedApi;
import org.thingsboard.server.service.ai.TbAiService;
import org.thingsboard.server.service.ai.transport.TbAiTransport;
import org.thingsboard.server.service.ai.transport.TbAiTurnContext;
@@ -53,23 +56,25 @@ class DefaultAiChatServiceTest {
TbAiOperations operations;
@Mock
TbAiTransport tbAiTransport;
+ @Mock
+ RateLimitService rateLimitService;
DefaultAiChatService service;
@BeforeEach
void setUp() {
- service = new DefaultAiChatService(tbAiService, tbAiTransport, operations);
+ service = new DefaultAiChatService(tbAiService, tbAiTransport, operations, rateLimitService);
lenient().when(operations.execute(any(TbAiOperation.class), any(SecurityUser.class), any(TbAiClient.TokenProvider.class)))
.thenReturn(tbAiResponse);
}
@Test
- void shouldProcessWithoutCreditCheckAndDelegateToClient_whenCreateChatCalled() {
+ void shouldProcessWithCreditCheckAndDelegateToClient_whenCreateChatCalled() {
// GIVEN
JsonNode request = createChatRequest("New chat");
UUID chatId = UUID.randomUUID();
JsonNode expectedResponse = TextNode.valueOf(chatId.toString());
- given(tbAiService.process(any(), same(user), eq(false))).willReturn(expectedResponse);
+ given(tbAiService.process(any(), same(user), eq(true))).willReturn(expectedResponse);
// WHEN
JsonNode result = service.createChat(request, user);
@@ -77,7 +82,7 @@ class DefaultAiChatServiceTest {
// THEN
assertThat(result).isSameAs(expectedResponse);
- assertThat(captureProcessCall().apply(tokenProvider)).isSameAs(tbAiResponse);
+ assertThat(captureProcessCall(true).apply(tokenProvider)).isSameAs(tbAiResponse);
then(operations).should().execute(argThat(operation -> ChannelProtocol.CHAT_CREATE.equals(operation.type())
&& Objects.equals(new ChatOperationRequest(null, request), operation.payload())), same(user), same(tokenProvider));
then(tbAiService).shouldHaveNoMoreInteractions();
@@ -94,7 +99,7 @@ class DefaultAiChatServiceTest {
service.updateChat(chatId, request, user);
// THEN
- assertThat(captureProcessCall().apply(tokenProvider)).isSameAs(tbAiResponse);
+ assertThat(captureProcessCall(false).apply(tokenProvider)).isSameAs(tbAiResponse);
then(operations).should().execute(argThat(operation -> ChannelProtocol.CHAT_UPDATE.equals(operation.type())
&& Objects.equals(new ChatOperationRequest(chatId, request), operation.payload())), same(user), same(tokenProvider));
then(tbAiService).shouldHaveNoMoreInteractions();
@@ -113,7 +118,7 @@ class DefaultAiChatServiceTest {
// THEN
assertThat(result).isSameAs(expectedResponse);
- assertThat(captureProcessCall().apply(tokenProvider)).isSameAs(tbAiResponse);
+ assertThat(captureProcessCall(false).apply(tokenProvider)).isSameAs(tbAiResponse);
then(operations).should().execute(argThat(operation -> ChannelProtocol.CHAT_LIST.equals(operation.type())
&& Objects.equals(null, operation.payload())), same(user), same(tokenProvider));
then(tbAiService).shouldHaveNoMoreInteractions();
@@ -132,7 +137,7 @@ class DefaultAiChatServiceTest {
// THEN
assertThat(result).isSameAs(expectedResponse);
- assertThat(captureProcessCall().apply(tokenProvider)).isSameAs(tbAiResponse);
+ assertThat(captureProcessCall(false).apply(tokenProvider)).isSameAs(tbAiResponse);
then(operations).should().execute(argThat(operation -> ChannelProtocol.CHAT_MESSAGES.equals(operation.type())
&& Objects.equals(new ChatOperationRequest(chatId, JacksonUtil.newObjectNode().put("toolCards", true)), operation.payload())),
same(user), same(tokenProvider));
@@ -149,12 +154,28 @@ class DefaultAiChatServiceTest {
service.deleteChat(chatId, user);
// THEN
- assertThat(captureProcessCall().apply(tokenProvider)).isSameAs(tbAiResponse);
+ assertThat(captureProcessCall(false).apply(tokenProvider)).isSameAs(tbAiResponse);
then(operations).should().execute(argThat(operation -> ChannelProtocol.CHAT_DELETE.equals(operation.type())
&& Objects.equals(new ChatOperationRequest(chatId, null), operation.payload())), same(user), same(tokenProvider));
then(tbAiService).shouldHaveNoMoreInteractions();
}
+ @Test
+ void shouldProcessWithoutCreditCheckAndDelegateToClient_whenStopChatCalled() {
+ // GIVEN
+ UUID chatId = UUID.randomUUID();
+ given(tbAiService.process(any(), same(user), eq(false))).willReturn(null);
+
+ // WHEN
+ service.stopChat(chatId, user);
+
+ // THEN
+ assertThat(captureProcessCall(false).apply(tokenProvider)).isSameAs(tbAiResponse);
+ then(operations).should().execute(argThat(operation -> ChannelProtocol.CHAT_STOP.equals(operation.type())
+ && Objects.equals(new ChatOperationRequest(chatId, null), operation.payload())), same(user), same(tokenProvider));
+ then(tbAiService).shouldHaveNoMoreInteractions();
+ }
+
@Test
void shouldProcessStreamAndDelegateToTransportWithTurnContext_whenSendChatMessageWithClientContextCalled() {
// GIVEN
@@ -166,6 +187,9 @@ class DefaultAiChatServiceTest {
.event("assistantMessage")
.data("{\"message\":\"ok\"}")
.build());
+ TenantId tenantId = TenantId.fromUUID(UUID.randomUUID());
+ given(user.getTenantId()).willReturn(tenantId);
+ given(rateLimitService.checkRateLimit(LimitedApi.AI_CHAT_REQUESTS, tenantId)).willReturn(true);
given(tbAiService.processStream(eq(chatId), any(), same(user), any(TbAiTurnLink.class), eq(true))).willReturn(expectedStream);
var clientOrigin = "https://tb.example.com";
var expectedContext = new TbAiTurnContext(user, tbAccessToken, acceptLanguage, tokenProvider, clientOrigin);
@@ -184,6 +208,26 @@ class DefaultAiChatServiceTest {
then(tbAiService).shouldHaveNoMoreInteractions();
}
+ @Test
+ void shouldAnswerWithRateLimitedError_whenTenantExceedsAiChatRequestsLimit() {
+ // GIVEN
+ UUID chatId = UUID.randomUUID();
+ TenantId tenantId = TenantId.fromUUID(UUID.randomUUID());
+ given(user.getTenantId()).willReturn(tenantId);
+ given(rateLimitService.checkRateLimit(LimitedApi.AI_CHAT_REQUESTS, tenantId)).willReturn(false);
+
+ // WHEN
+ var events = service.sendChatMessage(chatId, sendMessageBody("And how many assets?", "DEVICE_LIST"),
+ "tb-access-token", "en-US", "https://tb.example.com", user).collectList().block();
+
+ // THEN
+ assertThat(events).hasSize(1);
+ assertThat(events.get(0).event()).isEqualTo("error");
+ assertThat(events.get(0).data()).isEqualTo("{\"message\":\"Rate limit exceeded\",\"code\":\"RATE_LIMITED\"}");
+ then(tbAiService).shouldHaveNoInteractions();
+ then(tbAiTransport).shouldHaveNoInteractions();
+ }
+
@Test
void shouldFollowTheRunningTurnWithoutCreditCheck_whenResumeChatCalled() {
// GIVEN
@@ -211,9 +255,9 @@ class DefaultAiChatServiceTest {
}
@SuppressWarnings({"rawtypes", "unchecked"})
- private TbAiService.TbAiCall captureProcessCall() {
+ private TbAiService.TbAiCall captureProcessCall(boolean checkCredits) {
ArgumentCaptor callCaptor = ArgumentCaptor.forClass(TbAiService.TbAiCall.class);
- then(tbAiService).should().process(callCaptor.capture(), same(user), eq(false));
+ then(tbAiService).should().process(callCaptor.capture(), same(user), eq(checkCredits));
return callCaptor.getValue();
}
diff --git a/application/src/test/java/org/thingsboard/server/service/ai/solution/DefaultAiSolutionServiceTest.java b/application/src/test/java/org/thingsboard/server/service/ai/solution/DefaultAiSolutionServiceTest.java
index 723dc0131e..1ca652aff1 100644
--- a/application/src/test/java/org/thingsboard/server/service/ai/solution/DefaultAiSolutionServiceTest.java
+++ b/application/src/test/java/org/thingsboard/server/service/ai/solution/DefaultAiSolutionServiceTest.java
@@ -22,7 +22,10 @@ import org.thingsboard.ai.common.channel.SolutionStepRequest;
import org.thingsboard.ai.common.client.TbAiClient;
import org.thingsboard.ai.common.data.solution.SolutionStep;
import org.thingsboard.common.util.JacksonUtil;
+import org.thingsboard.server.cache.limits.RateLimitService;
import org.thingsboard.server.common.data.exception.ThingsboardErrorCode;
+import org.thingsboard.server.common.data.id.TenantId;
+import org.thingsboard.server.common.data.limit.LimitedApi;
import org.thingsboard.server.exception.ThingsboardRuntimeException;
import org.thingsboard.server.service.ai.TbAiService;
import org.thingsboard.server.service.ai.transport.TbAiOperation;
@@ -58,6 +61,10 @@ class DefaultAiSolutionServiceTest {
TbAiOperations operations;
@Mock
SecurityUser user;
+ @Mock
+ RateLimitService rateLimitService;
+
+ TenantId tenantId = TenantId.fromUUID(UUID.randomUUID());
String clientOrigin = "https://tb.example.com";
@@ -65,16 +72,18 @@ class DefaultAiSolutionServiceTest {
@BeforeEach
void setUp() {
- service = new DefaultAiSolutionService(tbAiService, operations);
+ service = new DefaultAiSolutionService(tbAiService, operations, rateLimitService);
+ lenient().when(user.getTenantId()).thenReturn(tenantId);
+ lenient().when(rateLimitService.checkRateLimit(LimitedApi.AI_CHAT_REQUESTS, tenantId)).thenReturn(true);
lenient().when(operations.execute(any(TbAiOperation.class), any(SecurityUser.class), any(TbAiClient.TokenProvider.class)))
.thenReturn(tbAiResponse);
}
@Test
- void shouldProcessWithoutCreditCheckAndDelegateToClient_whenStartNewCalled() {
+ void shouldProcessWithCreditCheckAndDelegateToClient_whenStartNewCalled() {
// GIVEN
JsonNode expectedResponse = solutionResponse(UUID.randomUUID(), "Energy Monitoring", false, false);
- given(tbAiService.process(any(), same(user), eq(false))).willReturn(expectedResponse);
+ given(tbAiService.process(any(), same(user))).willReturn(expectedResponse);
// WHEN
JsonNode result = service.startNew(user);
@@ -82,7 +91,7 @@ class DefaultAiSolutionServiceTest {
// THEN
assertThat(result).isSameAs(expectedResponse);
- assertThat(captureProcessCallWithoutCreditCheck().apply(tokenProvider)).isSameAs(tbAiResponse);
+ assertThat(captureProcessCallWithCreditCheck().apply(tokenProvider)).isSameAs(tbAiResponse);
then(operations).should().execute(argThat(operation -> ChannelProtocol.SOLUTION_START.equals(operation.type())
&& Objects.equals(null, operation.payload())), same(user), same(tokenProvider));
then(tbAiService).shouldHaveNoMoreInteractions();
@@ -136,6 +145,20 @@ class DefaultAiSolutionServiceTest {
then(tbAiService).shouldHaveNoInteractions();
}
+ @Test
+ void shouldRefuseWithTooManyRequestsWithoutCallingTheAiService_whenTheTenantIsOverTheChatRequestsLimit() {
+ // GIVEN
+ given(rateLimitService.checkRateLimit(LimitedApi.AI_CHAT_REQUESTS, tenantId)).willReturn(false);
+
+ // WHEN
+ Throwable thrown = catchThrowable(() -> service.chat(UUID.randomUUID(), SolutionStep.INITIAL_CONFIGURATION, "Add humidity", List.of(), user));
+
+ // THEN
+ assertThat(thrown).isInstanceOf(ThingsboardRuntimeException.class).hasMessage("Rate limit exceeded");
+ assertThat(((ThingsboardRuntimeException) thrown).getErrorCode()).isEqualTo(ThingsboardErrorCode.TOO_MANY_REQUESTS);
+ then(tbAiService).shouldHaveNoInteractions();
+ }
+
@ParameterizedTest
@EnumSource(SolutionStep.class)
void shouldProcessWithCreditCheckAndDelegateToClient_whenChatCalled(SolutionStep step) {
@@ -214,6 +237,22 @@ class DefaultAiSolutionServiceTest {
then(tbAiService).shouldHaveNoMoreInteractions();
}
+ @Test
+ void shouldProcessWithoutCreditCheckAndDelegateToClient_whenStopSolutionCalled() {
+ // GIVEN
+ UUID solutionId = UUID.randomUUID();
+ given(tbAiService.process(any(), same(user), eq(false))).willReturn(null);
+
+ // WHEN
+ service.stopSolution(solutionId, user);
+
+ // THEN
+ assertThat(captureProcessCallWithoutCreditCheck().apply(tokenProvider)).isSameAs(tbAiResponse);
+ then(operations).should().execute(argThat(operation -> ChannelProtocol.SOLUTION_STOP.equals(operation.type())
+ && Objects.equals(new SolutionOperationRequest(solutionId), operation.payload())), same(user), same(tokenProvider));
+ then(tbAiService).shouldHaveNoMoreInteractions();
+ }
+
@Test
void shouldProcessWithoutCreditCheckAndDelegateToClient_whenInstallSolutionCalled() {
// GIVEN
diff --git a/application/src/test/java/org/thingsboard/server/service/ai/transport/ChannelTbAiOperationsTest.java b/application/src/test/java/org/thingsboard/server/service/ai/transport/ChannelTbAiOperationsTest.java
index c5771a6b26..3665c2476c 100644
--- a/application/src/test/java/org/thingsboard/server/service/ai/transport/ChannelTbAiOperationsTest.java
+++ b/application/src/test/java/org/thingsboard/server/service/ai/transport/ChannelTbAiOperationsTest.java
@@ -189,7 +189,8 @@ class ChannelTbAiOperationsTest {
// THEN
assertThat(response.isSuccess()).isFalse();
- assertThat(response.getError()).isEqualTo("Service unavailable");
+ assertThat(response.getStatus()).isEqualTo(503);
+ assertThat(response.getError()).isEqualTo(TbAiOperations.UNAVAILABLE_MESSAGE);
assertThat(server.received(ChannelProtocol.SOLUTION_INSTALL)).hasSize(1);
}
@@ -239,7 +240,8 @@ class ChannelTbAiOperationsTest {
// THEN
assertThat(response.isSuccess()).isFalse();
- assertThat(response.getError()).isEqualTo("Service unavailable");
+ assertThat(response.getStatus()).isEqualTo(503);
+ assertThat(response.getError()).isEqualTo(TbAiOperations.UNAVAILABLE_MESSAGE);
assertThat(server.received(ChannelProtocol.SOLUTION_INSTALL)).hasSize(1);
assertThat(server.connections.get()).isEqualTo(1);
}
diff --git a/application/src/test/java/org/thingsboard/server/service/ai/transport/ChannelTbAiTransportTest.java b/application/src/test/java/org/thingsboard/server/service/ai/transport/ChannelTbAiTransportTest.java
index a7095f83e3..7635a173e1 100644
--- a/application/src/test/java/org/thingsboard/server/service/ai/transport/ChannelTbAiTransportTest.java
+++ b/application/src/test/java/org/thingsboard/server/service/ai/transport/ChannelTbAiTransportTest.java
@@ -72,7 +72,7 @@ class ChannelTbAiTransportTest {
assertThat(second).hasSize(3);
assertThat(server.connections.get()).isEqualTo(1);
ChannelHello hello = server.codec.fromPayload(server.received(ChannelProtocol.HELLO).getFirst().payload(), ChannelHello.class);
- assertThat(hello).isEqualTo(new ChannelHello(1, TbAiPooledConnection.CLIENT_CAPABILITIES, "https://tb.example.com", null));
+ assertThat(hello).isEqualTo(new ChannelHello(1, List.of("chat.kit"), "https://tb.example.com", null));
ChannelFrame send = server.received(ChannelProtocol.CHAT_SEND).getFirst();
ChatTurnRequest turnRequest = server.codec.fromPayload(send.payload(), ChatTurnRequest.class);
assertThat(turnRequest.request()).isEqualTo(request);
diff --git a/application/src/test/java/org/thingsboard/server/service/ai/transport/TbAiChannelPoolTest.java b/application/src/test/java/org/thingsboard/server/service/ai/transport/TbAiChannelPoolTest.java
index 4b5a5e41df..fcf55c4214 100644
--- a/application/src/test/java/org/thingsboard/server/service/ai/transport/TbAiChannelPoolTest.java
+++ b/application/src/test/java/org/thingsboard/server/service/ai/transport/TbAiChannelPoolTest.java
@@ -7,17 +7,24 @@ import org.junit.jupiter.api.Test;
import org.springframework.http.HttpHeaders;
import org.thingsboard.ai.common.channel.ChannelProtocol;
import org.thingsboard.ai.common.client.TbAiHeaders;
+import org.thingsboard.ai.common.client.TbAiTokenFactory;
+import org.thingsboard.ai.common.data.usage.RateLimitScope;
+import org.thingsboard.ai.common.data.usage.RateLimitedApi;
+import org.thingsboard.ai.common.data.user.ProfileConfig;
import org.thingsboard.server.common.data.id.TenantId;
import org.thingsboard.server.common.data.id.UserId;
import org.thingsboard.server.service.security.model.SecurityUser;
+import java.nio.charset.StandardCharsets;
import java.time.Duration;
+import java.util.Base64;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong;
+import java.util.concurrent.atomic.AtomicReference;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
@@ -28,6 +35,8 @@ import static org.mockito.Mockito.mock;
class TbAiChannelPoolTest {
static final String TB_VERSION = "4.4.0";
+ static final TbAiTokenFactory TOKEN_FACTORY = new TbAiTokenFactory("test", Base64.getEncoder()
+ .encodeToString("tb-ai-channel-pool-test-signing-key-".repeat(2).getBytes(StandardCharsets.UTF_8)), Duration.ofMinutes(60));
AtomicLong now = new AtomicLong(1_000_000_000L);
FakeTbAiServer server = FakeTbAiServer.start((connection, frame) -> {});
@@ -246,6 +255,68 @@ class TbAiChannelPoolTest {
await().atMost(5, TimeUnit.SECONDS).until(() -> pool.pooledConnections() == 0);
}
+ @Test
+ void shouldRetireIdleChannel_whenTheTokenCarriesOtherLimits() {
+ // GIVEN
+ pool = pool(10);
+ SecurityUser user = user();
+ AtomicReference token = new AtomicReference<>(token("10:60", "198.51.100.10"));
+ TbAiTurnContext context = context(user, token);
+ TbAiPooledConnection before = join(pool.acquire(context, false));
+ before.unreserve(now.get());
+
+ // WHEN
+ token.set(token("1:60", "198.51.100.10"));
+ TbAiPooledConnection after = join(pool.acquire(context, false));
+
+ // THEN
+ assertThat(after).isNotSameAs(before);
+ assertThat(server.connections.get()).isEqualTo(2);
+ await().atMost(5, TimeUnit.SECONDS).until(() -> server.openConnections.get() == 1);
+ }
+
+ @Test
+ void shouldFinishTheRunningCallOnAStaleChannel_thenCloseIt() {
+ // GIVEN
+ pool = pool(10);
+ AtomicReference token = new AtomicReference<>(token("10:60", "198.51.100.10"));
+ TbAiTurnContext context = context(user(), token);
+ TbAiPooledConnection busy = join(pool.acquire(context, false));
+
+ // WHEN
+ token.set(token("1:60", "198.51.100.10"));
+ TbAiPooledConnection next = join(pool.acquire(context, false));
+ int openWhileBusy = server.openConnections.get();
+ busy.unreserve(now.get());
+
+ // THEN
+ assertThat(next).isNotSameAs(busy);
+ assertThat(openWhileBusy).isEqualTo(2);
+ await().atMost(5, TimeUnit.SECONDS).until(() -> server.openConnections.get() == 1);
+ }
+
+ @Test
+ void shouldKeepChannel_whenOnlyTheClientAddressChanged() {
+ // GIVEN
+ pool = pool(10);
+ AtomicReference token = new AtomicReference<>(token("10:60", "198.51.100.10"));
+ TbAiTurnContext context = context(user(), token);
+ TbAiPooledConnection desktop = join(pool.acquire(context, false));
+ desktop.unreserve(now.get());
+
+ // WHEN
+ token.set(token("10:60", "203.0.113.20"));
+ TbAiPooledConnection mobile = join(pool.acquire(context, false));
+ mobile.unreserve(now.get());
+ token.set(token("10:60", "198.51.100.10"));
+ TbAiPooledConnection desktopAgain = join(pool.acquire(context, false));
+
+ // THEN
+ assertThat(mobile).isSameAs(desktop);
+ assertThat(desktopAgain).isSameAs(desktop);
+ assertThat(server.connections.get()).isEqualTo(1);
+ }
+
TbAiChannelPool pool(int maxConnections) {
return new TbAiChannelPool(server.client(), TB_VERSION, maxConnections, 20, Duration.ofSeconds(60), Duration.ofMinutes(10), now::get, false);
}
@@ -265,4 +336,14 @@ class TbAiChannelPoolTest {
return new TbAiTurnContext(user, null, null, () -> "token", origin);
}
+ static TbAiTurnContext context(SecurityUser user, AtomicReference token) {
+ return new TbAiTurnContext(user, null, null, token::get, "https://tb.example.com");
+ }
+
+ static String token(String chatRequestsLimit, String clientAddress) {
+ ProfileConfig profileConfig = new ProfileConfig();
+ profileConfig.setRateLimits(Map.of(RateLimitedApi.AI_CHAT_REQUESTS, Map.of(RateLimitScope.TENANT, chatRequestsLimit)));
+ return TOKEN_FACTORY.createToken(UUID.randomUUID().toString(), profileConfig, Map.of("clientAddress", clientAddress));
+ }
+
}
diff --git a/application/src/test/java/org/thingsboard/server/service/ai/transport/TbAiOperationsTest.java b/application/src/test/java/org/thingsboard/server/service/ai/transport/TbAiOperationsTest.java
index eb751dba12..c0217ea02f 100644
--- a/application/src/test/java/org/thingsboard/server/service/ai/transport/TbAiOperationsTest.java
+++ b/application/src/test/java/org/thingsboard/server/service/ai/transport/TbAiOperationsTest.java
@@ -2,6 +2,7 @@
// SPDX-License-Identifier: BUSL-1.1
package org.thingsboard.server.service.ai.transport;
+import org.springframework.http.HttpStatus;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
import org.thingsboard.ai.common.channel.ChannelProtocol;
@@ -50,19 +51,21 @@ class TbAiOperationsTest {
// THEN
assertThat(response.isSuccess()).isFalse();
- assertThat(response.getError()).isEqualTo("Service unavailable");
+ assertThat(response.getStatus()).isEqualTo(503);
+ assertThat(response.getError()).isEqualTo(TbAiOperations.UNAVAILABLE_MESSAGE);
}
@Test
void shouldReturnRejection_whenChannelHandshakeIsRefused() {
// GIVEN
- given(channel.execute(operation, context)).willThrow(new TbAiChannelRejectedException("Unauthorized"));
+ given(channel.execute(operation, context)).willThrow(new TbAiChannelRejectedException(HttpStatus.UNAUTHORIZED));
// WHEN
TbAiResponse response = operations.execute(operation, context);
// THEN
assertThat(response.isSuccess()).isFalse();
+ assertThat(response.getStatus()).isEqualTo(401);
assertThat(response.getError()).isEqualTo("Unauthorized");
}
diff --git a/application/src/test/java/org/thingsboard/server/service/ai/transport/TbAiPooledConnectionTest.java b/application/src/test/java/org/thingsboard/server/service/ai/transport/TbAiPooledConnectionTest.java
index b77252bf94..028c865290 100644
--- a/application/src/test/java/org/thingsboard/server/service/ai/transport/TbAiPooledConnectionTest.java
+++ b/application/src/test/java/org/thingsboard/server/service/ai/transport/TbAiPooledConnectionTest.java
@@ -14,7 +14,6 @@ import org.thingsboard.server.common.data.id.TenantId;
import org.thingsboard.server.common.data.id.UserId;
import java.time.Duration;
-import java.util.List;
import java.util.UUID;
import java.util.concurrent.TimeoutException;
@@ -71,7 +70,7 @@ class TbAiPooledConnectionTest {
}
@Test
- void shouldSendHelloWithoutCapabilities_whenSessionOpens() {
+ void shouldSendHelloWithItsCapabilities_whenSessionOpens() {
// GIVEN
TbAiPooledConnection connection = connection();
ChannelSession session = openSession();
@@ -83,12 +82,30 @@ class TbAiPooledConnectionTest {
// THEN
then(session).should().send(ChannelFrame.of(ChannelProtocol.HELLO,
- codec.toPayload(new ChannelHello(ChannelProtocol.VERSION, List.of(), "https://tb.example.com", null))));
+ codec.toPayload(new ChannelHello(ChannelProtocol.VERSION, TbAiPooledConnection.CLIENT_CAPABILITIES, "https://tb.example.com", null))));
then(session).should(never()).close(anyInt(), anyString());
assertThat(connection.ready()).isCompletedWithValue(connection);
assertThat(connection.maxFrameBytes()).isEqualTo(1024);
}
+ @Test
+ void shouldBeStale_whenTheCallerHoldsOtherLimits() {
+ // GIVEN
+ TbAiPooledConnection connection = connection();
+ connection.handshakeLimits("limits-before-the-profile-change");
+
+ // WHEN-THEN
+ assertThat(connection.isStaleFor("limits-after-the-profile-change")).isTrue();
+ assertThat(connection.isStaleFor("limits-before-the-profile-change")).isFalse();
+ assertThat(connection.isStaleFor(null)).isFalse();
+ }
+
+ @Test
+ void shouldNotBeStale_whenItsHandshakeLimitsAreUnknown() {
+ // WHEN-THEN
+ assertThat(connection().isStaleFor("any-limits")).isFalse();
+ }
+
TbAiPooledConnection connection() {
return new TbAiPooledConnection(key, "https://tb.example.com", false, 20, codec, pool, System.nanoTime());
}
diff --git a/application/src/test/java/org/thingsboard/server/service/cf/ctx/state/GeofencingValueArgumentEntryTest.java b/application/src/test/java/org/thingsboard/server/service/cf/ctx/state/GeofencingValueArgumentEntryTest.java
index eb9fe521f3..1f51ed9e25 100644
--- a/application/src/test/java/org/thingsboard/server/service/cf/ctx/state/GeofencingValueArgumentEntryTest.java
+++ b/application/src/test/java/org/thingsboard/server/service/cf/ctx/state/GeofencingValueArgumentEntryTest.java
@@ -1,13 +1,14 @@
// SPDX-FileCopyrightText: Copyright The ThingsBoard Authors
-// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Modifications Copyright ThingsBoard, Inc.
+// SPDX-License-Identifier: Apache-2.0 AND BUSL-1.1
package org.thingsboard.server.service.cf.ctx.state;
-import io.hypersistence.utils.hibernate.type.json.internal.JacksonUtil;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
+import org.thingsboard.common.util.JacksonUtil;
import org.thingsboard.common.util.geo.PerimeterDefinition;
import org.thingsboard.server.common.data.id.AssetId;
import org.thingsboard.server.common.data.id.EntityId;
diff --git a/application/src/test/java/org/thingsboard/server/service/entitiy/EntityServiceTest.java b/application/src/test/java/org/thingsboard/server/service/entitiy/EntityServiceTest.java
index 208c4ae00e..e509d2666d 100644
--- a/application/src/test/java/org/thingsboard/server/service/entitiy/EntityServiceTest.java
+++ b/application/src/test/java/org/thingsboard/server/service/entitiy/EntityServiceTest.java
@@ -2105,6 +2105,7 @@ public class EntityServiceTest extends AbstractControllerTest {
entityView.setCustomerId(customerId);
entityView.setName("test");
entityView.setType("default");
+ entityView.setEntityId(deviceId);
customerEntityIds.add(entityViewService.saveEntityView(entityView).getId());
EntityGroup entityGroup = new EntityGroup();
@@ -3876,12 +3877,18 @@ public class EntityServiceTest extends AbstractControllerTest {
@Test
public void testEntityViewEntityMapping() {
+ Device device = new Device();
+ device.setTenantId(tenantId);
+ device.setName("Device for entity view");
+ device.setType("default");
+ device = deviceService.saveDevice(device);
+
EntityView entityView = new EntityView();
entityView.setTenantId(tenantId);
entityView.setCustomerId(customerId);
entityView.setName("test");
entityView.setType("default");
- entityView.setEntityId(new DeviceId(UUID.randomUUID()));
+ entityView.setEntityId(device.getId());
entityView.setKeys(new TelemetryEntityView(List.of("test"), null));
entityView.setStartTimeMs(124);
entityView.setEndTimeMs(256);
@@ -3913,12 +3920,18 @@ public class EntityServiceTest extends AbstractControllerTest {
@Test
public void testFindEntitiesWithEntityViewFilter() {
+ Device device = new Device();
+ device.setTenantId(tenantId);
+ device.setName("Device for entity view");
+ device.setType("default");
+ device = deviceService.saveDevice(device);
+
EntityView entityView = new EntityView();
entityView.setTenantId(tenantId);
entityView.setCustomerId(customerId);
entityView.setName("test");
entityView.setType("default");
- entityView.setEntityId(new DeviceId(UUID.randomUUID()));
+ entityView.setEntityId(device.getId());
entityView.setKeys(new TelemetryEntityView(List.of("test"), null));
entityView.setStartTimeMs(124);
entityView.setEndTimeMs(256);
diff --git a/application/src/test/java/org/thingsboard/server/service/install/lts/MigrationIntegrationTest.java b/application/src/test/java/org/thingsboard/server/service/install/lts/MigrationIntegrationTest.java
index bbdb95c466..0d557be89b 100644
--- a/application/src/test/java/org/thingsboard/server/service/install/lts/MigrationIntegrationTest.java
+++ b/application/src/test/java/org/thingsboard/server/service/install/lts/MigrationIntegrationTest.java
@@ -57,9 +57,9 @@ public class MigrationIntegrationTest extends AbstractControllerTest {
private static final String SCHEMA_UPDATE_SQL = "schema_update.sql";
// Versions with a registered bean but no schema_update.sql, because their whole change is programmatic:
- // 4.3.1.5 rewrites one JSON column through the DAO. Entries here opt out of the dir/bean check below,
+ // 4.3.1.5 rewrites one JSON column through the DAO, 4.4.2.0 adds a notification template. Entries here opt out of the dir/bean check below,
// so add one only when the version genuinely ships no SQL.
- private static final Set SQL_LESS_ALLOWED = Set.of("4.3.1.5");
+ private static final Set SQL_LESS_ALLOWED = Set.of("4.3.1.5", "4.4.2.0");
@Autowired
private MigrationService migrationService;
diff --git a/application/src/test/java/org/thingsboard/server/service/install/lts/V4_4_2_0MigrationTest.java b/application/src/test/java/org/thingsboard/server/service/install/lts/V4_4_2_0MigrationTest.java
new file mode 100644
index 0000000000..37dc7bd57e
--- /dev/null
+++ b/application/src/test/java/org/thingsboard/server/service/install/lts/V4_4_2_0MigrationTest.java
@@ -0,0 +1,56 @@
+// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc.
+// SPDX-License-Identifier: BUSL-1.1
+package org.thingsboard.server.service.install.lts;
+
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.ExtendWith;
+import org.mockito.InjectMocks;
+import org.mockito.Mock;
+import org.mockito.junit.jupiter.MockitoExtension;
+import org.thingsboard.server.common.data.id.TenantId;
+import org.thingsboard.server.common.data.notification.NotificationType;
+import org.thingsboard.server.dao.notification.DefaultNotifications;
+import org.thingsboard.server.dao.notification.NotificationSettingsService;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.Mockito.never;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+
+@ExtendWith(MockitoExtension.class)
+class V4_4_2_0MigrationTest {
+
+ @Mock
+ private NotificationSettingsService notificationSettingsService;
+ @Mock
+ private DefaultNotifications defaultNotifications;
+
+ @InjectMocks
+ private V4_4_2_0Migration migration;
+
+ @Test
+ void hasItsVersion() {
+ assertEquals("4.4.2.0", migration.getVersion());
+ }
+
+ @Test
+ void createsAiCreditsLimitIncreaseRequestTemplateWhenMissing() {
+ when(notificationSettingsService.isNotificationConfigured(TenantId.SYS_TENANT_ID, NotificationType.AI_CREDITS_LIMIT_INCREASE_REQUEST))
+ .thenReturn(false);
+
+ migration.apply();
+
+ verify(defaultNotifications).create(TenantId.SYS_TENANT_ID, DefaultNotifications.aiCreditsLimitIncreaseRequest);
+ }
+
+ @Test
+ void keepsAiCreditsLimitIncreaseRequestTemplateWhenPresent() {
+ when(notificationSettingsService.isNotificationConfigured(TenantId.SYS_TENANT_ID, NotificationType.AI_CREDITS_LIMIT_INCREASE_REQUEST))
+ .thenReturn(true);
+
+ migration.apply();
+
+ verify(defaultNotifications, never()).create(any(), any());
+ }
+}
diff --git a/application/src/test/java/org/thingsboard/server/service/install/update/EntityViewGroupAllUpdaterTest.java b/application/src/test/java/org/thingsboard/server/service/install/update/EntityViewGroupAllUpdaterTest.java
new file mode 100644
index 0000000000..f939680b3f
--- /dev/null
+++ b/application/src/test/java/org/thingsboard/server/service/install/update/EntityViewGroupAllUpdaterTest.java
@@ -0,0 +1,35 @@
+// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc.
+// SPDX-License-Identifier: BUSL-1.1
+package org.thingsboard.server.service.install.update;
+
+import org.junit.jupiter.api.Test;
+import org.thingsboard.server.common.data.EntityView;
+import org.thingsboard.server.common.data.group.EntityGroup;
+import org.thingsboard.server.common.data.id.CustomerId;
+import org.thingsboard.server.dao.customer.CustomerService;
+import org.thingsboard.server.dao.entityview.EntityViewService;
+import org.thingsboard.server.dao.group.EntityGroupService;
+
+import java.util.UUID;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.verify;
+
+class EntityViewGroupAllUpdaterTest {
+
+ @Test
+ void testUnassignFromCustomerSavesWithoutValidation() {
+ EntityViewService entityViewService = mock(EntityViewService.class);
+ EntityViewGroupAllUpdater updater = new EntityViewGroupAllUpdater(entityViewService, mock(CustomerService.class),
+ mock(EntityGroupService.class), new EntityGroup(), true);
+ EntityView entityView = new EntityView();
+ entityView.setCustomerId(new CustomerId(UUID.randomUUID()));
+
+ updater.unassignFromCustomer(entityView);
+
+ verify(entityViewService).saveEntityView(entityView, false);
+ assertThat(entityView.getCustomerId().isNullUid()).isTrue();
+ }
+
+}
diff --git a/application/src/test/java/org/thingsboard/server/service/integration/DefaultPlatformIntegrationServiceTest.java b/application/src/test/java/org/thingsboard/server/service/integration/DefaultPlatformIntegrationServiceTest.java
index 9e25bd44c9..83f55e632b 100644
--- a/application/src/test/java/org/thingsboard/server/service/integration/DefaultPlatformIntegrationServiceTest.java
+++ b/application/src/test/java/org/thingsboard/server/service/integration/DefaultPlatformIntegrationServiceTest.java
@@ -2,6 +2,8 @@
// SPDX-License-Identifier: BUSL-1.1
package org.thingsboard.server.service.integration;
+import com.google.gson.JsonObject;
+import com.google.gson.JsonParser;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
@@ -11,25 +13,44 @@ import org.mockito.junit.jupiter.MockitoExtension;
import org.mockito.junit.jupiter.MockitoSettings;
import org.mockito.quality.Strictness;
import org.springframework.test.util.ReflectionTestUtils;
+import org.thingsboard.integration.api.IntegrationCallback;
+import org.thingsboard.integration.api.converter.DedicatedConverterConfig;
+import org.thingsboard.integration.api.converter.DedicatedConverterUtil;
+import org.thingsboard.integration.api.converter.DedicatedUplinkData;
+import org.thingsboard.integration.api.converter.wrapper.ThingsStackConverterUnwrapper;
+import org.thingsboard.integration.api.data.ContentType;
+import org.thingsboard.integration.api.data.UplinkMetaData;
+import org.thingsboard.server.common.adaptor.JsonConverter;
import org.thingsboard.server.common.data.Customer;
import org.thingsboard.server.common.data.Device;
+import org.thingsboard.server.common.data.EntityType;
import org.thingsboard.server.common.data.asset.Asset;
import org.thingsboard.server.common.data.exception.ThingsboardErrorCode;
import org.thingsboard.server.common.data.id.AssetId;
import org.thingsboard.server.common.data.id.CustomerId;
import org.thingsboard.server.common.data.id.DeviceId;
+import org.thingsboard.server.common.data.id.DeviceProfileId;
import org.thingsboard.server.common.data.id.IntegrationId;
import org.thingsboard.server.common.data.id.TenantId;
import org.thingsboard.server.common.data.integration.AbstractIntegration;
+import org.thingsboard.server.common.data.kv.DataType;
+import org.thingsboard.server.common.data.kv.KvEntry;
+import org.thingsboard.server.common.data.msg.TbMsgType;
import org.thingsboard.server.common.data.relation.EntityRelation;
import org.thingsboard.server.common.msg.TbMsg;
+import org.thingsboard.server.common.msg.TbMsgMetaData;
import org.thingsboard.server.common.msg.queue.TbCallback;
import org.thingsboard.server.dao.asset.AssetService;
import org.thingsboard.server.dao.customer.CustomerService;
import org.thingsboard.server.dao.device.DeviceService;
import org.thingsboard.server.dao.relation.RelationService;
import org.thingsboard.server.exception.ThingsboardRuntimeException;
+import org.thingsboard.server.gen.integration.AssetUplinkDataProto;
+import org.thingsboard.server.gen.integration.DeviceUplinkDataProto;
import org.thingsboard.server.gen.transport.TransportProtos.DeviceActivityProto;
+import org.thingsboard.server.gen.transport.TransportProtos.KeyValueProto;
+import org.thingsboard.server.gen.transport.TransportProtos.KeyValueType;
+import org.thingsboard.server.gen.transport.TransportProtos.PostTelemetryMsg;
import org.thingsboard.server.gen.transport.TransportProtos.ToRuleEngineMsg;
import org.thingsboard.server.queue.TbQueueCallback;
import org.thingsboard.server.queue.TbQueueProducer;
@@ -38,15 +59,22 @@ import org.thingsboard.server.queue.common.TbRuleEngineProducerService;
import org.thingsboard.server.service.profile.DefaultTbAssetProfileCache;
import org.thingsboard.server.service.profile.DefaultTbDeviceProfileCache;
+import java.nio.charset.StandardCharsets;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
import java.util.Optional;
+import java.util.Set;
import java.util.UUID;
import java.util.concurrent.ExecutorService;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
+import static org.assertj.core.api.Assertions.tuple;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyLong;
import static org.mockito.ArgumentMatchers.eq;
+import static org.mockito.Mockito.atLeastOnce;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock;
@@ -484,4 +512,220 @@ public class DefaultPlatformIntegrationServiceTest {
verify(customerService).saveCustomer(any(Customer.class));
}
+ @Test
+ public void whenDeviceUplinkFromTypedConverter_thenStringIdentifiersStayStringsAfterRuleNodeParsing() throws Exception {
+ AbstractIntegration integration = mock(AbstractIntegration.class);
+ when(integration.getTenantId()).thenReturn(TENANT_ID);
+ when(integration.getId()).thenReturn(new IntegrationId(UUID.randomUUID()));
+ Device device = new Device();
+ device.setId(DEVICE_ID);
+ device.setTenantId(TENANT_ID);
+ device.setName("ttn-device");
+ device.setType("default");
+ device.setDeviceProfileId(new DeviceProfileId(UUID.randomUUID()));
+ when(deviceService.findDeviceByTenantIdAndName(TENANT_ID, device.getName())).thenReturn(device);
+ doAnswer(_ -> null).when(service).onActivity(any(), any(), anyLong());
+
+ DedicatedUplinkData uplink = parseThingsStackUplink();
+ DeviceUplinkDataProto data = DeviceUplinkDataProto.newBuilder()
+ .setDeviceName(device.getName())
+ .setDeviceType(device.getType())
+ .setPostTelemetryMsg(JsonConverter.convertToTelemetryProto(uplink.getTelemetryJson(), uplink.getTelemetryTypeCastDisabledKeys()))
+ .setPostAttributesMsg(JsonConverter.convertToAttributesProto(uplink.getAttributesJson(), uplink.getAttributesTypeCastDisabledKeys()))
+ .addAllTelemetryTypeCastDisabledKeys(uplink.getTelemetryTypeCastDisabledKeys())
+ .addAllAttributesTypeCastDisabledKeys(uplink.getAttributesTypeCastDisabledKeys())
+ .build();
+
+ service.processUplinkData(integration, data, mock(IntegrationCallback.class)).run();
+
+ assertThingsStackUplinkTypes(captureRuleEngineMsgs());
+ }
+
+ @Test
+ public void whenAssetUplinkFromTypedConverter_thenStringIdentifiersStayStringsAfterRuleNodeParsing() throws Exception {
+ AbstractIntegration integration = mock(AbstractIntegration.class);
+ when(integration.getTenantId()).thenReturn(TENANT_ID);
+ Asset asset = new Asset();
+ asset.setId(ASSET_ID);
+ asset.setTenantId(TENANT_ID);
+ asset.setName("ttn-asset");
+ asset.setType("default");
+ when(assetService.findAssetByTenantIdAndName(TENANT_ID, asset.getName())).thenReturn(asset);
+
+ DedicatedUplinkData uplink = parseThingsStackUplink();
+ AssetUplinkDataProto data = AssetUplinkDataProto.newBuilder()
+ .setAssetName(asset.getName())
+ .setAssetType(asset.getType())
+ .setPostTelemetryMsg(JsonConverter.convertToTelemetryProto(uplink.getTelemetryJson(), uplink.getTelemetryTypeCastDisabledKeys()))
+ .setPostAttributesMsg(JsonConverter.convertToAttributesProto(uplink.getAttributesJson(), uplink.getAttributesTypeCastDisabledKeys()))
+ .addAllTelemetryTypeCastDisabledKeys(uplink.getTelemetryTypeCastDisabledKeys())
+ .addAllAttributesTypeCastDisabledKeys(uplink.getAttributesTypeCastDisabledKeys())
+ .build();
+
+ service.processUplinkData(integration, data, mock(IntegrationCallback.class)).run();
+
+ assertThingsStackUplinkTypes(captureRuleEngineMsgs());
+ }
+
+ @Test
+ public void whenUplinkHasNoKeptStrings_thenTypeCastDisabledKeysMetadataIsNotAdded() {
+ AbstractIntegration integration = mock(AbstractIntegration.class);
+ when(integration.getTenantId()).thenReturn(TENANT_ID);
+ when(integration.getId()).thenReturn(new IntegrationId(UUID.randomUUID()));
+ Device device = new Device();
+ device.setId(DEVICE_ID);
+ device.setTenantId(TENANT_ID);
+ device.setName("http-device");
+ device.setType("default");
+ device.setDeviceProfileId(new DeviceProfileId(UUID.randomUUID()));
+ when(deviceService.findDeviceByTenantIdAndName(TENANT_ID, device.getName())).thenReturn(device);
+ doAnswer(_ -> null).when(service).onActivity(any(), any(), anyLong());
+
+ DeviceUplinkDataProto data = DeviceUplinkDataProto.newBuilder()
+ .setDeviceName(device.getName())
+ .setDeviceType(device.getType())
+ .setPostAttributesMsg(JsonConverter.convertToAttributesProto(JsonParser.parseString("{\"devAddr\": \"01020304\", \"model\": \"x1\"}")))
+ .build();
+
+ service.processUplinkData(integration, data, mock(IntegrationCallback.class)).run();
+
+ List msgs = captureRuleEngineMsgs();
+ assertThat(msgs).hasSize(1);
+ assertThat(msgs.get(0).getMetaData().getValue(TbMsgMetaData.TYPE_CAST_DISABLED_KEYS)).isNull();
+ }
+
+ @Test
+ public void whenDecoderSendsLongDecimal_thenItIsNotMarkedAndIsSavedAsNumber() throws Exception {
+ AbstractIntegration integration = mock(AbstractIntegration.class);
+ when(integration.getTenantId()).thenReturn(TENANT_ID);
+ when(integration.getId()).thenReturn(new IntegrationId(UUID.randomUUID()));
+ Device device = new Device();
+ device.setId(DEVICE_ID);
+ device.setTenantId(TENANT_ID);
+ device.setName("ttn-device");
+ device.setType("default");
+ device.setDeviceProfileId(new DeviceProfileId(UUID.randomUUID()));
+ when(deviceService.findDeviceByTenantIdAndName(TENANT_ID, device.getName())).thenReturn(device);
+ doAnswer(_ -> null).when(service).onActivity(any(), any(), anyLong());
+
+ DedicatedUplinkData uplink = parseThingsStackUplink();
+ PostTelemetryMsg telemetry = JsonConverter.convertToTelemetryProto(uplink.getTelemetryJson(), uplink.getTelemetryTypeCastDisabledKeys());
+ // The proto parser keeps a decimal with more than 16 fraction digits as a string.
+ assertThat(telemetry.getTsKvList(0).getKvList())
+ .filteredOn(kv -> kv.getKey().equals("pressure"))
+ .extracting(KeyValueProto::getType, KeyValueProto::getStringV)
+ .containsExactly(tuple(KeyValueType.STRING_V, "21.50000000000000000000"));
+ DeviceUplinkDataProto data = DeviceUplinkDataProto.newBuilder()
+ .setDeviceName(device.getName())
+ .setDeviceType(device.getType())
+ .setPostTelemetryMsg(telemetry)
+ .setPostAttributesMsg(JsonConverter.convertToAttributesProto(uplink.getAttributesJson(), uplink.getAttributesTypeCastDisabledKeys()))
+ .addAllTelemetryTypeCastDisabledKeys(uplink.getTelemetryTypeCastDisabledKeys())
+ .addAllAttributesTypeCastDisabledKeys(uplink.getAttributesTypeCastDisabledKeys())
+ .build();
+
+ service.processUplinkData(integration, data, mock(IntegrationCallback.class)).run();
+
+ List msgs = captureRuleEngineMsgs();
+ TbMsg telemetryMsg = msgs.stream().filter(msg -> msg.isTypeOf(TbMsgType.POST_TELEMETRY_REQUEST)).findFirst().orElseThrow();
+ TbMsg attributesMsg = msgs.stream().filter(msg -> msg.isTypeOf(TbMsgType.POST_ATTRIBUTES_REQUEST)).findFirst().orElseThrow();
+ assertThat(telemetryMsg.getTypeCastDisabledKeys()).containsExactlyInAnyOrder("devAddr");
+ assertThat(attributesMsg.getTypeCastDisabledKeys()).containsExactlyInAnyOrder("eui", "joinEui", "hardwareVersion", "firmwareVersion");
+ assertThingsStackUplinkTypes(msgs);
+ }
+
+ @Test
+ public void whenRemoteIntegrationSendsNoKeys_thenTypeCastDisabledKeysMetadataIsNotAdded() throws Exception {
+ AbstractIntegration integration = mock(AbstractIntegration.class);
+ when(integration.getTenantId()).thenReturn(TENANT_ID);
+ when(integration.getId()).thenReturn(new IntegrationId(UUID.randomUUID()));
+ Device device = new Device();
+ device.setId(DEVICE_ID);
+ device.setTenantId(TENANT_ID);
+ device.setName("old-remote-device");
+ device.setType("default");
+ device.setDeviceProfileId(new DeviceProfileId(UUID.randomUUID()));
+ when(deviceService.findDeviceByTenantIdAndName(TENANT_ID, device.getName())).thenReturn(device);
+ doAnswer(_ -> null).when(service).onActivity(any(), any(), anyLong());
+
+ // An older remote integration builds the same protos without the type-cast-disabled key fields.
+ DedicatedUplinkData uplink = parseThingsStackUplink();
+ DeviceUplinkDataProto data = DeviceUplinkDataProto.newBuilder()
+ .setDeviceName(device.getName())
+ .setDeviceType(device.getType())
+ .setPostTelemetryMsg(JsonConverter.convertToTelemetryProto(uplink.getTelemetryJson(), uplink.getTelemetryTypeCastDisabledKeys()))
+ .setPostAttributesMsg(JsonConverter.convertToAttributesProto(uplink.getAttributesJson(), uplink.getAttributesTypeCastDisabledKeys()))
+ .build();
+
+ service.processUplinkData(integration, data, mock(IntegrationCallback.class)).run();
+
+ List msgs = captureRuleEngineMsgs();
+ assertThat(msgs).hasSize(2);
+ assertThat(msgs).allSatisfy(msg -> assertThat(msg.getMetaData().getValue(TbMsgMetaData.TYPE_CAST_DISABLED_KEYS)).isNull());
+ }
+
+ // What the typed TTN converter produces: unwrapped event keys plus the decoder output
+ // {"telemetry": {"temperature": "22.5", "pressure": 21.50000000000000000000}}.
+ private static DedicatedUplinkData parseThingsStackUplink() throws Exception {
+ String payload = """
+ {
+ "end_device_ids": {
+ "device_id": "ttn-device",
+ "application_ids": {"application_id": "test-app"},
+ "dev_eui": "70B3D57ED0000001",
+ "join_eui": "0000000000000000",
+ "dev_addr": "01020304"
+ },
+ "received_at": "2026-11-17T09:46:05.447941836Z",
+ "uplink_message": {
+ "f_port": 1,
+ "f_cnt": 101,
+ "frm_payload": "AgI7AAMANwJxDGA=",
+ "decoded_payload": {"temperature": "22.5"},
+ "version_ids": {"brand_id": "acme", "model_id": "sensor", "hardware_version": "1.0", "firmware_version": "1.01", "band_id": "EU_863_870"},
+ "rx_metadata": [{"gateway_ids": {"gateway_id": "gw"}, "rssi": -22, "channel_rssi": -22, "snr": 11}],
+ "settings": {"data_rate": {"lora": {"bandwidth": 125000, "spreading_factor": 11}}, "frequency": "867700000"}
+ }
+ }
+ """;
+ ThingsStackConverterUnwrapper unwrapper = new ThingsStackConverterUnwrapper();
+ UplinkMetaData metadata = unwrapper.unwrap(payload.getBytes(StandardCharsets.UTF_8), new UplinkMetaData<>(ContentType.JSON, Map.of())).getSecond();
+
+ DedicatedConverterConfig config = new DedicatedConverterConfig();
+ config.setType(EntityType.DEVICE);
+ config.setName("Device $eui");
+ config.setAttributes(Set.of("eui", "joinEui", "hardwareVersion", "firmwareVersion"));
+ config.setTelemetry(Set.of("devAddr", "fCnt"));
+
+ JsonObject decoded = JsonParser.parseString("{\"telemetry\": {\"temperature\": \"22.5\", \"pressure\": 21.50000000000000000000}}").getAsJsonObject();
+ return DedicatedConverterUtil.parseUplinkData(config, decoded, metadata, unwrapper.getKeys());
+ }
+
+ private List captureRuleEngineMsgs() {
+ ArgumentCaptor msgCaptor = ArgumentCaptor.forClass(TbMsg.class);
+ verify(ruleEngineProducerService, atLeastOnce()).sendToRuleEngine(eq(integrationRuleEngineMsgProducer), eq(TENANT_ID), msgCaptor.capture(), any(TbQueueCallback.class));
+ return msgCaptor.getAllValues();
+ }
+
+ // Parses each message the way the save attributes / save time series nodes do.
+ private static void assertThingsStackUplinkTypes(List msgs) {
+ Map kvs = new HashMap<>();
+ for (TbMsg msg : msgs) {
+ if (msg.isTypeOf(TbMsgType.POST_ATTRIBUTES_REQUEST)) {
+ JsonConverter.attributesFromMsg(msg).forEach(kv -> kvs.put(kv.getKey(), kv));
+ } else {
+ JsonConverter.telemetryFromMsg(msg, 0L).values().forEach(list -> list.forEach(kv -> kvs.put(kv.getKey(), kv)));
+ }
+ }
+ assertThat(kvs.values()).extracting(KvEntry::getKey, KvEntry::getDataType, KvEntry::getValue).containsExactlyInAnyOrder(
+ tuple("eui", DataType.STRING, "70B3D57ED0000001"),
+ tuple("joinEui", DataType.STRING, "0000000000000000"),
+ tuple("hardwareVersion", DataType.STRING, "1.0"),
+ tuple("firmwareVersion", DataType.STRING, "1.01"),
+ tuple("devAddr", DataType.STRING, "01020304"),
+ tuple("fCnt", DataType.LONG, 101L),
+ tuple("temperature", DataType.DOUBLE, 22.5),
+ tuple("pressure", DataType.DOUBLE, 21.5));
+ }
+
}
diff --git a/application/src/test/java/org/thingsboard/server/service/integration/IntegrationActivityManagerTest.java b/application/src/test/java/org/thingsboard/server/service/integration/IntegrationActivityManagerTest.java
index e729826633..9deef281ac 100644
--- a/application/src/test/java/org/thingsboard/server/service/integration/IntegrationActivityManagerTest.java
+++ b/application/src/test/java/org/thingsboard/server/service/integration/IntegrationActivityManagerTest.java
@@ -697,7 +697,7 @@ public class IntegrationActivityManagerTest {
IntegrationCallback callbackMock = mock(IntegrationCallback.class);
doCallRealMethod().when(integrationServiceMock).processUplinkData(eq(integration), any(UUID.class), eq(uplinkDataProto), eq(callbackMock));
- doCallRealMethod().when(integrationServiceMock).process(any(), eq(uplinkDataProto.getPostTelemetryMsg()), any());
+ doCallRealMethod().when(integrationServiceMock).process(any(), eq(uplinkDataProto.getPostTelemetryMsg()), any(), any());
long expectedTime = 123L;
when(integrationServiceMock.getCurrentTimeMillis()).thenReturn(expectedTime);
@@ -734,7 +734,7 @@ public class IntegrationActivityManagerTest {
.setPostAttributesMsg(postAttributeMsg).build();
doCallRealMethod().when(integrationServiceMock).processUplinkData(eq(integration), any(UUID.class), eq(uplinkDataProto), isNull());
- doCallRealMethod().when(integrationServiceMock).process(any(), eq(uplinkDataProto.getPostAttributesMsg()), isNull());
+ doCallRealMethod().when(integrationServiceMock).process(any(), eq(uplinkDataProto.getPostAttributesMsg()), any(), isNull());
long expectedTime = 123L;
when(integrationServiceMock.getCurrentTimeMillis()).thenReturn(expectedTime);
diff --git a/application/src/test/java/org/thingsboard/server/service/integration/TypedConverterUplinkTypesTest.java b/application/src/test/java/org/thingsboard/server/service/integration/TypedConverterUplinkTypesTest.java
new file mode 100644
index 0000000000..acf6960825
--- /dev/null
+++ b/application/src/test/java/org/thingsboard/server/service/integration/TypedConverterUplinkTypesTest.java
@@ -0,0 +1,152 @@
+// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc.
+// SPDX-License-Identifier: BUSL-1.1
+package org.thingsboard.server.service.integration;
+
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.node.ObjectNode;
+import org.junit.After;
+import org.junit.Test;
+import org.springframework.test.context.TestPropertySource;
+import org.thingsboard.common.util.JacksonUtil;
+import org.thingsboard.server.common.data.Device;
+import org.thingsboard.server.common.data.converter.Converter;
+import org.thingsboard.server.common.data.converter.ConverterType;
+import org.thingsboard.server.common.data.debug.DebugSettings;
+import org.thingsboard.server.common.data.integration.IntegrationType;
+import org.thingsboard.server.dao.service.DaoSqlTest;
+
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.concurrent.TimeUnit;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.awaitility.Awaitility.await;
+import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
+
+/**
+ * An uplink through a typed (version 2) LoRaWAN converter and the default root rule chain:
+ * identifiers the network server sends as strings are saved as strings, decoder output is still cast.
+ */
+@TestPropertySource(properties = {
+ "js.evaluator=local",
+ "service.integrations.supported=ALL"
+})
+@DaoSqlTest
+public class TypedConverterUplinkTypesTest extends AbstractIntegrationTest {
+
+ private static final String EUI = "1000000000000001";
+ private static final String DEV_ADDR = "01020304";
+
+ private static final String DECODER = """
+ var data = JSON.parse(String.fromCharCode.apply(String, payload));
+ return {attributes: {}, telemetry: {temperature: data.temperature}};
+ """;
+
+ @After
+ public void afterTest() throws Exception {
+ if (integration != null) {
+ disableIntegration();
+ removeIntegration(integration);
+ }
+ }
+
+ @Override
+ protected JsonNode createIntegrationClientConfiguration() {
+ return JacksonUtil.newObjectNode();
+ }
+
+ @Test
+ public void givenChirpStackUplink_whenSaved_thenStringIdentifiersStayStrings() throws Exception {
+ loginTenantAdmin();
+ createTypedConverter();
+ createIntegration("Typed ChirpStack integration", IntegrationType.CHIRPSTACK);
+ enableIntegration();
+ waitUntilIntegrationStarted(tenantId, integration.getId());
+
+ doPost("/api/v1/integrations/chirpstack/{routingKey}", chirpStackUplink(), integration.getRoutingKey()).andExpect(status().isOk());
+
+ String deviceName = "Device " + EUI;
+ await().atMost(TIMEOUT, TimeUnit.SECONDS).until(() ->
+ doGet("/api/tenant/devices?deviceName={name}", deviceName).andReturn().getResponse().getStatus() == 200);
+ Device device = doGet("/api/tenant/devices?deviceName={name}", Device.class, deviceName);
+
+ String attributesUrl = "/api/plugins/telemetry/DEVICE/" + device.getUuidId() + "/values/attributes/CLIENT_SCOPE?keys=eui,devAddr";
+ Map attributes = new HashMap<>();
+ await().atMost(TIMEOUT, TimeUnit.SECONDS).until(() -> {
+ attributes.clear();
+ doGetAsync(attributesUrl, JsonNode.class).forEach(kv -> attributes.put(kv.get("key").asText(), kv.get("value")));
+ return attributes.size() == 2;
+ });
+ assertThat(attributes.get("eui").isTextual()).as("eui is a string: %s", attributes.get("eui")).isTrue();
+ assertThat(attributes.get("eui").asText()).isEqualTo(EUI);
+ assertThat(attributes.get("devAddr").isTextual()).as("devAddr is a string: %s", attributes.get("devAddr")).isTrue();
+ assertThat(attributes.get("devAddr").asText()).isEqualTo(DEV_ADDR);
+
+ String telemetryUrl = "/api/plugins/telemetry/DEVICE/" + device.getUuidId() + "/values/timeseries?keys=fCnt,temperature&useStrictDataTypes=true";
+ Map telemetry = new HashMap<>();
+ await().atMost(TIMEOUT, TimeUnit.SECONDS).until(() -> {
+ telemetry.clear();
+ JsonNode latest = doGetAsync(telemetryUrl, JsonNode.class);
+ for (String key : List.of("fCnt", "temperature")) {
+ if (latest.has(key) && !latest.get(key).isEmpty()) {
+ telemetry.put(key, latest.get(key).get(0).get("value"));
+ }
+ }
+ return telemetry.size() == 2;
+ });
+ assertThat(telemetry.get("fCnt").isIntegralNumber()).as("fCnt is a number: %s", telemetry.get("fCnt")).isTrue();
+ assertThat(telemetry.get("fCnt").asLong()).isEqualTo(10L);
+ // The decoder returns "22.5" as a string; the usual type cast still applies to it.
+ assertThat(telemetry.get("temperature").isNumber()).as("temperature is a number: %s", telemetry.get("temperature")).isTrue();
+ assertThat(telemetry.get("temperature").asDouble()).isEqualTo(22.5);
+ }
+
+ private void createTypedConverter() {
+ ObjectNode configuration = JacksonUtil.newObjectNode();
+ configuration.put("type", "DEVICE");
+ configuration.put("name", "Device $eui");
+ configuration.put("profile", "default");
+ configuration.set("attributes", JacksonUtil.toJsonNode("[\"eui\", \"devAddr\"]"));
+ configuration.set("telemetry", JacksonUtil.toJsonNode("[\"fCnt\"]"));
+ configuration.put("scriptLang", "JS");
+ configuration.put("decoder", DECODER);
+
+ Converter converter = new Converter();
+ converter.setTenantId(tenantId);
+ converter.setName("Typed ChirpStack converter");
+ converter.setType(ConverterType.UPLINK);
+ converter.setIntegrationType(IntegrationType.CHIRPSTACK);
+ converter.setConverterVersion(2);
+ converter.setConfiguration(configuration);
+ converter.setDebugSettings(DebugSettings.all());
+ uplinkConverter = doPost("/api/converter", converter, Converter.class);
+ }
+
+ private static JsonNode chirpStackUplink() {
+ return JacksonUtil.toJsonNode("""
+ {
+ "deduplicationId": "3ac7e3c4-4401-4b8d-9386-a5c902f9202d",
+ "time": "2026-11-17T09:34:15.775023242+00:00",
+ "deviceInfo": {
+ "tenantId": "52f14cd4-c6f1-4fbd-8f87-4025e1d49242",
+ "tenantName": "ChirpStack",
+ "applicationId": "17c82e96-be03-4f38-aef3-f83d48582d97",
+ "applicationName": "Test application",
+ "deviceProfileId": "14855bf7-d10d-4aee-b618-ebfcb64dc7ad",
+ "deviceProfileName": "default",
+ "deviceName": "Chirpstack",
+ "devEui": "%s"
+ },
+ "devAddr": "%s",
+ "dr": 1,
+ "fCnt": 10,
+ "fPort": 80,
+ "object": {"temperature": "22.5"},
+ "rxInfo": [{"uplinkId": 1, "rssi": -22, "snr": 10.5}],
+ "txInfo": {"frequency": 867100000, "modulation": {"lora": {"bandwidth": 125000, "spreadingFactor": 11, "codeRate": "CR_4_5"}}}
+ }
+ """.formatted(EUI, DEV_ADDR));
+ }
+
+}
diff --git a/application/src/test/java/org/thingsboard/server/service/integration/template/IntegrationPackageExportServiceTest.java b/application/src/test/java/org/thingsboard/server/service/integration/template/IntegrationPackageExportServiceTest.java
index 664733f426..6b6b61a381 100644
--- a/application/src/test/java/org/thingsboard/server/service/integration/template/IntegrationPackageExportServiceTest.java
+++ b/application/src/test/java/org/thingsboard/server/service/integration/template/IntegrationPackageExportServiceTest.java
@@ -816,6 +816,11 @@ class IntegrationPackageExportServiceTest {
assertThat(entry.get("secretSupport")).isEqualTo(true);
assertThat(entry.get("defaultValue")).isEqualTo("");
}
+
+ assertThat(result.formEntries()).filteredOn(e -> "tuyaAccessId".equals(e.get("key")))
+ .extracting(e -> e.get("label")).containsExactly("Access ID");
+ assertThat(result.formEntries()).filteredOn(e -> "tuyaAccessKey".equals(e.get("key")))
+ .extracting(e -> e.get("label")).containsExactly("Access Secret");
}
@Test
diff --git a/application/src/test/java/org/thingsboard/server/service/iot_hub/DefaultDevicePackageUpdateServiceTest.java b/application/src/test/java/org/thingsboard/server/service/iot_hub/DefaultDevicePackageServiceTest.java
similarity index 58%
rename from application/src/test/java/org/thingsboard/server/service/iot_hub/DefaultDevicePackageUpdateServiceTest.java
rename to application/src/test/java/org/thingsboard/server/service/iot_hub/DefaultDevicePackageServiceTest.java
index 38595a0c71..a53d9f8dff 100644
--- a/application/src/test/java/org/thingsboard/server/service/iot_hub/DefaultDevicePackageUpdateServiceTest.java
+++ b/application/src/test/java/org/thingsboard/server/service/iot_hub/DefaultDevicePackageServiceTest.java
@@ -8,6 +8,7 @@ import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.ArgumentCaptor;
+import org.mockito.InOrder;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
@@ -16,12 +17,17 @@ import org.mockito.quality.Strictness;
import org.springframework.test.util.ReflectionTestUtils;
import org.springframework.transaction.support.TransactionCallback;
import org.springframework.transaction.support.TransactionTemplate;
+import org.springframework.web.client.RestClientException;
import org.thingsboard.common.util.JacksonUtil;
+import org.thingsboard.server.common.data.Customer;
import org.thingsboard.server.common.data.Dashboard;
import org.thingsboard.server.common.data.Device;
import org.thingsboard.server.common.data.DeviceProfile;
import org.thingsboard.server.common.data.EntityType;
+import org.thingsboard.server.common.data.HasName;
+import org.thingsboard.server.common.data.User;
import org.thingsboard.server.common.data.AttributeScope;
+import org.thingsboard.server.common.data.audit.ActionType;
import org.thingsboard.server.common.data.converter.Converter;
import org.thingsboard.server.common.data.debug.DebugSettings;
import org.thingsboard.server.common.data.exception.EntityVersionMismatchException;
@@ -30,23 +36,30 @@ import org.thingsboard.server.common.data.id.CustomerId;
import org.thingsboard.server.common.data.id.DashboardId;
import org.thingsboard.server.common.data.id.DeviceId;
import org.thingsboard.server.common.data.id.DeviceProfileId;
+import org.thingsboard.server.common.data.id.EntityGroupId;
import org.thingsboard.server.common.data.id.EntityId;
import org.thingsboard.server.common.data.id.IntegrationId;
import org.thingsboard.server.common.data.id.IotHubInstalledItemId;
import org.thingsboard.server.common.data.id.TenantId;
+import org.thingsboard.server.common.data.id.UserId;
+import org.thingsboard.server.common.data.group.EntityGroup;
import org.thingsboard.server.common.data.integration.Integration;
import org.thingsboard.server.common.data.page.PageData;
+import org.thingsboard.server.common.data.security.DeviceCredentials;
import org.thingsboard.server.common.data.subscription.SubscriptionErrorCode;
+import org.thingsboard.server.common.data.subscription.SubscriptionEntry;
import org.thingsboard.server.common.data.subscription.SubscriptionException;
import org.thingsboard.rule.engine.api.AttributesSaveRequest;
import org.thingsboard.server.common.data.iot_hub.DeviceInstalledItemDescriptor;
import org.thingsboard.server.common.data.iot_hub.IotHubInstalledItem;
import org.thingsboard.server.dao.converter.ConverterService;
+import org.thingsboard.server.dao.customer.CustomerService;
import org.thingsboard.server.dao.dashboard.DashboardService;
import org.thingsboard.server.dao.device.DeviceCredentialsService;
import org.thingsboard.server.dao.device.DeviceProfileService;
import org.thingsboard.server.dao.device.DeviceService;
import org.thingsboard.server.dao.entity.EntityService;
+import org.thingsboard.server.dao.group.EntityGroupService;
import org.thingsboard.server.dao.integration.IntegrationService;
import org.thingsboard.server.dao.iot_hub.IotHubInstalledItemService;
import org.thingsboard.server.dao.subscription.PlatformFeature;
@@ -54,28 +67,35 @@ import org.thingsboard.server.dao.subscription.SubscriptionService;
import org.thingsboard.server.exception.DataValidationException;
import org.thingsboard.server.service.entitiy.TbLogEntityActionService;
import org.thingsboard.server.service.entitiy.integration.TbIntegrationService;
+import org.thingsboard.server.service.install.ProjectInfo;
import org.thingsboard.server.service.security.model.SecurityUser;
import org.thingsboard.server.service.telemetry.TelemetrySubscriptionService;
+import org.thingsboard.server.exception.EntitiesLimitExceededException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.UUID;
+import java.util.concurrent.ExecutionException;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.ArgumentMatchers.eq;
+import static org.mockito.ArgumentMatchers.nullable;
+import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.doThrow;
+import static org.mockito.Mockito.inOrder;
import static org.mockito.Mockito.never;
+import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoInteractions;
import static org.mockito.Mockito.when;
@ExtendWith(MockitoExtension.class)
@MockitoSettings(strictness = Strictness.LENIENT)
-class DefaultDevicePackageUpdateServiceTest {
+class DefaultDevicePackageServiceTest {
private final TenantId tenantId = TenantId.fromUUID(UUID.randomUUID());
private final SecurityUser user = mock(SecurityUser.class);
@@ -119,18 +139,30 @@ class DefaultDevicePackageUpdateServiceTest {
private TelemetrySubscriptionService telemetryService;
@Mock
private IotHubService iotHubService;
+ @Mock
+ private ProjectInfo projectInfo;
+ @Mock
+ private CustomerService customerService;
+ @Mock
+ private EntityGroupService entityGroupService;
@InjectMocks
- private DefaultDevicePackageUpdateService service;
+ private DefaultDevicePackageService service;
private IotHubInstalledItem installedItem;
// Set when the transaction callback threw, so the transaction would roll back
private final List rolledBack = new ArrayList<>();
+ private boolean inTransaction;
+ private final List savedInTransaction = new ArrayList<>();
+ // What must run after commit: the audit log, the Hub install report and the attributes, each marked if it ran inside
+ private final List afterCommitCalls = new ArrayList<>();
@BeforeEach
void setUp() {
ReflectionTestUtils.setField(service, "entityService", entityService);
ReflectionTestUtils.setField(service, "logEntityActionService", logEntityActionService);
+ ReflectionTestUtils.setField(service, "customerService", customerService);
+ ReflectionTestUtils.setField(service, "entityGroupService", entityGroupService);
when(user.getTenantId()).thenReturn(tenantId);
DeviceInstalledItemDescriptor descriptor = new DeviceInstalledItemDescriptor();
@@ -158,11 +190,14 @@ class DefaultDevicePackageUpdateServiceTest {
when(iotHubRestClient.getVersionInfo(versionId)).thenReturn(versionInfo);
when(transactionTemplate.execute(any())).thenAnswer(invocation -> {
+ inTransaction = true;
try {
return invocation.>getArgument(0).doInTransaction(null);
} catch (RuntimeException e) {
rolledBack.add(e);
throw e;
+ } finally {
+ inTransaction = false;
}
});
when(packageEntities.checksum(any(), any())).thenReturn("checksum");
@@ -184,7 +219,7 @@ class DefaultDevicePackageUpdateServiceTest {
when(dashboardService.findDashboardById(tenantId, dashboardId)).thenReturn(dashboard);
when(dashboardService.saveDashboard(any(Dashboard.class))).thenAnswer(i -> i.getArgument(0));
- DeviceUpdateResult result = service.apply(user, installedItem.getId(), request(
+ DevicePackageResult result = service.update(user, installedItem.getId(), request(
overwrite("AM308 profile", "DEVICE_PROFILE", profileId, 3L, JacksonUtil.newObjectNode().put("name", "milesight-iot-am308").put("description", "new")),
keep("AM308", "DEVICE", deviceId),
overwrite("Dashboard", "DASHBOARD", dashboardId, 7L, JacksonUtil.newObjectNode().put("title", "Template title"))));
@@ -218,10 +253,10 @@ class DefaultDevicePackageUpdateServiceTest {
dashboardState.set("entityOutput", JacksonUtil.newObjectNode().put("id", dashboardId.getId().toString()));
((DeviceInstalledItemDescriptor) installedItem.getDescriptor()).setInstallState(Map.of("Dashboard", dashboardState));
when(dashboardService.findDashboardById(tenantId, dashboardId)).thenReturn(dashboard(9L));
- DeviceUpdateRequest request = request(keep("Dashboard", "DASHBOARD", dashboardId));
+ DevicePackageRequest request = request(keep("Dashboard", "DASHBOARD", dashboardId));
request.setSelectedInstallMethod("INTEGRATION_CHIRPSTACK");
- DeviceUpdateResult result = service.apply(user, installedItem.getId(), request);
+ DevicePackageResult result = service.update(user, installedItem.getId(), request);
assertThat(result.isSuccess()).isTrue();
DeviceInstalledItemDescriptor descriptor = (DeviceInstalledItemDescriptor) installedItem.getDescriptor();
@@ -237,10 +272,10 @@ class DefaultDevicePackageUpdateServiceTest {
dashboardState.set("entityOutput", JacksonUtil.newObjectNode().put("id", dashboardId.getId().toString()));
((DeviceInstalledItemDescriptor) installedItem.getDescriptor()).setInstallState(Map.of("Dashboard", dashboardState));
when(dashboardService.findDashboardById(tenantId, dashboardId)).thenReturn(dashboard(9L));
- DeviceUpdateRequest.Step overview = keep("Overview", "DASHBOARD", dashboardId);
+ DevicePackageRequest.Step overview = keep("Overview", "DASHBOARD", dashboardId);
overview.setId("main-dashboard");
- DeviceUpdateResult result = service.apply(user, installedItem.getId(), request(overview));
+ DevicePackageResult result = service.update(user, installedItem.getId(), request(overview));
assertThat(result.isSuccess()).isTrue();
DeviceInstalledItemDescriptor descriptor = (DeviceInstalledItemDescriptor) installedItem.getDescriptor();
@@ -256,7 +291,7 @@ class DefaultDevicePackageUpdateServiceTest {
((DeviceInstalledItemDescriptor) installedItem.getDescriptor()).setInstallState(Map.of("Dashboard", dashboardState));
when(dashboardService.findDashboardById(tenantId, dashboardId)).thenReturn(dashboard(9L));
- DeviceUpdateResult result = service.apply(user, installedItem.getId(), request(keep("Dashboard", "DASHBOARD", dashboardId)));
+ DevicePackageResult result = service.update(user, installedItem.getId(), request(keep("Dashboard", "DASHBOARD", dashboardId)));
assertThat(result.isSuccess()).isTrue();
DeviceInstalledItemDescriptor descriptor = (DeviceInstalledItemDescriptor) installedItem.getDescriptor();
@@ -266,10 +301,10 @@ class DefaultDevicePackageUpdateServiceTest {
@Test
void useExistingOfAPackageEntity_staysThePackages() {
when(dashboardService.findDashboardById(tenantId, dashboardId)).thenReturn(dashboard(9L));
- DeviceUpdateRequest.Step step = keep("Overview", "DASHBOARD", dashboardId);
+ DevicePackageRequest.Step step = keep("Overview", "DASHBOARD", dashboardId);
step.setResolution("use-existing");
- DeviceUpdateResult result = service.apply(user, installedItem.getId(), request(step));
+ DevicePackageResult result = service.update(user, installedItem.getId(), request(step));
assertThat(result.isSuccess()).isTrue();
DeviceInstalledItemDescriptor descriptor = (DeviceInstalledItemDescriptor) installedItem.getDescriptor();
@@ -282,10 +317,10 @@ class DefaultDevicePackageUpdateServiceTest {
// At install the user picked their own dashboard: the install adds it to createdEntityIds too
((DeviceInstalledItemDescriptor) installedItem.getDescriptor()).setInstallState(Map.of("Dashboard", stateOf(dashboardId, "use-existing")));
when(dashboardService.findDashboardById(tenantId, dashboardId)).thenReturn(dashboard(9L));
- DeviceUpdateRequest.Step step = keep("Dashboard", "DASHBOARD", dashboardId);
+ DevicePackageRequest.Step step = keep("Dashboard", "DASHBOARD", dashboardId);
step.setResolution("use-existing");
- DeviceUpdateResult result = service.apply(user, installedItem.getId(), request(step));
+ DevicePackageResult result = service.update(user, installedItem.getId(), request(step));
assertThat(result.isSuccess()).isTrue();
DeviceInstalledItemDescriptor descriptor = (DeviceInstalledItemDescriptor) installedItem.getDescriptor();
@@ -295,9 +330,9 @@ class DefaultDevicePackageUpdateServiceTest {
@Test
void overwritingAnEntityUsedAtInstall_needsAConfirmation() {
((DeviceInstalledItemDescriptor) installedItem.getDescriptor()).setInstallState(Map.of("Dashboard", stateOf(dashboardId, "use-existing")));
- DeviceUpdateRequest.Step step = overwrite("Dashboard", "DASHBOARD", dashboardId, 9L, JacksonUtil.newObjectNode().put("title", "Dashboard"));
+ DevicePackageRequest.Step step = overwrite("Dashboard", "DASHBOARD", dashboardId, 9L, JacksonUtil.newObjectNode().put("title", "Dashboard"));
- DeviceUpdateResult result = service.apply(user, installedItem.getId(), request(step));
+ DevicePackageResult result = service.update(user, installedItem.getId(), request(step));
assertThat(result.isSuccess()).isFalse();
verify(installedItemService, never()).save(any(), any());
@@ -308,7 +343,7 @@ class DefaultDevicePackageUpdateServiceTest {
Dashboard shared = dashboard(9L);
DevicePackageEntities.Snapshot snapshot = new DevicePackageEntities.Snapshot(shared, null);
when(packageEntities.load(tenantId, dashboardId)).thenReturn(snapshot);
- when(iotHubService.findKeptEntities(tenantId, installedItem.getId())).thenReturn(new InstalledItemKeptEntities(List.of(), 0, 0));
+ when(iotHubService.findKeptEntities(tenantId, installedItem.getId())).thenReturn(new InstalledItemKeptEntities(List.of(), 0, 0, List.of()));
// This package recorded the dashboard as it left it; the other one overwrote it since and recorded the new one
ObjectNode own = stateOf(dashboardId, "created").put("checksum", "as-this-package-left-it");
((DeviceInstalledItemDescriptor) installedItem.getDescriptor()).setInstallState(Map.of("Dashboard", own));
@@ -327,10 +362,10 @@ class DefaultDevicePackageUpdateServiceTest {
// v2 dropped the dashboard step: the install state no longer has it, createdEntityIds does
((DeviceInstalledItemDescriptor) installedItem.getDescriptor()).setInstallState(Map.of());
when(dashboardService.findDashboardById(tenantId, dashboardId)).thenReturn(dashboard(9L));
- DeviceUpdateRequest.Step step = keep("Dashboard", "DASHBOARD", dashboardId);
+ DevicePackageRequest.Step step = keep("Dashboard", "DASHBOARD", dashboardId);
step.setResolution("use-existing");
- DeviceUpdateResult result = service.apply(user, installedItem.getId(), request(step));
+ DevicePackageResult result = service.update(user, installedItem.getId(), request(step));
assertThat(result.isSuccess()).isTrue();
DeviceInstalledItemDescriptor descriptor = (DeviceInstalledItemDescriptor) installedItem.getDescriptor();
@@ -343,9 +378,9 @@ class DefaultDevicePackageUpdateServiceTest {
DeviceInstalledItemDescriptor installed = (DeviceInstalledItemDescriptor) installedItem.getDescriptor();
installed.setUsedExistingEntityIds(List.of(dashboardId));
installed.setInstallState(Map.of());
- DeviceUpdateRequest.Step step = overwrite("Dashboard", "DASHBOARD", dashboardId, 9L, JacksonUtil.newObjectNode().put("title", "Dashboard"));
+ DevicePackageRequest.Step step = overwrite("Dashboard", "DASHBOARD", dashboardId, 9L, JacksonUtil.newObjectNode().put("title", "Dashboard"));
- DeviceUpdateResult result = service.apply(user, installedItem.getId(), request(step));
+ DevicePackageResult result = service.update(user, installedItem.getId(), request(step));
assertThat(result.isSuccess()).isFalse();
verify(installedItemService, never()).save(any(), any());
@@ -358,7 +393,7 @@ class DefaultDevicePackageUpdateServiceTest {
when(dashboardService.findDashboardById(tenantId, dashboardId)).thenReturn(dashboard(9L));
when(entityService.fetchEntity(any(), any())).thenReturn(Optional.of(dashboard(9L)));
- DeviceUpdateResult result = service.apply(user, installedItem.getId(), request(keep("AM308", "DEVICE", deviceId)));
+ DevicePackageResult result = service.update(user, installedItem.getId(), request(keep("AM308", "DEVICE", deviceId)));
assertThat(result.isSuccess()).isTrue();
assertThat(((DeviceInstalledItemDescriptor) installedItem.getDescriptor()).getUsedExistingEntityIds()).containsExactly(dashboardId);
@@ -377,13 +412,13 @@ class DefaultDevicePackageUpdateServiceTest {
current.setConfiguration(configuration);
when(integrationService.findIntegrationById(tenantId, integrationId)).thenReturn(current);
when(integrationService.saveIntegration(any())).thenAnswer(i -> i.getArgument(0));
- DeviceUpdateRequest.Step step = keep("TTN", "INTEGRATION", integrationId);
+ DevicePackageRequest.Step step = keep("TTN", "INTEGRATION", integrationId);
step.setResolution("use-existing");
ObjectNode entries = JacksonUtil.newObjectNode().put("profile.lansitec-badge", "Badge");
entries.putNull("profile.milesight-iot-am308");
step.setMetadata(entries);
- DeviceUpdateResult result = service.apply(user, installedItem.getId(), request(step));
+ DevicePackageResult result = service.update(user, installedItem.getId(), request(step));
assertThat(result.isSuccess()).isTrue();
ArgumentCaptor saved = ArgumentCaptor.forClass(Integration.class);
@@ -411,7 +446,7 @@ class DefaultDevicePackageUpdateServiceTest {
integration.setId(integrationId);
when(entityService.fetchEntity(tenantId, integrationId)).thenReturn(Optional.of(integration));
- DeviceUpdateResult result = service.apply(user, installedItem.getId(), request(keep("AM308", "DEVICE", deviceId)));
+ DevicePackageResult result = service.update(user, installedItem.getId(), request(keep("AM308", "DEVICE", deviceId)));
assertThat(result.isSuccess()).isTrue();
DeviceInstalledItemDescriptor descriptor = (DeviceInstalledItemDescriptor) installedItem.getDescriptor();
@@ -438,11 +473,11 @@ class DefaultDevicePackageUpdateServiceTest {
current.setConfiguration(configuration);
when(integrationService.findIntegrationById(tenantId, tenantsIntegrationId)).thenReturn(current);
when(integrationService.saveIntegration(any())).thenAnswer(i -> i.getArgument(0));
- DeviceUpdateRequest.Step step = keep("TTN", "INTEGRATION", tenantsIntegrationId);
+ DevicePackageRequest.Step step = keep("TTN", "INTEGRATION", tenantsIntegrationId);
step.setResolution("use-existing");
step.setMetadata(JacksonUtil.newObjectNode().put("profile.milesight-iot-am308", "AM308"));
- DeviceUpdateResult result = service.apply(user, installedItem.getId(), request(step));
+ DevicePackageResult result = service.update(user, installedItem.getId(), request(step));
assertThat(result.isSuccess()).isTrue();
DeviceInstalledItemDescriptor descriptor = (DeviceInstalledItemDescriptor) installedItem.getDescriptor();
@@ -465,10 +500,10 @@ class DefaultDevicePackageUpdateServiceTest {
configuration.set("metadata", JacksonUtil.newObjectNode().put("profile.lansitec-badge", "Badge"));
current.setConfiguration(configuration);
when(integrationService.findIntegrationById(tenantId, integrationId)).thenReturn(current);
- DeviceUpdateRequest.Step step = keep("TTN", "INTEGRATION", integrationId);
+ DevicePackageRequest.Step step = keep("TTN", "INTEGRATION", integrationId);
step.setMetadata(JacksonUtil.newObjectNode().put("profile.lansitec-badge", "Badge"));
- DeviceUpdateResult result = service.apply(user, installedItem.getId(), request(step));
+ DevicePackageResult result = service.update(user, installedItem.getId(), request(step));
assertThat(result.isSuccess()).isTrue();
verify(integrationService, never()).saveIntegration(any());
@@ -476,12 +511,12 @@ class DefaultDevicePackageUpdateServiceTest {
@Test
void twoStepsWithOneKey_areRejected() {
- DeviceUpdateRequest.Step first = keep("Overview", "DASHBOARD", dashboardId);
+ DevicePackageRequest.Step first = keep("Overview", "DASHBOARD", dashboardId);
first.setId("main-dashboard");
- DeviceUpdateRequest.Step second = keep("Details", "DASHBOARD", dashboardId);
+ DevicePackageRequest.Step second = keep("Details", "DASHBOARD", dashboardId);
second.setId("main-dashboard");
- DeviceUpdateResult result = service.apply(user, installedItem.getId(), request(first, second));
+ DevicePackageResult result = service.update(user, installedItem.getId(), request(first, second));
assertThat(result.isSuccess()).isFalse();
verify(installedItemService, never()).save(any(), any());
@@ -489,25 +524,25 @@ class DefaultDevicePackageUpdateServiceTest {
@Test
void twoStepsOfOneTypeAndName_areRejected() {
- DeviceUpdateResult result = service.apply(user, installedItem.getId(), request(
+ DevicePackageResult result = service.update(user, installedItem.getId(), request(
keep("Dashboard", "DASHBOARD", dashboardId), keep("Dashboard", "DASHBOARD", dashboardId)));
assertThat(result.isSuccess()).isFalse();
- assertThat(result.getErrorMessage()).isEqualTo("Duplicate update step: DASHBOARD:Dashboard");
+ assertThat(result.getErrorMessage()).isEqualTo("Duplicate step: DASHBOARD:Dashboard");
verify(transactionTemplate, never()).execute(any());
}
@Test
void stepWithTheKeyOfAForm_isRejected() {
- DeviceUpdateRequest.Step step = keep("Dashboard", "DASHBOARD", dashboardId);
+ DevicePackageRequest.Step step = keep("Dashboard", "DASHBOARD", dashboardId);
step.setId("Settings");
- DeviceUpdateRequest request = request(step);
+ DevicePackageRequest request = request(step);
request.setInstallState(Map.of("Settings", JacksonUtil.newObjectNode().set("formValues", JacksonUtil.newObjectNode().put("interval", 10))));
- DeviceUpdateResult result = service.apply(user, installedItem.getId(), request);
+ DevicePackageResult result = service.update(user, installedItem.getId(), request);
assertThat(result.isSuccess()).isFalse();
- assertThat(result.getErrorMessage()).isEqualTo("Duplicate update step: Settings");
+ assertThat(result.getErrorMessage()).isEqualTo("Duplicate step: Settings");
verify(transactionTemplate, never()).execute(any());
}
@@ -532,14 +567,14 @@ class DefaultDevicePackageUpdateServiceTest {
legacy.set("metadata", JacksonUtil.newObjectNode().put("profile.milesight-iot-am308", "AM308"));
installed.setInstallState(Map.of("${integrationName}", legacy, "${profileName}", stateOf(profileId, "created"),
"Configuration", JacksonUtil.newObjectNode().set("formValues", JacksonUtil.newObjectNode().put("integrationName", "TTN my-app"))));
- DeviceUpdateRequest.Step uplink = keep("${integrationName}", "UPLINK_CONVERTER", converterId);
+ DevicePackageRequest.Step uplink = keep("${integrationName}", "UPLINK_CONVERTER", converterId);
uplink.setDefaultConverter(true);
- DeviceUpdateRequest.Step ttn = keep("${integrationName}", "INTEGRATION", integrationId);
+ DevicePackageRequest.Step ttn = keep("${integrationName}", "INTEGRATION", integrationId);
ttn.setMetadata(JacksonUtil.newObjectNode().put("profile.milesight-iot-am308", "AM308"));
- DeviceUpdateRequest request = request(uplink, ttn);
+ DevicePackageRequest request = request(uplink, ttn);
request.setInstallState(Map.of("Configuration", installed.getInstallState().get("Configuration")));
- DeviceUpdateResult result = service.apply(user, installedItem.getId(), request);
+ DevicePackageResult result = service.update(user, installedItem.getId(), request);
assertThat(result.isSuccess()).isTrue();
Map state = ((DeviceInstalledItemDescriptor) installedItem.getDescriptor()).getInstallState();
@@ -563,7 +598,7 @@ class DefaultDevicePackageUpdateServiceTest {
when(dashboardService.findDashboardById(tenantId, dashboardId)).thenReturn(dashboard(7L));
when(dashboardService.saveDashboard(any(Dashboard.class))).thenThrow(new DataValidationException("Dashboards limit reached"));
- DeviceUpdateResult result = service.apply(user, installedItem.getId(), request(
+ DevicePackageResult result = service.update(user, installedItem.getId(), request(
overwrite("AM308 profile", "DEVICE_PROFILE", profileId, 3L, JacksonUtil.newObjectNode().put("name", "p")),
overwrite("Dashboard", "DASHBOARD", dashboardId, 7L, JacksonUtil.newObjectNode().put("title", "d"))));
@@ -580,12 +615,12 @@ class DefaultDevicePackageUpdateServiceTest {
void entityChangedSinceTheCheck_isAVersionConflict() {
when(dashboardService.findDashboardById(tenantId, dashboardId)).thenReturn(dashboard(8L));
- DeviceUpdateResult result = service.apply(user, installedItem.getId(), request(
+ DevicePackageResult result = service.update(user, installedItem.getId(), request(
overwrite("Dashboard", "DASHBOARD", dashboardId, 7L, JacksonUtil.newObjectNode().put("title", "d"))));
assertThat(result.isSuccess()).isFalse();
assertThat(result.getFailedStep()).isEqualTo("DASHBOARD:Dashboard");
- assertThat(result.getErrorMessage()).contains("Check the update again");
+ assertThat(result.getErrorMessage()).contains("Check the package again");
verify(dashboardService, never()).saveDashboard(any(Dashboard.class));
}
@@ -608,7 +643,7 @@ class DefaultDevicePackageUpdateServiceTest {
ObjectNode integration = JacksonUtil.newObjectNode().put("name", "Template name").put("type", "TTN").put("edgeTemplate", true);
integration.set("defaultConverterId", JacksonUtil.newObjectNode().put("entityType", "CONVERTER").put("id", "${uplinkConverter.id}"));
- DeviceUpdateResult result = service.apply(user, installedItem.getId(), request(
+ DevicePackageResult result = service.update(user, installedItem.getId(), request(
create("Uplink", "UPLINK_CONVERTER", JacksonUtil.newObjectNode().put("name", "Uplink for TTN")),
overwrite("TTN", "INTEGRATION", integrationId, 2L, integration)));
@@ -640,12 +675,12 @@ class DefaultDevicePackageUpdateServiceTest {
IotHubInstalledItem taker = otherPackage(Map.of("Uplink", usedExisting));
when(installedItemService.findByTenantId(any(), any(), any(), any()))
.thenReturn(new PageData<>(List.of(installedItem, creator, taker), 1, 3, false));
- DeviceUpdateRequest.Step step = overwrite("Uplink", "UPLINK_CONVERTER", converterId, 4L,
+ DevicePackageRequest.Step step = overwrite("Uplink", "UPLINK_CONVERTER", converterId, 4L,
JacksonUtil.newObjectNode().put("name", "Uplink").set("configuration", JacksonUtil.newObjectNode().put("tbelDecoder", "return {};")));
step.setConfirmed(true);
step.setDefaultConverter(true);
- DeviceUpdateResult result = service.apply(user, installedItem.getId(), request(step));
+ DevicePackageResult result = service.update(user, installedItem.getId(), request(step));
assertThat(result.isSuccess()).isTrue();
JsonNode state = ((DeviceInstalledItemDescriptor) installedItem.getDescriptor()).getInstallState().get("UPLINK_CONVERTER:Uplink");
@@ -672,14 +707,14 @@ class DefaultDevicePackageUpdateServiceTest {
ObjectNode versionInfo = JacksonUtil.newObjectNode().put("itemId", itemId.toString()).put("name", "AM308").put("version", "1.0.0");
when(iotHubRestClient.getVersionInfo(installedVersionId.toString())).thenReturn(versionInfo);
// ThingsBoard's default converter changed: only the converter step is sent
- DeviceUpdateRequest.Step step = overwrite("Uplink data converter", "UPLINK_CONVERTER", converterId, 4L,
+ DevicePackageRequest.Step step = overwrite("Uplink data converter", "UPLINK_CONVERTER", converterId, 4L,
JacksonUtil.newObjectNode().put("name", "Uplink").set("configuration", JacksonUtil.newObjectNode().put("tbelDecoder", "return {};")));
step.setId("uplink");
step.setDefaultConverter(true);
- DeviceUpdateRequest request = request(step);
+ DevicePackageRequest request = request(step);
request.setVersionId(installedVersionId.toString());
- DeviceUpdateResult result = service.apply(user, installedItem.getId(), request);
+ DevicePackageResult result = service.update(user, installedItem.getId(), request);
assertThat(result.isSuccess()).isTrue();
Map state = ((DeviceInstalledItemDescriptor) installedItem.getDescriptor()).getInstallState();
@@ -697,7 +732,7 @@ class DefaultDevicePackageUpdateServiceTest {
void updateToAnotherVersion_dropsTheInstallStateOfTheStepsItLeavesOut() {
when(dashboardService.findDashboardById(tenantId, dashboardId)).thenReturn(dashboard(9L));
- DeviceUpdateResult result = service.apply(user, installedItem.getId(), request(keep("Dashboard", "DASHBOARD", dashboardId)));
+ DevicePackageResult result = service.update(user, installedItem.getId(), request(keep("Dashboard", "DASHBOARD", dashboardId)));
assertThat(result.isSuccess()).isTrue();
assertThat(((DeviceInstalledItemDescriptor) installedItem.getDescriptor()).getInstallState()).containsOnlyKeys("DASHBOARD:Dashboard");
@@ -707,7 +742,7 @@ class DefaultDevicePackageUpdateServiceTest {
void overwritingAnEntityOfAnotherPackage_needsAConfirmation() {
DashboardId foreign = new DashboardId(UUID.randomUUID());
- DeviceUpdateResult result = service.apply(user, installedItem.getId(), request(
+ DevicePackageResult result = service.update(user, installedItem.getId(), request(
overwrite("Dashboard", "DASHBOARD", foreign, 1L, JacksonUtil.newObjectNode().put("title", "d"))));
assertThat(result.isSuccess()).isFalse();
@@ -716,7 +751,7 @@ class DefaultDevicePackageUpdateServiceTest {
@Test
void theDeviceIsNeverOverwritten() {
- DeviceUpdateResult result = service.apply(user, installedItem.getId(), request(
+ DevicePackageResult result = service.update(user, installedItem.getId(), request(
overwrite("AM308", "DEVICE", deviceId, 1L, JacksonUtil.newObjectNode().put("name", "d"))));
assertThat(result.isSuccess()).isFalse();
@@ -729,7 +764,7 @@ class DefaultDevicePackageUpdateServiceTest {
ObjectNode other = JacksonUtil.newObjectNode().put("itemId", UUID.randomUUID().toString());
when(iotHubRestClient.getVersionInfo(versionId)).thenReturn(other);
- DeviceUpdateResult result = service.apply(user, installedItem.getId(), request(keep("AM308", "DEVICE", deviceId)));
+ DevicePackageResult result = service.update(user, installedItem.getId(), request(keep("AM308", "DEVICE", deviceId)));
assertThat(result.isSuccess()).isFalse();
verify(transactionTemplate, never()).execute(any());
@@ -743,7 +778,7 @@ class DefaultDevicePackageUpdateServiceTest {
updated.setItemVersionId(UUID.fromString(versionId));
when(installedItemService.findByIdForUpdate(tenantId, installedItem.getId())).thenReturn(updated);
- DeviceUpdateResult result = service.apply(user, installedItem.getId(), request(
+ DevicePackageResult result = service.update(user, installedItem.getId(), request(
create("Uplink", "UPLINK_CONVERTER", JacksonUtil.newObjectNode().put("name", "Uplink for TTN"))));
assertThat(result.isSuccess()).isFalse();
@@ -754,10 +789,10 @@ class DefaultDevicePackageUpdateServiceTest {
@Test
void planOfAnotherInstalledVersion_isRejected() {
- DeviceUpdateRequest request = request(keep("AM308", "DEVICE", deviceId));
+ DevicePackageRequest request = request(keep("AM308", "DEVICE", deviceId));
request.setFromVersionId(UUID.randomUUID());
- DeviceUpdateResult result = service.apply(user, installedItem.getId(), request);
+ DevicePackageResult result = service.update(user, installedItem.getId(), request);
assertThat(result.isSuccess()).isFalse();
verify(installedItemService, never()).save(any(), any());
@@ -768,7 +803,7 @@ class DefaultDevicePackageUpdateServiceTest {
doThrow(new SubscriptionException("Integrations feature is disabled!", SubscriptionErrorCode.FEATURE_DISABLED))
.when(subscriptionService).checkFeatureAllowed(tenantId, PlatformFeature.INTEGRATIONS);
- DeviceUpdateResult result = service.apply(user, installedItem.getId(), request(
+ DevicePackageResult result = service.update(user, installedItem.getId(), request(
create("Uplink", "UPLINK_CONVERTER", JacksonUtil.newObjectNode().put("name", "Uplink for TTN"))));
assertThat(result.isSuccess()).isFalse();
@@ -780,10 +815,10 @@ class DefaultDevicePackageUpdateServiceTest {
void attributesOfAnOverwrittenEntity_areSavedAfterCommit() {
when(dashboardService.findDashboardById(tenantId, dashboardId)).thenReturn(dashboard(7L));
when(dashboardService.saveDashboard(any(Dashboard.class))).thenAnswer(i -> i.getArgument(0));
- DeviceUpdateRequest.Step step = overwrite("Dashboard", "DASHBOARD", dashboardId, 7L, JacksonUtil.newObjectNode().put("title", "d"));
+ DevicePackageRequest.Step step = overwrite("Dashboard", "DASHBOARD", dashboardId, 7L, JacksonUtil.newObjectNode().put("title", "d"));
step.setServerAttributes(JacksonUtil.newObjectNode().put("deviceId", "${device.id}"));
- DeviceUpdateResult result = service.apply(user, installedItem.getId(), request(keep("AM308", "DEVICE", deviceId), step));
+ DevicePackageResult result = service.update(user, installedItem.getId(), request(keep("AM308", "DEVICE", deviceId), step));
assertThat(result.isSuccess()).isTrue();
ArgumentCaptor saved = ArgumentCaptor.forClass(AttributesSaveRequest.class);
@@ -829,12 +864,38 @@ class DefaultDevicePackageUpdateServiceTest {
@Test
void userMessage_showsValidationMessagesAndHidesInternalOnes() {
- assertThat(DefaultDevicePackageUpdateService.userMessage(new DataValidationException("Rule chains limit reached")))
+ assertThat(DefaultDevicePackageService.userMessage(new DataValidationException("Rule chains limit reached")))
.isEqualTo("Rule chains limit reached");
- assertThat(DefaultDevicePackageUpdateService.userMessage(new EntityVersionMismatchException(EntityType.DASHBOARD, null)))
- .contains("Check the update again");
- assertThat(DefaultDevicePackageUpdateService.userMessage(new IllegalStateException("could not execute statement; SQL [n/a]")))
- .isEqualTo("Failed to update the device package");
+ assertThat(DefaultDevicePackageService.userMessage(new EntityVersionMismatchException(EntityType.DASHBOARD, null)))
+ .contains("Check the package again");
+ assertThat(DefaultDevicePackageService.userMessage(new IllegalStateException("could not execute statement; SQL [n/a]")))
+ .isEqualTo("Failed to save the device package");
+ }
+
+ @Test
+ void limitOf_givesTheLimitResponseBody_whenAStepHitsASubscriptionLimit() {
+ JsonNode limit = DefaultDevicePackageService.limitOf(new RuntimeException("step failed", new SubscriptionException(
+ "Maximum allowed devices limit reached!", SubscriptionErrorCode.LIMIT_REACHED, SubscriptionEntry.DEVICE_COUNT, 5)));
+
+ assertThat(limit.get("errorCode").asInt()).isEqualTo(40);
+ assertThat(limit.get("message").asText()).isEqualTo("Maximum allowed devices limit reached!");
+ assertThat(limit.get("subscriptionErrorCode").asText()).isEqualTo("LIMIT_REACHED");
+ assertThat(limit.get("subscriptionEntry").asText()).isEqualTo("DEVICE_COUNT");
+ assertThat(limit.at("/subscriptionValue/value").asLong()).isEqualTo(5);
+ }
+
+ @Test
+ void limitOf_givesTheLimitResponseBody_whenAStepHitsATenantProfileLimit() {
+ JsonNode limit = DefaultDevicePackageService.limitOf(new EntitiesLimitExceededException(TenantId.SYS_TENANT_ID, EntityType.DASHBOARD, 10));
+
+ assertThat(limit.get("errorCode").asInt()).isEqualTo(41);
+ assertThat(limit.get("entityType").asText()).isEqualTo("DASHBOARD");
+ assertThat(limit.get("limit").asLong()).isEqualTo(10);
+ }
+
+ @Test
+ void limitOf_givesNothing_whenTheFailureIsNotALimit() {
+ assertThat(DefaultDevicePackageService.limitOf(new DataValidationException("Device with such name already exists!"))).isNull();
}
@Test
@@ -842,12 +903,431 @@ class DefaultDevicePackageUpdateServiceTest {
ObjectNode device = JacksonUtil.newObjectNode().put("id", "123");
ObjectNode node = JacksonUtil.newObjectNode().put("a", "${device.id}").put("b", "x ${device.id} ${gateway.id}");
- ObjectNode resolved = (ObjectNode) DefaultDevicePackageUpdateService.resolvePlaceholders(node, Map.of("device", device));
+ ObjectNode resolved = (ObjectNode) DefaultDevicePackageService.resolvePlaceholders(node, Map.of("device", device));
assertThat(resolved.get("a").asText()).isEqualTo("123");
assertThat(resolved.get("b").asText()).isEqualTo("x 123 ${gateway.id}");
}
+ @Test
+ void installSavesTheEntitiesAndTheInstalledItemInOneTransaction() {
+ mockInstall();
+ DevicePackageRequest.Step integrationStep = keep("TTN", "INTEGRATION", integrationId);
+ integrationStep.setResolution("use-existing");
+
+ DevicePackageResult result = service.install(user, request(
+ create("AM308 profile", "DEVICE_PROFILE", JacksonUtil.newObjectNode().put("name", "milesight-iot-am308")),
+ integrationStep,
+ create("Dashboard", "DASHBOARD", JacksonUtil.newObjectNode().put("title", "AM308 dashboard"))));
+
+ assertThat(result.isSuccess()).isTrue();
+ verify(transactionTemplate).execute(any());
+ assertThat(savedInTransaction).containsExactly("DEVICE_PROFILE", "DASHBOARD", "INSTALLED_ITEM");
+ ArgumentCaptor saved = ArgumentCaptor.forClass(IotHubInstalledItem.class);
+ verify(installedItemService).save(eq(tenantId), saved.capture());
+ IotHubInstalledItem item = saved.getValue();
+ assertThat(item.getTenantId()).isEqualTo(tenantId);
+ assertThat(item.getItemId()).isEqualTo(itemId);
+ assertThat(item.getItemVersionId()).isEqualTo(UUID.fromString(versionId));
+ assertThat(item.getVersion()).isEqualTo("1.0.1");
+ assertThat(item.getItemName()).isEqualTo("AM308");
+ assertThat(item.getItemType()).isEqualTo("DEVICE");
+ DeviceInstalledItemDescriptor descriptor = (DeviceInstalledItemDescriptor) item.getDescriptor();
+ assertThat(descriptor.getCreatedEntityIds()).containsExactly(profileId, integrationId, dashboardId);
+ assertThat(descriptor.getUsedExistingEntityIds()).containsExactly(integrationId);
+ assertThat(descriptor.getDashboardId()).isEqualTo(dashboardId);
+ Map state = descriptor.getInstallState();
+ assertThat(state.get("DEVICE_PROFILE:AM308 profile").get("entityOutput").get("id").asText()).isEqualTo(profileId.getId().toString());
+ assertThat(state.get("DEVICE_PROFILE:AM308 profile").get("checksum").isTextual()).isTrue();
+ assertThat(state.get("DASHBOARD:Dashboard").get("entityOutput").get("id").asText()).isEqualTo(dashboardId.getId().toString());
+ assertThat(state.get("DASHBOARD:Dashboard").get("checksum").isTextual()).isTrue();
+ assertThat(state.get("INTEGRATION:TTN").get("entityOutput").get("id").asText()).isEqualTo(integrationId.getId().toString());
+ assertThat(state.get("INTEGRATION:TTN").get("resolution").asText()).isEqualTo("use-existing");
+ assertThat(result.getDescriptor()).isSameAs(descriptor);
+ assertThat(result.getOutputs()).containsOnlyKeys("DEVICE_PROFILE:AM308 profile", "INTEGRATION:TTN", "DASHBOARD:Dashboard");
+ assertThat(afterCommitCalls).containsExactly("AUDIT", "AUDIT", "REPORT");
+ }
+
+ @Test
+ void installFailureOnALaterStepSavesNothing() {
+ mockInstall();
+ when(dashboardService.saveDashboard(any(Dashboard.class))).thenThrow(new DataValidationException("Dashboards limit reached"));
+
+ DevicePackageResult result = service.install(user, request(
+ create("AM308 profile", "DEVICE_PROFILE", JacksonUtil.newObjectNode().put("name", "milesight-iot-am308")),
+ create("Dashboard", "DASHBOARD", JacksonUtil.newObjectNode().put("title", "AM308 dashboard"))));
+
+ assertThat(result.isSuccess()).isFalse();
+ assertThat(result.getFailedStep()).isEqualTo("DASHBOARD:Dashboard");
+ assertThat(result.getErrorMessage()).isEqualTo("Dashboards limit reached");
+ assertThat(rolledBack).hasSize(1);
+ verify(installedItemService, never()).save(any(), any());
+ verifyNoInteractions(logEntityActionService, telemetryService);
+ verify(iotHubRestClient, never()).reportVersionInstalled(any(), any());
+ }
+
+ @Test
+ void installOverwriteOfAnExistingEntityNeedsAConfirmation() {
+ mockInstall();
+ when(dashboardService.findDashboardById(tenantId, dashboardId)).thenReturn(dashboard(7L));
+
+ DevicePackageResult result = service.install(user, request(
+ overwrite("Dashboard", "DASHBOARD", dashboardId, 7L, JacksonUtil.newObjectNode().put("title", "d"))));
+
+ assertThat(result.isSuccess()).isFalse();
+ assertThat(result.getErrorMessage()).isEqualTo("Overwriting an entity of another package needs a confirmation: Dashboard");
+ verify(transactionTemplate, never()).execute(any());
+ verify(dashboardService, never()).saveDashboard(any(Dashboard.class));
+ verify(installedItemService, never()).save(any(), any());
+ }
+
+ @Test
+ void installWithBadIntegrationCredentialsSavesNothing() throws Exception {
+ mockInstall();
+ doThrow(new ExecutionException(new IllegalStateException("Wrong API key")))
+ .when(tbIntegrationService).validateIntegrationConfiguration(eq(tenantId), any());
+
+ DevicePackageResult result = service.install(user, request(
+ create("TTN", "INTEGRATION", JacksonUtil.newObjectNode().put("name", "TTN").put("type", "TTN"))));
+
+ assertThat(result.isSuccess()).isFalse();
+ assertThat(result.getFailedStep()).isEqualTo("INTEGRATION:TTN");
+ assertThat(result.getErrorMessage()).isEqualTo("Wrong API key");
+ verify(transactionTemplate, never()).execute(any());
+ verify(installedItemService, never()).save(any(), any());
+ }
+
+ @Test
+ void installWhenHubIsUnavailableSavesNothing() {
+ mockInstall();
+ when(iotHubRestClient.getVersionInfo(versionId)).thenThrow(new RestClientException("Connection refused"));
+
+ DevicePackageResult result = service.install(user, request(
+ create("Dashboard", "DASHBOARD", JacksonUtil.newObjectNode().put("title", "AM308 dashboard"))));
+
+ assertThat(result.isSuccess()).isFalse();
+ assertThat(result.getErrorMessage()).isEqualTo("IoT Hub is unavailable. Try again later.");
+ verify(transactionTemplate, never()).execute(any());
+ verify(installedItemService, never()).save(any(), any());
+ }
+
+ @Test
+ void installReportsToTheHubAfterCommitAndIgnoresAReportFailure() {
+ mockInstall();
+ doAnswer(i -> {
+ recordAfterCommit("REPORT");
+ throw new RestClientException("Connection refused");
+ }).when(iotHubRestClient).reportVersionInstalled(eq(versionId), any());
+
+ DevicePackageResult result = service.install(user, request(
+ create("Dashboard", "DASHBOARD", JacksonUtil.newObjectNode().put("title", "AM308 dashboard"))));
+
+ assertThat(result.isSuccess()).isTrue();
+ InOrder order = inOrder(installedItemService, logEntityActionService, iotHubRestClient);
+ order.verify(installedItemService).save(eq(tenantId), any());
+ order.verify(logEntityActionService).logEntityAction(eq(tenantId), eq(dashboardId), any(), any(), eq(ActionType.ADDED), eq(user));
+ order.verify(iotHubRestClient).reportVersionInstalled(eq(versionId), any());
+ assertThat(afterCommitCalls).containsExactly("AUDIT", "REPORT");
+ }
+
+ @Test
+ void installRejectsAFromVersion() {
+ mockInstall();
+ DevicePackageRequest request = request(create("Dashboard", "DASHBOARD", JacksonUtil.newObjectNode().put("title", "d")));
+ request.setFromVersionId(installedVersionId);
+
+ DevicePackageResult result = service.install(user, request);
+
+ assertThat(result.isSuccess()).isFalse();
+ assertThat(result.getErrorMessage()).isEqualTo("Invalid install request");
+ verify(transactionTemplate, never()).execute(any());
+ verify(installedItemService, never()).save(any(), any());
+ }
+
+ @Test
+ void installKeepStepMustUseExisting() {
+ mockInstall();
+ DevicePackageRequest.Step integrationStep = keep("TTN", "INTEGRATION", integrationId);
+ integrationStep.setResolution("created");
+
+ DevicePackageResult result = service.install(user, request(integrationStep));
+
+ assertThat(result.isSuccess()).isFalse();
+ assertThat(result.getErrorMessage()).isEqualTo("Invalid install step: TTN");
+ verify(transactionTemplate, never()).execute(any());
+ verify(installedItemService, never()).save(any(), any());
+ }
+
+ @Test
+ void installRejectsAMalformedVersionId() {
+ mockInstall();
+ DevicePackageRequest request = request(create("Dashboard", "DASHBOARD", JacksonUtil.newObjectNode().put("title", "d")));
+ request.setVersionId("not-a-uuid");
+
+ DevicePackageResult result = service.install(user, request);
+
+ assertThat(result.isSuccess()).isFalse();
+ assertThat(result.getErrorMessage()).isEqualTo("Invalid install request");
+ verify(iotHubRestClient, never()).getVersionInfo(any());
+ verify(transactionTemplate, never()).execute(any());
+ }
+
+ @Test
+ void installAssignsTheCustomerToTheDeviceAndTheDashboard() {
+ mockInstall();
+ CustomerId customerId = customerOf(tenantId);
+ DevicePackageRequest request = request(
+ create("AM308", "DEVICE", JacksonUtil.newObjectNode().put("name", "AM308")),
+ create("Dashboard", "DASHBOARD", JacksonUtil.newObjectNode().put("title", "AM308 dashboard")));
+ request.setCustomerId(customerId.getId());
+
+ DevicePackageResult result = service.install(user, request);
+
+ assertThat(result.isSuccess()).isTrue();
+ ArgumentCaptor device = ArgumentCaptor.forClass(Device.class);
+ verify(deviceService).saveDevice(device.capture());
+ assertThat(device.getValue().getCustomerId()).isEqualTo(customerId);
+ ArgumentCaptor dashboard = ArgumentCaptor.forClass(Dashboard.class);
+ verify(dashboardService).saveDashboard(dashboard.capture());
+ assertThat(dashboard.getValue().getCustomerId()).isEqualTo(customerId);
+ }
+
+ @Test
+ void installAddsTheDeviceToTheEntityGroup() {
+ mockInstall();
+ EntityGroup group = new EntityGroup();
+ group.setId(new EntityGroupId(UUID.randomUUID()));
+ group.setType(EntityType.DEVICE);
+ group.setName("Warehouse sensors");
+ group.setOwnerId(tenantId);
+ when(entityGroupService.findEntityGroupById(tenantId, group.getId())).thenReturn(group);
+ DevicePackageRequest request = request(
+ create("AM308", "DEVICE", JacksonUtil.newObjectNode().put("name", "AM308")),
+ create("Dashboard", "DASHBOARD", JacksonUtil.newObjectNode().put("title", "AM308 dashboard")));
+ request.setEntityGroupId(group.getId().getId());
+
+ DevicePackageResult result = service.install(user, request);
+
+ assertThat(result.isSuccess()).isTrue();
+ verify(entityGroupService).addEntityToEntityGroup(tenantId, group.getId(), deviceId);
+ verify(entityGroupService, never()).addEntityToEntityGroup(any(), any(), eq(dashboardId));
+ assertThat(savedInTransaction).contains("ENTITY_GROUP");
+ verify(logEntityActionService).logEntityAction(eq(tenantId), eq(deviceId), any(Device.class), any(), eq(ActionType.ADDED_TO_ENTITY_GROUP),
+ eq(user), eq(deviceId.toString()), eq(group.getId().toString()), eq("Warehouse sensors"));
+ assertThat(afterCommitCalls).containsExactly("AUDIT", "AUDIT", "AUDIT", "REPORT");
+ }
+
+ @Test
+ void installRejectsACustomerOfAnotherTenant() {
+ mockInstall();
+ CustomerId customerId = customerOf(TenantId.fromUUID(UUID.randomUUID()));
+ DevicePackageRequest request = request(create("Dashboard", "DASHBOARD", JacksonUtil.newObjectNode().put("title", "d")));
+ request.setCustomerId(customerId.getId());
+
+ DevicePackageResult result = service.install(user, request);
+
+ assertThat(result.isSuccess()).isFalse();
+ assertThat(result.getErrorMessage()).isEqualTo("Invalid install request");
+ verify(transactionTemplate, never()).execute(any());
+ verify(installedItemService, never()).save(any(), any());
+ }
+
+ @Test
+ void updateIgnoresCustomerAndEntityGroup() {
+ when(dashboardService.findDashboardById(tenantId, dashboardId)).thenReturn(dashboard(7L));
+ when(dashboardService.saveDashboard(any(Dashboard.class))).thenAnswer(i -> i.getArgument(0));
+ DevicePackageRequest request = request(overwrite("Dashboard", "DASHBOARD", dashboardId, 7L, JacksonUtil.newObjectNode().put("title", "d")));
+ request.setCustomerId(UUID.randomUUID());
+ request.setEntityGroupId(UUID.randomUUID());
+
+ DevicePackageResult result = service.update(user, installedItem.getId(), request);
+
+ assertThat(result.isSuccess()).isTrue();
+ ArgumentCaptor dashboard = ArgumentCaptor.forClass(Dashboard.class);
+ verify(dashboardService).saveDashboard(dashboard.capture());
+ assertThat(dashboard.getValue().getCustomerId()).isNull();
+ verifyNoInteractions(customerService, entityGroupService);
+ }
+
+ @Test
+ void updateOverwriteOfACustomerDeviceThatChangesItsOwnerFails() {
+ DeviceId otherId = new DeviceId(UUID.randomUUID());
+ Device current = new Device(otherId);
+ current.setTenantId(tenantId);
+ current.setName("AM308 spare");
+ current.setCustomerId(customerOf(tenantId));
+ when(deviceService.findDeviceById(tenantId, otherId)).thenReturn(current);
+ DevicePackageRequest.Step step = overwrite("AM308 spare", "DEVICE", otherId, null, JacksonUtil.newObjectNode().put("name", "AM308 spare"));
+ step.setConfirmed(true);
+
+ DevicePackageResult result = service.update(user, installedItem.getId(), request(keep("AM308", "DEVICE", deviceId), step));
+
+ assertThat(result.isSuccess()).isFalse();
+ assertThat(result.getFailedStep()).isEqualTo("DEVICE:AM308 spare");
+ assertThat(result.getErrorMessage()).isEqualTo("AM308 spare belongs to another owner");
+ verify(deviceService, never()).saveDevice(any(Device.class));
+ verify(installedItemService, never()).save(any(), any());
+ }
+
+ @Test
+ void updateOverwriteOfAnotherDeviceKeepsItsCredentials() {
+ DeviceId otherId = new DeviceId(UUID.randomUUID());
+ Device current = new Device(otherId);
+ current.setTenantId(tenantId);
+ current.setName("AM308 spare");
+ when(deviceService.findDeviceById(tenantId, otherId)).thenReturn(current);
+ when(deviceService.saveDevice(any(Device.class))).thenAnswer(i -> i.getArgument(0));
+ DeviceCredentials credentials = new DeviceCredentials();
+ credentials.setDeviceId(otherId);
+ credentials.setCredentialsId("existing-token");
+ when(deviceCredentialsService.findDeviceCredentialsByDeviceId(tenantId, otherId)).thenReturn(credentials);
+ DevicePackageRequest.Step step = overwrite("AM308 spare", "DEVICE", otherId, null, JacksonUtil.newObjectNode().put("name", "AM308 spare"));
+ step.setConfirmed(true);
+ step.setCredentials(JacksonUtil.newObjectNode().put("credentialsType", "ACCESS_TOKEN").put("credentialsId", "package-token"));
+
+ DevicePackageResult result = service.update(user, installedItem.getId(), request(keep("AM308", "DEVICE", deviceId), step));
+
+ assertThat(result.isSuccess()).isTrue();
+ verify(deviceService).saveDevice(any(Device.class));
+ verify(deviceCredentialsService, never()).updateDeviceCredentials(any(), any());
+ assertThat(result.getOutputs().get("DEVICE:AM308 spare").get("token").asText()).isEqualTo("existing-token");
+ }
+
+ @Test
+ void installRejectsAnOverwriteOfADeviceOrGateway() {
+ mockInstall();
+ for (String type : new String[]{"DEVICE", "GATEWAY"}) {
+ DevicePackageRequest.Step step = overwrite("AM308", type, deviceId, 1L, JacksonUtil.newObjectNode().put("name", "AM308"));
+ step.setConfirmed(true);
+
+ DevicePackageResult result = service.install(user, request(step));
+
+ assertThat(result.isSuccess()).isFalse();
+ assertThat(result.getErrorMessage()).isEqualTo("Invalid install step: AM308");
+ }
+ verify(transactionTemplate, never()).execute(any());
+ verify(deviceService, never()).saveDevice(any(Device.class));
+ verify(installedItemService, never()).save(any(), any());
+ }
+
+ @Test
+ void installWritesStepAttributesOnAUsedExistingEntityAfterCommit() {
+ mockInstall();
+ DevicePackageRequest.Step deviceStep = keep("AM308", "DEVICE", deviceId);
+ deviceStep.setResolution("use-existing");
+ deviceStep.setServerAttributes(JacksonUtil.newObjectNode().put("model", "AM308"));
+ deviceStep.setSharedAttributes(JacksonUtil.newObjectNode().put("deviceId", "${device.id}"));
+
+ DevicePackageResult result = service.install(user, request(deviceStep,
+ create("Dashboard", "DASHBOARD", JacksonUtil.newObjectNode().put("title", "AM308 dashboard"))));
+
+ assertThat(result.isSuccess()).isTrue();
+ ArgumentCaptor saved = ArgumentCaptor.forClass(AttributesSaveRequest.class);
+ verify(telemetryService, times(2)).saveAttributes(saved.capture());
+ assertThat(saved.getAllValues()).extracting(AttributesSaveRequest::getEntityId).containsOnly(deviceId);
+ assertThat(saved.getAllValues()).extracting(AttributesSaveRequest::getScope).containsExactly(AttributeScope.SERVER_SCOPE, AttributeScope.SHARED_SCOPE);
+ assertThat(saved.getAllValues().get(0).getEntries().get(0).getValueAsString()).isEqualTo("AM308");
+ assertThat(saved.getAllValues().get(1).getEntries().get(0).getValueAsString()).isEqualTo(deviceId.getId().toString());
+ // The kept device isn't saved, so only the dashboard is audited
+ assertThat(afterCommitCalls).containsExactly("AUDIT", "ATTRIBUTES", "ATTRIBUTES", "REPORT");
+ }
+
+ @Test
+ void installIntoACustomerGroupGivesTheDeviceTheGroupsCustomer() {
+ mockInstall();
+ CustomerId groupCustomer = customerOf(tenantId);
+ EntityGroup group = new EntityGroup();
+ group.setId(new EntityGroupId(UUID.randomUUID()));
+ group.setType(EntityType.DEVICE);
+ group.setName("Customer sensors");
+ group.setOwnerId(groupCustomer);
+ when(entityGroupService.findEntityGroupById(tenantId, group.getId())).thenReturn(group);
+ DevicePackageRequest request = request(
+ create("AM308", "DEVICE", JacksonUtil.newObjectNode().put("name", "AM308")),
+ create("Dashboard", "DASHBOARD", JacksonUtil.newObjectNode().put("title", "AM308 dashboard")));
+ request.setEntityGroupId(group.getId().getId());
+
+ DevicePackageResult result = service.install(user, request);
+
+ assertThat(result.isSuccess()).isTrue();
+ ArgumentCaptor device = ArgumentCaptor.forClass(Device.class);
+ verify(deviceService).saveDevice(device.capture());
+ assertThat(device.getValue().getCustomerId()).isEqualTo(groupCustomer);
+ ArgumentCaptor dashboard = ArgumentCaptor.forClass(Dashboard.class);
+ verify(dashboardService).saveDashboard(dashboard.capture());
+ assertThat(dashboard.getValue().getOwnerId()).isEqualTo(tenantId);
+ verify(entityGroupService).addEntityToEntityGroup(tenantId, group.getId(), deviceId);
+ verify(logEntityActionService).logEntityAction(eq(tenantId), eq(deviceId), any(Device.class), eq(groupCustomer), eq(ActionType.ADDED), eq(user));
+ }
+
+ private CustomerId customerOf(TenantId owner) {
+ Customer customer = new Customer(new CustomerId(UUID.randomUUID()));
+ customer.setTenantId(owner);
+ when(customerService.findCustomerById(tenantId, customer.getId())).thenReturn(customer);
+ return customer.getId();
+ }
+
+ /** The new entities get these ids; each save records that it ran inside the transaction. */
+ private void mockInstall() {
+ when(user.getId()).thenReturn(new UserId(UUID.randomUUID()));
+ when(projectInfo.getProjectVersion()).thenReturn("4.4.1");
+ when(projectInfo.getProductType()).thenReturn("PE");
+ when(deviceProfileService.saveDeviceProfile(any())).thenAnswer(i -> {
+ recordSave("DEVICE_PROFILE");
+ DeviceProfile profile = i.getArgument(0);
+ profile.setId(profileId);
+ return profile;
+ });
+ when(dashboardService.saveDashboard(any(Dashboard.class))).thenAnswer(i -> {
+ recordSave("DASHBOARD");
+ Dashboard dashboard = i.getArgument(0);
+ dashboard.setId(dashboardId);
+ return dashboard;
+ });
+ when(deviceService.saveDevice(any(Device.class))).thenAnswer(i -> {
+ recordSave("DEVICE");
+ Device device = i.getArgument(0);
+ device.setId(deviceId);
+ return device;
+ });
+ doAnswer(i -> {
+ recordSave("ENTITY_GROUP");
+ return null;
+ }).when(entityGroupService).addEntityToEntityGroup(any(), any(), any());
+ when(installedItemService.save(any(), any())).thenAnswer(i -> {
+ recordSave("INSTALLED_ITEM");
+ return i.getArgument(1);
+ });
+ Integration integration = new Integration();
+ integration.setId(integrationId);
+ integration.setTenantId(tenantId);
+ integration.setName("TTN my-app");
+ when(integrationService.findIntegrationById(tenantId, integrationId)).thenReturn(integration);
+ doAnswer(i -> {
+ recordAfterCommit("AUDIT");
+ return null;
+ }).when(logEntityActionService).logEntityAction(any(TenantId.class), any(EntityId.class), any(HasName.class), nullable(CustomerId.class),
+ any(ActionType.class), any(User.class), any(Object[].class));
+ doAnswer(i -> {
+ recordAfterCommit("REPORT");
+ return null;
+ }).when(iotHubRestClient).reportVersionInstalled(any(), any());
+ doAnswer(i -> {
+ recordAfterCommit("ATTRIBUTES");
+ return null;
+ }).when(telemetryService).saveAttributes(any(AttributesSaveRequest.class));
+ }
+
+ private void recordSave(String what) {
+ if (inTransaction) {
+ savedInTransaction.add(what);
+ }
+ }
+
+ private void recordAfterCommit(String what) {
+ afterCommitCalls.add(inTransaction ? what + " in transaction" : what);
+ }
+
private IotHubInstalledItem otherPackage(Map installState) {
DeviceInstalledItemDescriptor descriptor = new DeviceInstalledItemDescriptor();
descriptor.setInstallState(installState);
@@ -875,35 +1355,35 @@ class DefaultDevicePackageUpdateServiceTest {
return dashboard;
}
- private DeviceUpdateRequest request(DeviceUpdateRequest.Step... steps) {
- DeviceUpdateRequest request = new DeviceUpdateRequest();
+ private DevicePackageRequest request(DevicePackageRequest.Step... steps) {
+ DevicePackageRequest request = new DevicePackageRequest();
request.setVersionId(versionId);
request.setSteps(List.of(steps));
return request;
}
- private static DeviceUpdateRequest.Step keep(String name, String type, EntityId id) {
- DeviceUpdateRequest.Step step = step(name, type, DeviceUpdateRequest.Action.KEEP);
+ private static DevicePackageRequest.Step keep(String name, String type, EntityId id) {
+ DevicePackageRequest.Step step = step(name, type, DevicePackageRequest.Action.KEEP);
step.setEntityId(id.getId());
return step;
}
- private static DeviceUpdateRequest.Step overwrite(String name, String type, EntityId id, Long version, ObjectNode entity) {
- DeviceUpdateRequest.Step step = step(name, type, DeviceUpdateRequest.Action.OVERWRITE);
+ private static DevicePackageRequest.Step overwrite(String name, String type, EntityId id, Long version, ObjectNode entity) {
+ DevicePackageRequest.Step step = step(name, type, DevicePackageRequest.Action.OVERWRITE);
step.setEntityId(id.getId());
step.setExpectedVersion(version);
step.setEntity(entity);
return step;
}
- private static DeviceUpdateRequest.Step create(String name, String type, ObjectNode entity) {
- DeviceUpdateRequest.Step step = step(name, type, DeviceUpdateRequest.Action.CREATE);
+ private static DevicePackageRequest.Step create(String name, String type, ObjectNode entity) {
+ DevicePackageRequest.Step step = step(name, type, DevicePackageRequest.Action.CREATE);
step.setEntity(entity);
return step;
}
- private static DeviceUpdateRequest.Step step(String name, String type, DeviceUpdateRequest.Action action) {
- DeviceUpdateRequest.Step step = new DeviceUpdateRequest.Step();
+ private static DevicePackageRequest.Step step(String name, String type, DevicePackageRequest.Action action) {
+ DevicePackageRequest.Step step = new DevicePackageRequest.Step();
step.setName(name);
step.setType(type);
step.setAction(action);
diff --git a/application/src/test/java/org/thingsboard/server/service/iot_hub/DefaultIotHubServiceTest.java b/application/src/test/java/org/thingsboard/server/service/iot_hub/DefaultIotHubServiceTest.java
index a81368450c..a7ac68bd8e 100644
--- a/application/src/test/java/org/thingsboard/server/service/iot_hub/DefaultIotHubServiceTest.java
+++ b/application/src/test/java/org/thingsboard/server/service/iot_hub/DefaultIotHubServiceTest.java
@@ -3,6 +3,10 @@
// SPDX-License-Identifier: Apache-2.0 AND BUSL-1.1
package org.thingsboard.server.service.iot_hub;
+import ch.qos.logback.classic.Level;
+import ch.qos.logback.classic.Logger;
+import ch.qos.logback.classic.spi.ILoggingEvent;
+import ch.qos.logback.core.read.ListAppender;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import jakarta.servlet.http.HttpServletRequest;
@@ -14,16 +18,37 @@ import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Spy;
import org.mockito.junit.jupiter.MockitoExtension;
+import org.slf4j.LoggerFactory;
import org.thingsboard.common.util.JacksonUtil;
import org.thingsboard.server.common.data.Device;
+import org.thingsboard.server.common.data.cf.CalculatedField;
+import org.thingsboard.server.common.data.cf.CalculatedFieldType;
+import org.thingsboard.server.common.data.cf.configuration.AlarmCalculatedFieldConfiguration;
+import org.thingsboard.server.common.data.cf.configuration.Argument;
+import org.thingsboard.server.common.data.cf.configuration.ArgumentType;
+import org.thingsboard.server.common.data.cf.configuration.ArgumentsBasedCalculatedFieldConfiguration;
+import org.thingsboard.server.common.data.cf.configuration.CalculatedFieldConfiguration;
+import org.thingsboard.server.common.data.cf.configuration.ReferencedEntityKey;
+import org.thingsboard.server.common.data.cf.configuration.SimpleCalculatedFieldConfiguration;
+import org.thingsboard.server.common.data.cf.configuration.TimeSeriesOutput;
+import org.thingsboard.server.common.data.cf.configuration.geofencing.EntityCoordinates;
+import org.thingsboard.server.common.data.cf.configuration.geofencing.GeofencingCalculatedFieldConfiguration;
+import org.thingsboard.server.common.data.cf.configuration.geofencing.GeofencingReportStrategy;
+import org.thingsboard.server.common.data.cf.configuration.geofencing.ZoneGroupConfiguration;
+import org.thingsboard.server.common.data.id.CalculatedFieldId;
import org.thingsboard.server.common.data.id.DashboardId;
import org.thingsboard.server.common.data.id.DeviceId;
import org.thingsboard.server.common.data.id.DeviceProfileId;
import org.thingsboard.server.common.data.id.EntityId;
import org.thingsboard.server.common.data.id.IntegrationId;
import org.thingsboard.server.common.data.id.IotHubInstalledItemId;
+import org.thingsboard.server.common.data.id.RuleChainId;
+import org.thingsboard.server.common.data.rule.RuleChain;
+import org.thingsboard.server.exception.DataValidationException;
import org.thingsboard.server.common.data.id.TenantId;
import org.thingsboard.server.common.data.integration.Integration;
+import org.thingsboard.server.common.data.iot_hub.AlarmRuleInstalledItemDescriptor;
+import org.thingsboard.server.common.data.iot_hub.CalculatedFieldInstalledItemDescriptor;
import org.thingsboard.server.common.data.iot_hub.DeviceInstalledItemDescriptor;
import org.thingsboard.server.common.data.iot_hub.IotHubInstalledItem;
import org.thingsboard.server.common.data.iot_hub.RuleChainInstalledItemDescriptor;
@@ -32,6 +57,7 @@ import org.thingsboard.server.common.data.DeviceProfile;
import org.thingsboard.server.common.data.converter.Converter;
import org.thingsboard.server.common.data.id.ConverterId;
import org.thingsboard.server.common.data.page.PageData;
+import org.thingsboard.server.dao.cf.CalculatedFieldService;
import org.thingsboard.server.dao.dashboard.DashboardService;
import org.thingsboard.server.dao.converter.ConverterService;
import org.thingsboard.server.dao.device.DeviceProfileService;
@@ -39,12 +65,16 @@ import org.thingsboard.server.dao.device.DeviceService;
import org.thingsboard.server.dao.entity.EntityService;
import org.thingsboard.server.dao.integration.IntegrationService;
import org.thingsboard.server.dao.iot_hub.IotHubInstalledItemService;
+import org.thingsboard.server.service.entitiy.cf.TbCalculatedFieldService;
+import org.thingsboard.server.dao.rule.RuleChainService;
import org.thingsboard.server.service.entitiy.dashboard.TbDashboardService;
import org.thingsboard.server.service.entitiy.converter.TbConverterService;
import org.thingsboard.server.service.entitiy.device.TbDeviceService;
import org.thingsboard.server.service.entitiy.device.profile.TbDeviceProfileService;
+import org.thingsboard.server.service.rule.TbRuleChainService;
import org.thingsboard.server.service.security.model.SecurityUser;
+import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Map;
import java.util.Optional;
@@ -60,6 +90,7 @@ import static org.mockito.Mockito.doNothing;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.inOrder;
+import static org.mockito.Mockito.lenient;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
@@ -76,6 +107,10 @@ class DefaultIotHubServiceTest {
@Mock
private IotHubInstalledItemService iotHubInstalledItemService;
@Mock
+ private TbCalculatedFieldService tbCalculatedFieldService;
+ @Mock
+ private CalculatedFieldService calculatedFieldService;
+ @Mock
private DeviceService deviceService;
@Mock
private EntityService entityService;
@@ -95,6 +130,12 @@ class DefaultIotHubServiceTest {
private ConverterService converterService;
@Mock
private TbConverterService tbConverterService;
+ @Mock
+ private DevicePackageEntities devicePackageEntities;
+ @Mock
+ private RuleChainService ruleChainService;
+ @Mock
+ private TbRuleChainService tbRuleChainService;
@Spy
@InjectMocks
@@ -459,6 +500,151 @@ class DefaultIotHubServiceTest {
assertThat(result.getErrorMessage()).contains("install failed");
}
+ @Test
+ void doInstallVersion_calculatedField_mapsTenantReferencesToInstallingTenant() throws Exception {
+ mockTenant();
+ String versionId = UUID.randomUUID().toString();
+ when(iotHubRestClient.getVersionInfo(versionId))
+ .thenReturn(version(versionId, UUID.randomUUID().toString(), "CALCULATED_FIELD", "CF", "1.0"));
+ when(iotHubRestClient.getVersionFileData(versionId)).thenReturn(calculatedFieldFileData());
+ when(tbCalculatedFieldService.save(any(), eq(user))).thenAnswer(invocation -> invocation.getArgument(0));
+ when(iotHubInstalledItemService.save(eq(tenantId), any())).thenAnswer(invocation -> invocation.getArgument(1));
+
+ service.doInstallVersion(user, versionId, null, null);
+
+ ArgumentCaptor captor = ArgumentCaptor.forClass(CalculatedField.class);
+ verify(tbCalculatedFieldService).save(captor.capture(), eq(user));
+ assertThat(((ArgumentsBasedCalculatedFieldConfiguration) captor.getValue().getConfiguration()).getArguments().get("T").getRefEntityId()).isEqualTo(tenantId);
+ }
+
+ @Test
+ void updateItemVersion_calculatedField_mapsTenantReferencesToInstallingTenant() throws Exception {
+ mockTenant();
+ String versionId = UUID.randomUUID().toString();
+ CalculatedFieldId calculatedFieldId = new CalculatedFieldId(UUID.randomUUID());
+ CalculatedFieldInstalledItemDescriptor descriptor = new CalculatedFieldInstalledItemDescriptor();
+ descriptor.setCalculatedFieldId(calculatedFieldId);
+ IotHubInstalledItem item = installedItem(UUID.randomUUID());
+ item.setItemType("CALCULATED_FIELD");
+ item.setItemVersionId(UUID.randomUUID());
+ item.setDescriptor(descriptor);
+ when(iotHubInstalledItemService.findById(tenantId, item.getId())).thenReturn(item);
+ when(iotHubRestClient.getVersionInfo(anyString()))
+ .thenReturn(version(versionId, UUID.randomUUID().toString(), "CALCULATED_FIELD", "CF", "2.0"));
+ when(iotHubRestClient.getVersionFileData(versionId)).thenReturn(calculatedFieldFileData());
+ CalculatedField existing = new CalculatedField(calculatedFieldId);
+ existing.setTenantId(tenantId);
+ when(calculatedFieldService.findById(tenantId, calculatedFieldId)).thenReturn(existing);
+
+ UpdateItemVersionResult result = service.updateItemVersion(user, item.getId(), versionId, true, null);
+
+ assertThat(result.isSuccess()).isTrue();
+ ArgumentCaptor captor = ArgumentCaptor.forClass(CalculatedField.class);
+ verify(tbCalculatedFieldService).save(captor.capture(), eq(user));
+ assertThat(((ArgumentsBasedCalculatedFieldConfiguration) captor.getValue().getConfiguration()).getArguments().get("T").getRefEntityId()).isEqualTo(tenantId);
+ }
+
+ @Test
+ void doInstallVersion_alarmRule_mapsTenantReferencesToInstallingTenant() throws Exception {
+ mockTenant();
+ String versionId = UUID.randomUUID().toString();
+ when(iotHubRestClient.getVersionInfo(versionId))
+ .thenReturn(version(versionId, UUID.randomUUID().toString(), "ALARM_RULE", "Alarm", "1.0"));
+ when(iotHubRestClient.getVersionFileData(versionId)).thenReturn(alarmRuleFileData());
+ when(tbCalculatedFieldService.save(any(), eq(user))).thenAnswer(invocation -> invocation.getArgument(0));
+ when(iotHubInstalledItemService.save(eq(tenantId), any())).thenAnswer(invocation -> invocation.getArgument(1));
+
+ service.doInstallVersion(user, versionId, null, null);
+
+ ArgumentCaptor captor = ArgumentCaptor.forClass(CalculatedField.class);
+ verify(tbCalculatedFieldService).save(captor.capture(), eq(user));
+ assertThat(((ArgumentsBasedCalculatedFieldConfiguration) captor.getValue().getConfiguration()).getArguments().get("T").getRefEntityId()).isEqualTo(tenantId);
+ }
+
+ @Test
+ void updateItemVersion_alarmRule_mapsTenantReferencesToInstallingTenant() throws Exception {
+ mockTenant();
+ String versionId = UUID.randomUUID().toString();
+ CalculatedFieldId calculatedFieldId = new CalculatedFieldId(UUID.randomUUID());
+ AlarmRuleInstalledItemDescriptor descriptor = new AlarmRuleInstalledItemDescriptor();
+ descriptor.setCalculatedFieldId(calculatedFieldId);
+ IotHubInstalledItem item = installedItem(UUID.randomUUID());
+ item.setItemType("ALARM_RULE");
+ item.setItemVersionId(UUID.randomUUID());
+ item.setDescriptor(descriptor);
+ when(iotHubInstalledItemService.findById(tenantId, item.getId())).thenReturn(item);
+ when(iotHubRestClient.getVersionInfo(anyString()))
+ .thenReturn(version(versionId, UUID.randomUUID().toString(), "ALARM_RULE", "Alarm", "2.0"));
+ when(iotHubRestClient.getVersionFileData(versionId)).thenReturn(alarmRuleFileData());
+ CalculatedField existing = new CalculatedField(calculatedFieldId);
+ existing.setTenantId(tenantId);
+ when(calculatedFieldService.findById(tenantId, calculatedFieldId)).thenReturn(existing);
+
+ UpdateItemVersionResult result = service.updateItemVersion(user, item.getId(), versionId, true, null);
+
+ assertThat(result.isSuccess()).isTrue();
+ ArgumentCaptor captor = ArgumentCaptor.forClass(CalculatedField.class);
+ verify(tbCalculatedFieldService).save(captor.capture(), eq(user));
+ assertThat(((ArgumentsBasedCalculatedFieldConfiguration) captor.getValue().getConfiguration()).getArguments().get("T").getRefEntityId()).isEqualTo(tenantId);
+ }
+
+ @Test
+ void doInstallVersion_geofencingCalculatedField_mapsZoneGroupTenantReferencesToInstallingTenant() throws Exception {
+ mockTenant();
+ String versionId = UUID.randomUUID().toString();
+ when(iotHubRestClient.getVersionInfo(versionId))
+ .thenReturn(version(versionId, UUID.randomUUID().toString(), "CALCULATED_FIELD", "Geofencing", "1.0"));
+ when(iotHubRestClient.getVersionFileData(versionId)).thenReturn(geofencingFileData());
+ when(tbCalculatedFieldService.save(any(), eq(user))).thenAnswer(invocation -> invocation.getArgument(0));
+ when(iotHubInstalledItemService.save(eq(tenantId), any())).thenAnswer(invocation -> invocation.getArgument(1));
+
+ service.doInstallVersion(user, versionId, null, null);
+
+ ArgumentCaptor captor = ArgumentCaptor.forClass(CalculatedField.class);
+ verify(tbCalculatedFieldService).save(captor.capture(), eq(user));
+ assertThat(((GeofencingCalculatedFieldConfiguration) captor.getValue().getConfiguration()).getZoneGroups().get("zones").getRefEntityId()).isEqualTo(tenantId);
+ }
+
+ private byte[] calculatedFieldFileData() {
+ SimpleCalculatedFieldConfiguration configuration = new SimpleCalculatedFieldConfiguration();
+ configuration.setArguments(Map.of("T", otherTenantArgument()));
+ configuration.setExpression("T");
+ return fileData(CalculatedFieldType.SIMPLE, configuration);
+ }
+
+ private byte[] alarmRuleFileData() {
+ AlarmCalculatedFieldConfiguration configuration = new AlarmCalculatedFieldConfiguration();
+ configuration.setArguments(Map.of("T", otherTenantArgument()));
+ configuration.setCreateRules(Map.of());
+ return fileData(CalculatedFieldType.ALARM, configuration);
+ }
+
+ private byte[] geofencingFileData() {
+ ZoneGroupConfiguration zoneGroup = new ZoneGroupConfiguration("perimeter", GeofencingReportStrategy.REPORT_PRESENCE_STATUS_ONLY, false);
+ zoneGroup.setRefEntityId(TenantId.fromUUID(UUID.randomUUID()));
+ GeofencingCalculatedFieldConfiguration configuration = new GeofencingCalculatedFieldConfiguration();
+ configuration.setEntityCoordinates(new EntityCoordinates("latitude", "longitude"));
+ configuration.setZoneGroups(Map.of("zones", zoneGroup));
+ configuration.setOutput(new TimeSeriesOutput());
+ return fileData(CalculatedFieldType.GEOFENCING, configuration);
+ }
+
+ private Argument otherTenantArgument() {
+ Argument argument = new Argument();
+ argument.setRefEntityId(TenantId.fromUUID(UUID.randomUUID()));
+ argument.setRefEntityKey(new ReferencedEntityKey("temperature", ArgumentType.TS_LATEST, null));
+ return argument;
+ }
+
+ private byte[] fileData(CalculatedFieldType type, CalculatedFieldConfiguration configuration) {
+ CalculatedField calculatedField = new CalculatedField();
+ calculatedField.setEntityId(new DeviceId(UUID.randomUUID()));
+ calculatedField.setType(type);
+ calculatedField.setName("CF");
+ calculatedField.setConfiguration(configuration);
+ return JacksonUtil.toString(calculatedField).getBytes(StandardCharsets.UTF_8);
+ }
+
@Test
void deleteInstalledItem_devicePackage_removesEachEntityBeforeWhatItRefersTo() throws Exception {
mockTenant();
@@ -467,6 +653,10 @@ class DefaultIotHubServiceTest {
profile.setDefaultDashboardId(dashboard.getId());
Integration integration = new Integration(new IntegrationId(UUID.randomUUID()));
Converter converter = new Converter(new ConverterId(UUID.randomUUID()));
+ profile.setTenantId(tenantId);
+ dashboard.setTenantId(tenantId);
+ integration.setTenantId(tenantId);
+ converter.setTenantId(tenantId);
// The profile and the integration listed first: in reverse order of creation, the dashboard would go before the
// profile that refers to it, and the converter before the integration that uses it.
IotHubInstalledItem deleted = devicePackage(profile.getId(), dashboard.getId(), integration.getId(), converter.getId());
@@ -474,6 +664,7 @@ class DefaultIotHubServiceTest {
when(iotHubInstalledItemService.findByTenantId(eq(tenantId), eq(List.of("DEVICE")), isNull(), any()))
.thenReturn(new PageData<>(List.of(deleted), 1, 1, false));
when(deviceProfileService.findDeviceProfileById(tenantId, profile.getId())).thenReturn(profile);
+ noDevices(profile.getId());
when(dashboardService.findDashboardById(tenantId, dashboard.getId())).thenReturn(dashboard);
when(integrationService.findIntegrationById(tenantId, integration.getId())).thenReturn(integration);
when(converterService.findConverterById(tenantId, converter.getId())).thenReturn(converter);
@@ -499,6 +690,7 @@ class DefaultIotHubServiceTest {
when(iotHubInstalledItemService.findByTenantId(eq(tenantId), eq(List.of("DEVICE")), isNull(), any()))
.thenReturn(new PageData<>(List.of(deleted, other), 1, 2, false));
Device device = new Device(deviceId);
+ device.setTenantId(tenantId);
when(deviceService.findDeviceById(tenantId, deviceId)).thenReturn(device);
service.deleteInstalledItem(user, deleted.getId());
@@ -604,6 +796,7 @@ class DefaultIotHubServiceTest {
mockTenant();
IntegrationId integrationId = new IntegrationId(UUID.randomUUID());
Converter converter = new Converter(new ConverterId(UUID.randomUUID()));
+ converter.setTenantId(tenantId);
when(converterService.findConverterById(tenantId, converter.getId())).thenReturn(converter);
IotHubInstalledItem deleted = devicePackage(converter.getId(), integrationId);
// The converter and the integration steps shared the name: the integration's state replaced the converter's
@@ -643,6 +836,12 @@ class DefaultIotHubServiceTest {
when(iotHubInstalledItemService.findById(tenantId, checked.getId())).thenReturn(checked);
when(iotHubInstalledItemService.findByTenantId(eq(tenantId), eq(List.of("DEVICE")), isNull(), any()))
.thenReturn(new PageData<>(List.of(checked, first, second, unrelated), 1, 4, false));
+ DeviceProfile sharedProfile = new DeviceProfile(sharedProfileId);
+ sharedProfile.setTenantId(tenantId);
+ when(deviceProfileService.findDeviceProfileById(tenantId, sharedProfileId)).thenReturn(sharedProfile);
+ Dashboard sharedDashboard = new Dashboard(sharedDashboardId);
+ sharedDashboard.setTenantId(tenantId);
+ when(dashboardService.findDashboardById(tenantId, sharedDashboardId)).thenReturn(sharedDashboard);
when(entityService.fetchEntityName(tenantId, sharedProfileId)).thenReturn(Optional.of("Shared profile"));
when(entityService.fetchEntityName(tenantId, sharedDashboardId)).thenReturn(Optional.of("Shared dashboard"));
@@ -665,6 +864,7 @@ class DefaultIotHubServiceTest {
when(iotHubInstalledItemService.findByTenantId(eq(tenantId), eq(List.of("DEVICE")), isNull(), any()))
.thenReturn(new PageData<>(List.of(deleted), 1, 1, false));
Device device = new Device(deviceId);
+ device.setTenantId(tenantId);
when(deviceService.findDeviceById(tenantId, deviceId)).thenReturn(device);
service.deleteInstalledItem(user, deleted.getId());
@@ -682,6 +882,9 @@ class DefaultIotHubServiceTest {
when(iotHubInstalledItemService.findById(tenantId, checked.getId())).thenReturn(checked);
when(iotHubInstalledItemService.findByTenantId(eq(tenantId), eq(List.of("DEVICE")), isNull(), any()))
.thenReturn(new PageData<>(List.of(checked), 1, 1, false));
+ Dashboard usersDashboard = new Dashboard(usersDashboardId);
+ usersDashboard.setTenantId(tenantId);
+ when(dashboardService.findDashboardById(tenantId, usersDashboardId)).thenReturn(usersDashboard);
when(entityService.fetchEntityName(tenantId, usersDashboardId)).thenReturn(Optional.of("My dashboard"));
InstalledItemKeptEntities kept = service.findKeptEntities(tenantId, checked.getId());
@@ -691,6 +894,59 @@ class DefaultIotHubServiceTest {
assertThat(kept.getUsedExistingCount()).isEqualTo(1);
}
+ @Test
+ void deleteInstalledItem_devicePackageInstalledBefore441_keepsEntitiesTheUserHadBefore() {
+ mockTenant();
+ DeviceId deviceId = new DeviceId(UUID.randomUUID());
+ DashboardId usersDashboardId = new DashboardId(UUID.randomUUID());
+ IotHubInstalledItem deleted = devicePackageInstalledBefore441(deviceId, usersDashboardId);
+ when(iotHubInstalledItemService.findById(tenantId, deleted.getId())).thenReturn(deleted);
+ when(iotHubInstalledItemService.findByTenantId(eq(tenantId), eq(List.of("DEVICE")), isNull(), any()))
+ .thenReturn(new PageData<>(List.of(deleted), 1, 1, false));
+ // Found, so only the use-existing rule keeps it
+ Dashboard usersDashboard = new Dashboard(usersDashboardId);
+ usersDashboard.setTenantId(tenantId);
+ lenient().when(dashboardService.findDashboardById(tenantId, usersDashboardId)).thenReturn(usersDashboard);
+ Device device = new Device(deviceId);
+ device.setTenantId(tenantId);
+ when(deviceService.findDeviceById(tenantId, deviceId)).thenReturn(device);
+
+ service.deleteInstalledItem(user, deleted.getId());
+
+ verify(tbDeviceService).delete(device, user);
+ verify(tbDashboardService, never()).delete(any(), any());
+ }
+
+ @Test
+ void findKeptEntities_devicePackageInstalledBefore441_namesTheEntitiesTheUserHadBefore() {
+ DeviceId deviceId = new DeviceId(UUID.randomUUID());
+ DashboardId usersDashboardId = new DashboardId(UUID.randomUUID());
+ IotHubInstalledItem checked = devicePackageInstalledBefore441(deviceId, usersDashboardId);
+ when(iotHubInstalledItemService.findById(tenantId, checked.getId())).thenReturn(checked);
+ when(iotHubInstalledItemService.findByTenantId(eq(tenantId), eq(List.of("DEVICE")), isNull(), any()))
+ .thenReturn(new PageData<>(List.of(checked), 1, 1, false));
+ Dashboard usersDashboard = new Dashboard(usersDashboardId);
+ usersDashboard.setTenantId(tenantId);
+ lenient().when(dashboardService.findDashboardById(tenantId, usersDashboardId)).thenReturn(usersDashboard);
+ when(entityService.fetchEntityName(tenantId, usersDashboardId)).thenReturn(Optional.of("My dashboard"));
+
+ InstalledItemKeptEntities kept = service.findKeptEntities(tenantId, checked.getId());
+
+ assertThat(kept.getEntities()).containsExactly(new InstalledItemKeptEntities.KeptEntity(usersDashboardId, "My dashboard"));
+ assertThat(kept.getUsedExistingCount()).isEqualTo(1);
+ }
+
+ /** An install made before 4.4.1: the dashboard the user took as it was is only in the install state, under the step name. */
+ private IotHubInstalledItem devicePackageInstalledBefore441(DeviceId deviceId, DashboardId usersDashboardId) {
+ IotHubInstalledItem installedItem = devicePackage(deviceId, usersDashboardId);
+ ObjectNode device = JacksonUtil.newObjectNode().put("resolution", "created");
+ device.set("entityOutput", JacksonUtil.newObjectNode().put("id", deviceId.getId().toString()));
+ ObjectNode dashboard = JacksonUtil.newObjectNode().put("resolution", "use-existing");
+ dashboard.set("entityOutput", JacksonUtil.newObjectNode().put("id", usersDashboardId.getId().toString()));
+ ((DeviceInstalledItemDescriptor) installedItem.getDescriptor()).setInstallState(Map.of("Device", device, "Dashboard", dashboard));
+ return installedItem;
+ }
+
@Test
void findKeptEntities_devicePackageSharingNothing_keepsNothing() {
IotHubInstalledItem checked = devicePackage(new DeviceId(UUID.randomUUID()));
@@ -736,6 +992,185 @@ class DefaultIotHubServiceTest {
return integration;
}
+ @Test
+ void findKeptEntities_devicePackage_namesTheProfileDevicesUseAndWhatItRefersTo_apartFromTheShared() {
+ DeviceProfile profile = new DeviceProfile(new DeviceProfileId(UUID.randomUUID()));
+ profile.setTenantId(tenantId);
+ RuleChain ruleChain = new RuleChain(new RuleChainId(UUID.randomUUID()));
+ ruleChain.setTenantId(tenantId);
+ RuleChainId ruleChainId = ruleChain.getId();
+ Dashboard dashboard = new Dashboard(new DashboardId(UUID.randomUUID()));
+ dashboard.setTenantId(tenantId);
+ DashboardId dashboardId = dashboard.getId();
+ profile.setDefaultRuleChainId(ruleChainId);
+ profile.setDefaultDashboardId(dashboardId);
+ // The user's, not the package's: not listed
+ profile.setDefaultEdgeRuleChainId(new RuleChainId(UUID.randomUUID()));
+ Device packageDevice = new Device(new DeviceId(UUID.randomUUID()));
+ packageDevice.setDeviceProfileId(profile.getId());
+ IotHubInstalledItem checked = devicePackage(ruleChainId, dashboardId, profile.getId(), packageDevice.getId());
+ when(iotHubInstalledItemService.findById(tenantId, checked.getId())).thenReturn(checked);
+ when(iotHubInstalledItemService.findByTenantId(eq(tenantId), eq(List.of("DEVICE")), isNull(), any()))
+ .thenReturn(new PageData<>(List.of(checked), 1, 1, false));
+ // 3 devices on the profile: the package's own, which the delete removes first, and 2 the integration created
+ when(deviceService.findDeviceIdsByTenantIdAndDeviceProfileId(eq(tenantId), eq(profile.getId()), any()))
+ .thenReturn(new PageData<>(List.of(), 3, 3, true));
+ when(deviceService.findDeviceById(tenantId, packageDevice.getId())).thenReturn(packageDevice);
+ when(deviceProfileService.findDeviceProfileById(tenantId, profile.getId())).thenReturn(profile);
+ when(ruleChainService.findRuleChainById(tenantId, ruleChainId)).thenReturn(ruleChain);
+ when(dashboardService.findDashboardById(tenantId, dashboardId)).thenReturn(dashboard);
+ when(entityService.fetchEntityName(tenantId, profile.getId())).thenReturn(Optional.of("smartico-l2-lr"));
+ when(entityService.fetchEntityName(tenantId, ruleChainId)).thenReturn(Optional.of("Smartico L2-LR"));
+ when(entityService.fetchEntityName(tenantId, dashboardId)).thenReturn(Optional.of("Smartico L2-LR Fleet"));
+
+ InstalledItemKeptEntities kept = service.findKeptEntities(tenantId, checked.getId());
+
+ // An update reads entities as shared with other packages: the profile is not among them
+ assertThat(kept.getEntities()).isEmpty();
+ assertThat(kept.getReferencedEntities()).containsExactly(
+ new InstalledItemKeptEntities.KeptEntity(profile.getId(), "smartico-l2-lr"),
+ new InstalledItemKeptEntities.KeptEntity(ruleChainId, "Smartico L2-LR"),
+ new InstalledItemKeptEntities.KeptEntity(dashboardId, "Smartico L2-LR Fleet"));
+ }
+
+ @Test
+ void findKeptEntities_devicePackage_aKeptDeviceKeepsItsProfile() {
+ DeviceProfileId profileId = new DeviceProfileId(UUID.randomUUID());
+ DeviceId sharedDeviceId = new DeviceId(UUID.randomUUID());
+ IotHubInstalledItem checked = devicePackage(profileId, sharedDeviceId);
+ IotHubInstalledItem other = devicePackage(sharedDeviceId);
+ when(iotHubInstalledItemService.findById(tenantId, checked.getId())).thenReturn(checked);
+ when(iotHubInstalledItemService.findByTenantId(eq(tenantId), eq(List.of("DEVICE")), isNull(), any()))
+ .thenReturn(new PageData<>(List.of(checked, other), 1, 2, false));
+ // The only device on the profile is the one another package uses: the delete keeps it, so it keeps the profile
+ when(deviceService.findDeviceIdsByTenantIdAndDeviceProfileId(eq(tenantId), eq(profileId), any()))
+ .thenReturn(new PageData<>(List.of(sharedDeviceId), 1, 1, false));
+
+ InstalledItemKeptEntities kept = service.findKeptEntities(tenantId, checked.getId());
+
+ assertThat(kept.getReferencedEntities()).extracting(InstalledItemKeptEntities.KeptEntity::getEntityId).containsExactly(profileId);
+ }
+
+ @Test
+ void findKeptEntities_devicePackage_aSharedProfileKeepsWhatItRefersTo() {
+ DeviceProfile profile = new DeviceProfile(new DeviceProfileId(UUID.randomUUID()));
+ RuleChainId ruleChainId = new RuleChainId(UUID.randomUUID());
+ RuleChainId edgeRuleChainId = new RuleChainId(UUID.randomUUID());
+ profile.setDefaultRuleChainId(ruleChainId);
+ profile.setDefaultEdgeRuleChainId(edgeRuleChainId);
+ IotHubInstalledItem checked = devicePackage(ruleChainId, edgeRuleChainId, profile.getId());
+ IotHubInstalledItem other = devicePackage(profile.getId());
+ when(iotHubInstalledItemService.findById(tenantId, checked.getId())).thenReturn(checked);
+ when(iotHubInstalledItemService.findByTenantId(eq(tenantId), eq(List.of("DEVICE")), isNull(), any()))
+ .thenReturn(new PageData<>(List.of(checked, other), 1, 2, false));
+ when(deviceProfileService.findDeviceProfileById(tenantId, profile.getId())).thenReturn(profile);
+
+ InstalledItemKeptEntities kept = service.findKeptEntities(tenantId, checked.getId());
+
+ assertThat(kept.getEntities()).extracting(InstalledItemKeptEntities.KeptEntity::getEntityId).containsExactly(profile.getId());
+ assertThat(kept.getReferencedEntities()).extracting(InstalledItemKeptEntities.KeptEntity::getEntityId)
+ .containsExactly(ruleChainId, edgeRuleChainId);
+ }
+
+ @Test
+ void deleteInstalledItem_devicePackage_keepsTheProfileDevicesUseAndWhatItRefersTo() throws Exception {
+ mockTenant();
+ DeviceProfile profile = new DeviceProfile(new DeviceProfileId(UUID.randomUUID()));
+ RuleChainId ruleChainId = new RuleChainId(UUID.randomUUID());
+ DashboardId dashboardId = new DashboardId(UUID.randomUUID());
+ profile.setDefaultRuleChainId(ruleChainId);
+ profile.setDefaultDashboardId(dashboardId);
+ IotHubInstalledItem deleted = devicePackage(ruleChainId, dashboardId, profile.getId());
+ when(iotHubInstalledItemService.findById(tenantId, deleted.getId())).thenReturn(deleted);
+ when(iotHubInstalledItemService.findByTenantId(eq(tenantId), eq(List.of("DEVICE")), isNull(), any()))
+ .thenReturn(new PageData<>(List.of(deleted), 1, 1, false));
+ when(deviceService.findDeviceIdsByTenantIdAndDeviceProfileId(eq(tenantId), eq(profile.getId()), any()))
+ .thenReturn(new PageData<>(List.of(new DeviceId(UUID.randomUUID())), 1, 1, false));
+ when(deviceProfileService.findDeviceProfileById(tenantId, profile.getId())).thenReturn(profile);
+
+ service.deleteInstalledItem(user, deleted.getId());
+
+ verify(tbDeviceProfileService, never()).delete(any(), any());
+ verify(tbRuleChainService, never()).delete(any(), any());
+ verify(tbDashboardService, never()).delete(any(), any());
+ verify(iotHubInstalledItemService).deleteById(tenantId, deleted.getId());
+ }
+
+ @Test
+ void deleteInstalledItem_devicePackage_aSharedProfileKeepsItsRuleChain() throws Exception {
+ mockTenant();
+ DeviceProfile profile = new DeviceProfile(new DeviceProfileId(UUID.randomUUID()));
+ RuleChainId ruleChainId = new RuleChainId(UUID.randomUUID());
+ profile.setDefaultRuleChainId(ruleChainId);
+ IotHubInstalledItem deleted = devicePackage(ruleChainId, profile.getId());
+ IotHubInstalledItem other = devicePackage(profile.getId());
+ when(iotHubInstalledItemService.findById(tenantId, deleted.getId())).thenReturn(deleted);
+ when(iotHubInstalledItemService.findByTenantId(eq(tenantId), eq(List.of("DEVICE")), isNull(), any()))
+ .thenReturn(new PageData<>(List.of(deleted, other), 1, 2, false));
+ when(deviceProfileService.findDeviceProfileById(tenantId, profile.getId())).thenReturn(profile);
+
+ service.deleteInstalledItem(user, deleted.getId());
+
+ verify(tbDeviceProfileService, never()).delete(any(), any());
+ verify(tbRuleChainService, never()).delete(any(), any());
+ }
+
+ @Test
+ void deleteInstalledItem_devicePackage_anEntitySomethingElseRefersToStays_loggedAsKept() throws Exception {
+ // A profile the user made after the install uses the package's rule chain
+ List logs = deleteRuleChainFailingWith(
+ new DataValidationException("The rule chain referenced by the device profiles cannot be deleted!"));
+
+ assertThat(logs).anySatisfy(event -> {
+ assertThat(event.getLevel()).isEqualTo(Level.INFO);
+ assertThat(event.getFormattedMessage()).contains("Kept RULE_CHAIN").contains("referenced by the device profiles");
+ });
+ assertThat(logs).noneMatch(event -> event.getLevel() == Level.ERROR);
+ }
+
+ @Test
+ void deleteInstalledItem_devicePackage_aFailedDelete_staysAnError() throws Exception {
+ List logs = deleteRuleChainFailingWith(new RuntimeException("Database is down"));
+
+ assertThat(logs).anySatisfy(event -> {
+ assertThat(event.getLevel()).isEqualTo(Level.ERROR);
+ assertThat(event.getFormattedMessage()).contains("Failed to delete device package entity");
+ });
+ }
+
+ /** Deletes a package whose only entity is a rule chain that fails to delete with {@code failure}; the service's logs. */
+ private List deleteRuleChainFailingWith(Exception failure) throws Exception {
+ mockTenant();
+ RuleChain ruleChain = new RuleChain(new RuleChainId(UUID.randomUUID()));
+ ruleChain.setTenantId(tenantId);
+ IotHubInstalledItem deleted = devicePackage(ruleChain.getId());
+ when(iotHubInstalledItemService.findById(tenantId, deleted.getId())).thenReturn(deleted);
+ when(iotHubInstalledItemService.findByTenantId(eq(tenantId), eq(List.of("DEVICE")), isNull(), any()))
+ .thenReturn(new PageData<>(List.of(deleted), 1, 1, false));
+ when(ruleChainService.findRuleChainById(tenantId, ruleChain.getId())).thenReturn(ruleChain);
+ doThrow(failure).when(tbRuleChainService).delete(ruleChain, user);
+ Logger logger = (Logger) LoggerFactory.getLogger(DefaultIotHubService.class);
+ ListAppender appender = new ListAppender<>();
+ appender.start();
+ logger.addAppender(appender);
+ Level level = logger.getLevel();
+ logger.setLevel(Level.INFO);
+ try {
+ service.deleteInstalledItem(user, deleted.getId());
+ } finally {
+ logger.setLevel(level);
+ logger.detachAppender(appender);
+ }
+ // The delete goes on either way
+ verify(iotHubInstalledItemService).deleteById(tenantId, deleted.getId());
+ return appender.list;
+ }
+
+ private void noDevices(DeviceProfileId profileId) {
+ when(deviceService.findDeviceIdsByTenantIdAndDeviceProfileId(eq(tenantId), eq(profileId), any()))
+ .thenReturn(new PageData<>(List.of(), 0, 0, false));
+ }
+
private IotHubInstalledItem devicePackage(EntityId... createdEntityIds) {
DeviceInstalledItemDescriptor descriptor = new DeviceInstalledItemDescriptor();
descriptor.setCreatedEntityIds(List.of(createdEntityIds));
@@ -744,4 +1179,184 @@ class DefaultIotHubServiceTest {
return item;
}
+ private Dashboard dashboard(TenantId owner) {
+ Dashboard dashboard = new Dashboard(new DashboardId(UUID.randomUUID()));
+ dashboard.setTenantId(owner);
+ return dashboard;
+ }
+
+ private Device device(TenantId owner) {
+ Device device = new Device(new DeviceId(UUID.randomUUID()));
+ device.setTenantId(owner);
+ return device;
+ }
+
+ private DeviceInstalledItemDescriptor devicePackageDescriptor(EntityId... createdEntityIds) {
+ DeviceInstalledItemDescriptor descriptor = new DeviceInstalledItemDescriptor();
+ descriptor.setCreatedEntityIds(List.of(createdEntityIds));
+ return descriptor;
+ }
+
+ @Test
+ void registerDeviceInstall_unknownEntity_rejectedAndNotSaved() {
+ mockTenant();
+ String versionId = UUID.randomUUID().toString();
+ when(iotHubRestClient.getVersionInfo(versionId))
+ .thenReturn(version(versionId, UUID.randomUUID().toString(), "DEVICE", "Pkg", "1.0"));
+ Device knownDevice = device(tenantId);
+ Dashboard unknownDashboard = dashboard(TenantId.fromUUID(UUID.randomUUID()));
+ when(deviceService.findDeviceById(tenantId, knownDevice.getId())).thenReturn(knownDevice);
+ when(dashboardService.findDashboardById(tenantId, unknownDashboard.getId())).thenReturn(unknownDashboard);
+
+ InstallItemVersionResult result = service.registerDeviceInstall(user, versionId,
+ devicePackageDescriptor(knownDevice.getId(), unknownDashboard.getId()));
+
+ assertThat(result.isSuccess()).isFalse();
+ verify(iotHubInstalledItemService, never()).save(any(), any());
+ verify(tbDeviceService, never()).delete(any(Device.class), any());
+ verify(tbDashboardService, never()).delete(any(Dashboard.class), any());
+ }
+
+ @Test
+ void registerDeviceInstall_unknownDashboardId_rejectedAndNotSaved() {
+ mockTenant();
+ String versionId = UUID.randomUUID().toString();
+ when(iotHubRestClient.getVersionInfo(versionId))
+ .thenReturn(version(versionId, UUID.randomUUID().toString(), "DEVICE", "Pkg", "1.0"));
+ Dashboard unknownDashboard = dashboard(TenantId.fromUUID(UUID.randomUUID()));
+ when(dashboardService.findDashboardById(tenantId, unknownDashboard.getId())).thenReturn(unknownDashboard);
+ DeviceInstalledItemDescriptor descriptor = devicePackageDescriptor();
+ descriptor.setDashboardId(unknownDashboard.getId());
+
+ InstallItemVersionResult result = service.registerDeviceInstall(user, versionId, descriptor);
+
+ assertThat(result.isSuccess()).isFalse();
+ verify(iotHubInstalledItemService, never()).save(any(), any());
+ }
+
+ @Test
+ void registerDeviceInstall_knownEntities_saved() {
+ mockTenant();
+ String versionId = UUID.randomUUID().toString();
+ when(iotHubRestClient.getVersionInfo(versionId))
+ .thenReturn(version(versionId, UUID.randomUUID().toString(), "DEVICE", "Pkg", "1.0"));
+ Device knownDevice = device(tenantId);
+ Dashboard knownDashboard = dashboard(tenantId);
+ when(deviceService.findDeviceById(tenantId, knownDevice.getId())).thenReturn(knownDevice);
+ when(dashboardService.findDashboardById(tenantId, knownDashboard.getId())).thenReturn(knownDashboard);
+ DeviceInstalledItemDescriptor descriptor = devicePackageDescriptor(knownDevice.getId(), knownDashboard.getId());
+ descriptor.setDashboardId(knownDashboard.getId());
+ when(iotHubInstalledItemService.save(eq(tenantId), any())).thenAnswer(inv -> inv.getArgument(1));
+
+ InstallItemVersionResult result = service.registerDeviceInstall(user, versionId, descriptor);
+
+ assertThat(result.isSuccess()).isTrue();
+ verify(iotHubInstalledItemService).save(eq(tenantId), any(IotHubInstalledItem.class));
+ }
+
+ @Test
+ void deleteInstalledItem_devicePackage_skipsEntityNotFound() throws Exception {
+ mockTenant();
+ Device knownDevice = device(tenantId);
+ Dashboard unknownDashboard = dashboard(TenantId.fromUUID(UUID.randomUUID()));
+ when(deviceService.findDeviceById(tenantId, knownDevice.getId())).thenReturn(knownDevice);
+ when(dashboardService.findDashboardById(tenantId, unknownDashboard.getId())).thenReturn(unknownDashboard);
+ UUID id = UUID.randomUUID();
+ IotHubInstalledItem item = installedItem(id);
+ item.setDescriptor(devicePackageDescriptor(knownDevice.getId(), unknownDashboard.getId()));
+ when(iotHubInstalledItemService.findById(tenantId, new IotHubInstalledItemId(id))).thenReturn(item);
+ when(iotHubInstalledItemService.findByTenantId(eq(tenantId), eq(List.of("DEVICE")), isNull(), any()))
+ .thenReturn(new PageData<>(List.of(item), 1, 1, false));
+
+ service.deleteInstalledItem(user, new IotHubInstalledItemId(id));
+
+ verify(tbDeviceService).delete(knownDevice, user);
+ verify(tbDashboardService, never()).delete(any(Dashboard.class), any());
+ verify(iotHubInstalledItemService).deleteById(tenantId, new IotHubInstalledItemId(id));
+ }
+
+ @Test
+ void deleteInstalledItem_devicePackage_deletesItsIntegrationAndConverter() throws Exception {
+ mockTenant();
+ Integration integration = new Integration(new IntegrationId(UUID.randomUUID()));
+ integration.setTenantId(tenantId);
+ Converter converter = new Converter(new ConverterId(UUID.randomUUID()));
+ converter.setTenantId(tenantId);
+ Integration unknownIntegration = new Integration(new IntegrationId(UUID.randomUUID()));
+ unknownIntegration.setTenantId(TenantId.fromUUID(UUID.randomUUID()));
+ when(integrationService.findIntegrationById(tenantId, integration.getId())).thenReturn(integration);
+ when(integrationService.findIntegrationById(tenantId, unknownIntegration.getId())).thenReturn(unknownIntegration);
+ when(converterService.findConverterById(tenantId, converter.getId())).thenReturn(converter);
+ UUID id = UUID.randomUUID();
+ IotHubInstalledItem item = installedItem(id);
+ item.setDescriptor(devicePackageDescriptor(converter.getId(), integration.getId(), unknownIntegration.getId()));
+ when(iotHubInstalledItemService.findById(tenantId, new IotHubInstalledItemId(id))).thenReturn(item);
+ when(iotHubInstalledItemService.findByTenantId(eq(tenantId), eq(List.of("DEVICE")), isNull(), any()))
+ .thenReturn(new PageData<>(List.of(item), 1, 1, false));
+
+ service.deleteInstalledItem(user, new IotHubInstalledItemId(id));
+
+ verify(integrationService).deleteIntegration(tenantId, integration.getId());
+ verify(integrationService, never()).deleteIntegration(tenantId, unknownIntegration.getId());
+ verify(tbConverterService).delete(converter, user);
+ verify(iotHubInstalledItemService).deleteById(tenantId, new IotHubInstalledItemId(id));
+ }
+
+ @Test
+ void registerDeviceInstall_usedExistingEntityOfAnotherTenant_rejectedAndNotSaved() {
+ mockTenant();
+ String versionId = UUID.randomUUID().toString();
+ when(iotHubRestClient.getVersionInfo(versionId))
+ .thenReturn(version(versionId, UUID.randomUUID().toString(), "DEVICE", "Pkg", "1.0"));
+ Device knownDevice = device(tenantId);
+ when(deviceService.findDeviceById(tenantId, knownDevice.getId())).thenReturn(knownDevice);
+ Dashboard otherTenantDashboard = dashboard(TenantId.fromUUID(UUID.randomUUID()));
+ when(dashboardService.findDashboardById(tenantId, otherTenantDashboard.getId())).thenReturn(otherTenantDashboard);
+ DeviceInstalledItemDescriptor descriptor = devicePackageDescriptor(knownDevice.getId());
+ descriptor.setUsedExistingEntityIds(List.of(otherTenantDashboard.getId()));
+
+ InstallItemVersionResult result = service.registerDeviceInstall(user, versionId, descriptor);
+
+ assertThat(result.isSuccess()).isFalse();
+ verify(iotHubInstalledItemService, never()).save(any(), any());
+ }
+
+ @Test
+ void deleteInstalledItem_devicePackage_leavesTheIntegrationOfAnotherTenantAsItIs() {
+ mockTenant();
+ IntegrationId integrationId = new IntegrationId(UUID.randomUUID());
+ IotHubInstalledItem deleted = devicePackage(integrationId);
+ setIntegrationState(deleted, integrationId, Map.of("profile.milesight-iot-am308", "am308-custom"));
+ ((DeviceInstalledItemDescriptor) deleted.getDescriptor()).setUsedExistingEntityIds(List.of(integrationId));
+ when(iotHubInstalledItemService.findById(tenantId, deleted.getId())).thenReturn(deleted);
+ when(iotHubInstalledItemService.findByTenantId(eq(tenantId), eq(List.of("DEVICE")), isNull(), any()))
+ .thenReturn(new PageData<>(List.of(deleted), 1, 1, false));
+ Integration otherTenantIntegration = integration(integrationId, Map.of("profile.milesight-iot-am308", "am308-custom"));
+ otherTenantIntegration.setTenantId(TenantId.fromUUID(UUID.randomUUID()));
+ when(integrationService.findIntegrationById(tenantId, integrationId)).thenReturn(otherTenantIntegration);
+
+ service.deleteInstalledItem(user, deleted.getId());
+
+ verify(integrationService, never()).saveIntegration(any());
+ verify(integrationService, never()).deleteIntegration(any(), any());
+ }
+
+ @Test
+ void findKeptEntities_devicePackage_namesNoEntityOfAnotherTenant() {
+ DashboardId otherTenantDashboardId = new DashboardId(UUID.randomUUID());
+ IotHubInstalledItem checked = devicePackage(new DeviceId(UUID.randomUUID()), otherTenantDashboardId);
+ ((DeviceInstalledItemDescriptor) checked.getDescriptor()).setUsedExistingEntityIds(List.of(otherTenantDashboardId));
+ when(iotHubInstalledItemService.findById(tenantId, checked.getId())).thenReturn(checked);
+ when(iotHubInstalledItemService.findByTenantId(eq(tenantId), eq(List.of("DEVICE")), isNull(), any()))
+ .thenReturn(new PageData<>(List.of(checked), 1, 1, false));
+ Dashboard otherTenantDashboard = new Dashboard(otherTenantDashboardId);
+ otherTenantDashboard.setTenantId(TenantId.fromUUID(UUID.randomUUID()));
+ when(dashboardService.findDashboardById(tenantId, otherTenantDashboardId)).thenReturn(otherTenantDashboard);
+
+ InstalledItemKeptEntities kept = service.findKeptEntities(tenantId, checked.getId());
+
+ assertThat(kept.getEntities()).containsExactly(new InstalledItemKeptEntities.KeptEntity(otherTenantDashboardId, null));
+ verify(entityService, never()).fetchEntityName(any(), any());
+ }
+
}
diff --git a/application/src/test/java/org/thingsboard/server/service/mail/TbMailSenderTest.java b/application/src/test/java/org/thingsboard/server/service/mail/TbMailSenderTest.java
index dcac2daf1a..ecc373e796 100644
--- a/application/src/test/java/org/thingsboard/server/service/mail/TbMailSenderTest.java
+++ b/application/src/test/java/org/thingsboard/server/service/mail/TbMailSenderTest.java
@@ -21,6 +21,7 @@ import java.util.Properties;
import java.util.UUID;
import java.util.stream.Stream;
+import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertSame;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.ArgumentMatchers.any;
@@ -63,6 +64,21 @@ public class TbMailSenderTest {
verify(tbMailSender, times(1)).testConnectionSuper();
}
+ @Test
+ public void testServerIdentityCheckIsDisabled() {
+ var json = JacksonUtil.newObjectNode();
+ json.put("smtpProtocol", "smtps");
+ json.put("smtpHost", "10.0.0.1");
+ json.put("smtpPort", "465");
+ json.put("timeout", "10000");
+ json.put("username", "");
+ json.put("enableTls", true);
+
+ TbMailSender sender = new TbMailSender(null, TenantId.SYS_TENANT_ID, json);
+
+ assertEquals("false", sender.getJavaMailProperties().getProperty("mail.smtps.ssl.checkserveridentity"));
+ }
+
@Test
public void testGiveMailTenantSettings_noFallbackToSystem() {
var json = JacksonUtil.newObjectNode();
diff --git a/application/src/test/java/org/thingsboard/server/service/notification/NotificationApiTest.java b/application/src/test/java/org/thingsboard/server/service/notification/NotificationApiTest.java
index 9b91c00669..fc79a220d6 100644
--- a/application/src/test/java/org/thingsboard/server/service/notification/NotificationApiTest.java
+++ b/application/src/test/java/org/thingsboard/server/service/notification/NotificationApiTest.java
@@ -1123,6 +1123,42 @@ public class NotificationApiTest extends AbstractNotificationApiTest {
assertThat(getAvailableDeliveryMethods()).doesNotContain(NotificationDeliveryMethod.MOBILE_APP);
}
+ @Test
+ public void testNotificationRequest_templateOfOtherTenant_returnsBadRequest() throws Exception {
+ loginDifferentTenant();
+ NotificationTemplate otherTemplate = createNotificationTemplate(NotificationType.GENERAL, "Subject", "Text", NotificationDeliveryMethod.WEB);
+ loginTenantAdmin();
+ NotificationTarget target = createNotificationTarget(tenantAdminUserId);
+ long requestsCount = findNotificationRequests().getTotalElements();
+
+ NotificationRequest notificationRequest = NotificationRequest.builder()
+ .targets(List.of(target.getUuidId()))
+ .templateId(otherTemplate.getId())
+ .additionalConfig(new NotificationRequestConfig())
+ .build();
+ doPost("/api/notification/request", notificationRequest).andExpect(status().isBadRequest());
+
+ assertThat(findNotificationRequests().getTotalElements()).isEqualTo(requestsCount);
+ }
+
+ @Test
+ public void testNotificationRequest_systemTemplate_isDelivered() throws Exception {
+ loginSysAdmin();
+ NotificationTemplate systemTemplate = createNotificationTemplate(NotificationType.GENERAL, "Subject", "Text", NotificationDeliveryMethod.WEB);
+ loginTenantAdmin();
+ NotificationTarget target = createNotificationTarget(tenantAdminUserId);
+
+ NotificationRequest notificationRequest = NotificationRequest.builder()
+ .tenantId(tenantId)
+ .templateId(systemTemplate.getId())
+ .originatorEntityId(tenantAdminUserId)
+ .targets(List.of(target.getUuidId()))
+ .build();
+ NotificationRequestStats stats = submitNotificationRequestAndWait(notificationRequest);
+ assertThat(stats.getErrors()).isEmpty();
+ assertThat(stats.getSent().get(NotificationDeliveryMethod.WEB).get()).isOne();
+ }
+
private NotificationRequestStats submitNotificationRequestAndWait(NotificationRequest notificationRequest) throws Exception {
SettableFuture